AdBlock Detected!
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.
SQL UNION |
|
SQL > Advanced SQL >
Union
The purpose of the SQL UNION query is to combine the results of two queries together while removing duplicates. In other words, when using UNION, only unique values are returned (similar to SELECT DISTINCT).
Key Takeaway: UNION stacks the results of two SELECT queries on top of each other and removes duplicate rows. Both queries must return the same number of columns with compatible data types.
SyntaxThe syntax of UNION in SQL is as follows: The columns selected in [SQL Statement 1] and [SQL Statement 2] need to be of the same data type for UNION to work. ExampleWe use the following tables for our example. Table Store_Information
Table Internet_Sales
To find all the dates where there is a sales transaction, we use the following SQL statement: Result:
Please note that if we type "SELECT DISTINCT Txn_Date" for either or both of the SQL statement, we will get the same result set. Frequently Asked QuestionsWhen should I use UNION vs JOIN?Use UNION to stack rows from two queries vertically (same columns, different rows). Use JOIN to combine columns horizontally from two tables. They solve different problems: UNION expands the row count, JOIN expands the column count. Why does Jan-07-1999 appear only once in the result even though it's in both tables?Because UNION removes duplicates. Jan-07-1999 appears in Store_Information AND Internet_Sales, but UNION returns it only once. Use UNION ALL to see it twice. Can I UNION more than two queries?Yes. You can chain multiple UNIONs: Does UNION preserve the original row order?No. The order of rows in a UNION result is not guaranteed unless you add an ORDER BY clause at the end of the full UNION statement.
|
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.