WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

SQL & Databases Β· Intermediate Β· question 35 of 100

What is the difference between UNION and UNION ALL, and when would you use each?

πŸ“• Buy this interview preparation book: 100 SQL & Databases questions & answers β€” PDF + EPUB for $5

In SQL, the UNION and UNION ALL operators are used to combine the results of two or more SELECT statements into a single result set. While both operators can be used to achieve the same result, there are some important differences between them.

The UNION operator is used to combine the results of two or more SELECT statements into a single result set, removing any duplicate rows that appear in the result set. Here is an example of the UNION operator:

SELECT name, age, gender
FROM employees
UNION
SELECT name, age, gender
FROM contractors;

In this example, the UNION operator is used to combine the results of two SELECT statements that retrieve data from the "employees" and "contractors" tables. The result set will include only distinct rows, removing any duplicates that appear in both tables.

The UNION ALL operator, on the other hand, is used to combine the results of two or more SELECT statements into a single result set, including all rows, even if they are duplicates. Here is an example of the UNION ALL operator:

SELECT name, age, gender
FROM employees
UNION ALL
SELECT name, age, gender
FROM contractors;

In this example, the UNION ALL operator is used to combine the results of two SELECT statements that retrieve data from the "employees" and "contractors" tables. The result set will include all rows from both tables, even if they are duplicates.

When deciding which operator to use, it is important to consider the nature of the data being retrieved and the requirements of the query. If duplicates are not allowed and should be removed from the result set, the UNION operator is appropriate. If duplicates are allowed and should be included in the result set, the UNION ALL operator is appropriate.

Overall, the UNION and UNION ALL operators are useful tools for combining data from multiple tables or queries into a single result set, and understanding the differences between them is essential for writing efficient and effective SQL queries.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic SQL & Databases interview β€” then scores it.
πŸ“ž Practice SQL & Databases β€” free 15 min
πŸ“• Buy this interview preparation book: 100 SQL & Databases questions & answers β€” PDF + EPUB for $5

All 100 SQL & Databases questions Β· All topics