SQL union all

Created By: chatGPT

The SQL UNION ALL operator is used to combine the results of two or more SELECT statements. Unlike UNION, it does not remove duplicates—meaning it will include every row from each SELECT statement, even if some rows are identical. This can be useful when you want to keep all occurrences of data from different sources.

Basic Syntax:

When using UNION ALL, the SELECT statements must have the same number of columns in the result sets with similar data types. Here's a basic example of its syntax:

SELECT column1, column2
FROM table1
UNION ALL
SELECT column1, column2
FROM table2;

In this example, we are selecting column1 and column2 from table1 and table2. The records from both tables will be combined, including any duplicates that exist between them.

Example Scenario:

Suppose you have two tables, sales_2022 and sales_2023, both having columns for sale amounts, you can use UNION ALL to get a comprehensive view of sales for both years.

SELECT sale_amount
FROM sales_2022
UNION ALL
SELECT sale_amount
FROM sales_2023;

This query will return all sale amounts from both years, allowing for any duplicate sale amounts to appear multiple times in the result set.

Important Notes:

  • Keep in mind that using UNION ALL will generally be faster than using UNION due to the lack of duplicate checking.
  • Always ensure that the number of columns and their data types are the same in each SELECT statement to avoid errors.
-- Example with different column counts will generate an error
SELECT column1
FROM table1
UNION ALL
SELECT column1, column2
FROM table2;
Introduction And SetupSelectFromWhereJoinInner JoinLeft JoinRight JoinFull JoinOnGroup ByHavingOrder ByLimitInsert IntoValuesUpdateSetDeleteCreate TableAlter TableDrop TableCreate IndexDrop IndexUnionUnion AllIntersectExceptCaseWhenThenElseEndInBetweenLikeIs NullIs Not NullExistsNot ExistsAndOrNotAsWithDistinctCountSumAvgMinMaxCastCoalesceNullifSubstringConcatLowerUpperTrimReplaceRoundFloorCeilAbsModCurrent_dateCurrent_timeCurrent_timestamp