Home / code / sql

Union

With this you make a combined query, where the results of 2 or more independent query's or tables are added.
[TABLE] query1 UNION [ALL] [TABLE] query2 [UNION [ALL.]
[TABLE] queryN [...]]

Part Explanation
query1 - N A select instruction, name of the query or table. With TABLE in front.

SELECT * FROM table WHERE field=1
UNION
SELECT * FROM table WHERE field=5

Selects all records where the value of the field is 1 or 5.

All records are only shown once:
SELECT * FROM table
UNION
SELECT * FROM table

All query's in a UNION must request the same number of fields, they do not have to be of the same data-type.

Alias can only be used in the first select-component, cause they are regenerated in the following. ORDER BY-component must point at the same names as the names used in the first SELECT-statement.

You can add a GROUP BY and/or HAVING-component in every query-argument to group the results.

At the end of the last query-argument, you can add a ORDER BY-component to show the results in sequence.

 

TOP

Latest script:

 

Books: