The UNION keyword in SQL is used to combine the results of two or more SELECT queries into a single result set. It eliminates duplicate records, returning only distinct rows from the combined queries.
Syntax:
SELECT column1, column2, ...
FROM table1
WHERE condition
UNION
SELECT column1, column2, ...
FROM table2
WHERE condition;
Important Points:
- Number of Columns: The
SELECTstatements combined withUNIONmust have the same number of columns, and the columns must have compatible data types. - Order of Columns: The order of columns in each
SELECTstatement should be the same. - Distinct Values: By default,
UNIONremoves duplicate rows. If you want to include duplicates, useUNION ALL. - Column Names: The column names in the result set will be taken from the first
SELECTstatement.
Example:
Suppose you have two tables, employees and contractors, with the same structure (columns for id, name, and role).
SELECT id, name, role
FROM employees
UNION
SELECT id, name, role
FROM contractors;
This query combines employees and contractors into a single result set without duplicates.
If you want to include duplicates, you can use UNION ALL:
SELECT id, name, role
FROM employees
UNION ALL
SELECT id, name, role
FROM contractors;
This query will include all rows from both employees and contractors, including any duplicates.
No comments:
Post a Comment