Add row to query result using select
157,061
Solution 1
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
Solution 2
In SQL Server, you would say:
Select name from users
UNION [ALL]
SELECT 'JASON'
In Oracle, you would say
Select name from user
UNION [ALL]
Select 'JASON' from DUAL
Solution 3
is it possible to extend query results with literals like this?
Yes.
Select Name
From Customers
UNION ALL
Select 'Jason'
- Use
UNION
to add Jason if it isn't already in the result set. - Use
UNION ALL
to add Jason whether or not he's already in the result set.
Related videos on Youtube
Author by
Deduplicator
Updated on July 05, 2022Comments
-
Deduplicator almost 2 years
Is it possible to extend query results with literals like this?
select name from users union select name from ('JASON');
or
select age, name from users union select age, name from (25,'Betty');
so it returns all the names in the table plus 'JASON', or (25,'Betty').
-
Admin about 15 yearsI'm using sql server 2005 and running a simple union like my first example, but I get "Incorrect Syntax". Is it explicitly like my example?
-
Joel Coehoorn about 15 yearsHe specified sql server: "from dual" is oracle only
-
Yeonho about 13 yearsshouldnt the brackets around ALL be omitted for SQL Server?
-
Rich.Carpenter about 13 yearsThe brackets around ALL here are indicating it's an optional element.
-
ALvin Das over 9 yearsHow would you always return 'Jason' as the first item in the return Union list?
-
Alex over 3 yearsDo I have to union them one by one? Is there a way to add multiple rows at the same time?
-
Quassnoi over 3 years@Alex: In SQL Server and PostgreSQL, you can do
SELECT age, name FROM users UNION SELECT * FROM (VALUES (25, 'Betty'), (26, 'Fatty')) q(age, name)