UNION and UNION ALL

Estimated reading: 1 minute 13 views

1. What is the difference between UNION and UNION ALL?

  • UNION: Combines the results of two or more queries and removes duplicate rows from the final result set.
  • UNION ALL: Combines results without removing duplicates, keeping all rows from each query, including duplicates.
    Key Difference: UNION performs deduplication, which can impact performance, while UNION ALL is faster but allows duplicates.

2. Write a query to combine the results of two queries using UNION.

Example: Combine a list of employees from two departments.

				
					SELECT name 
FROM employees 
WHERE department_id = 1
UNION
SELECT name 
FROM employees 
WHERE department_id = 2;

				
			

3. Can you use ORDER BY with a UNION query? Explain.

Yes, ORDER BY can be used, but it must be placed after all UNION operations, as it applies to the combined result set, not individual queries.

Example:

				
					SELECT name 
FROM employees 
WHERE department_id = 1
UNION
SELECT name 
FROM employees 
WHERE department_id = 2
ORDER BY name;

				
			

Key Note: To sort individual queries before combining, use ORDER BY within subqueries, but this does not affect the final order.

Leave a Comment

Share this Doc

UNION and UNION ALL

Or copy link

CONTENTS