SQL Queries and Set Operations


SQL Queries and Set Operations Interview with follow-up questions

1. What is a SQL query and how is it used?

A SQL query is a statement written in SQL that instructs the database to perform an operation — most commonly retrieving data, but also inserting, updating, deleting, or modifying database structure.

Anatomy of a SELECT query (the most common type):

SELECT   department, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM     employees
JOIN     departments ON employees.department_id = departments.id
WHERE    hire_date >= '2020-01-01'
GROUP BY department
HAVING   COUNT(*) > 5
ORDER BY avg_salary DESC
LIMIT    10;

How a query is used:

  1. Data retrieval: The primary use — pulling specific rows and columns based on conditions
  2. Reporting and aggregation: Using GROUP BY, COUNT, SUM, AVG, MIN, MAX to summarize data
  3. Data modification: INSERT, UPDATE, DELETE statements also qualify as queries
  4. Subqueries and CTEs: Queries nested inside other queries or defined with WITH for readability
  5. Joins: Combining data from multiple related tables in a single query

Query types beyond SELECT:

-- DML queries
INSERT INTO orders (customer_id, total) VALUES (1, 150.00);
UPDATE products SET price = price * 1.05 WHERE category = 'Electronics';
DELETE FROM sessions WHERE expired_at < NOW();

-- DDL queries
CREATE TABLE new_table (...);
ALTER TABLE employees ADD COLUMN phone VARCHAR(20);

Interview framing: When asked this question, demonstrate that you know queries go beyond SELECT and that you understand the logical execution order of a SELECT statement (FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT).

↑ Back to top

Follow-up 1

Can you write a basic SQL query?

Sure! Here's an example of a basic SQL query to retrieve all records from a table:

SELECT * FROM table_name;

Follow-up 2

What are some common SQL functions used in queries?

There are many SQL functions that can be used in queries, but some common ones include:

  • COUNT(): Returns the number of rows that match a specified condition.
  • SUM(): Calculates the sum of a column's values.
  • AVG(): Calculates the average of a column's values.
  • MAX(): Returns the maximum value in a column.
  • MIN(): Returns the minimum value in a column.
  • UPPER(): Converts a string to uppercase.
  • LOWER(): Converts a string to lowercase.
  • CONCAT(): Concatenates two or more strings.
  • SUBSTRING(): Extracts a substring from a string.
  • DATE(): Extracts the date part from a datetime value.
  • NOW(): Returns the current date and time.

These are just a few examples, and there are many more SQL functions available depending on the database system you are using.

Follow-up 3

What is the difference between a query and a subquery?

A query is a standalone SQL statement that retrieves data from one or more tables. It can be used to perform various operations such as filtering, sorting, and aggregating data.

On the other hand, a subquery is a query that is nested inside another query. It is used to retrieve data that is based on the result of another query. The result of a subquery can be used as a condition or value in the outer query.

In summary, a query is used to retrieve data directly from tables, while a subquery is used to retrieve data based on the result of another query.

2. What are set operations in SQL?

Set operations in SQL combine the result sets of two or more SELECT queries into a single result. All set operations require that both queries return the same number of columns with compatible data types.

The four set operations:

UNION — all rows from both queries, duplicates removed

SELECT city FROM customers
UNION
SELECT city FROM suppliers;

UNION ALL — all rows from both queries, duplicates kept (faster than UNION)

SELECT product_id FROM orders_2024
UNION ALL
SELECT product_id FROM orders_2025;

INTERSECT — only rows that appear in BOTH result sets

SELECT customer_id FROM orders_2024
INTERSECT
SELECT customer_id FROM orders_2025;
-- customers who ordered in both years

EXCEPT (or MINUS in Oracle) — rows from the first query that do NOT appear in the second

SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;
-- customers who have never placed an order

Rules:

  • Column count must match between both SELECT statements
  • Data types must be compatible (or implicitly convertible)
  • Column names in the result come from the first SELECT
  • ORDER BY can only appear once, at the very end, and applies to the final result

Performance note: UNION performs a sort/deduplicate step. UNION ALL skips this — use it when you know there are no duplicates or duplicates are acceptable, as it is significantly faster.

MySQL note: MySQL does not support INTERSECT or EXCEPT natively prior to MySQL 8.0.31. Both are available in MySQL 8.0.31+ (released 2022). PostgreSQL, SQL Server, and Oracle all support all four operations.

↑ Back to top

Follow-up 1

Can you provide examples of set operations?

Sure! Here are some examples of set operations in SQL:

  • UNION: Combines the results of two or more SELECT statements, and returns all distinct rows.

  • INTERSECT: Returns only the common rows between two SELECT statements.

  • EXCEPT: Returns only the rows from the first SELECT statement that are not present in the second SELECT statement.

Follow-up 2

How do set operations differ from joins?

Set operations and joins are both used to combine data from multiple tables, but they differ in their approach and purpose.

  • Set operations combine the results of SELECT statements, focusing on the rows and eliminating duplicates. They do not consider the relationship between tables.

  • Joins, on the other hand, combine tables based on a common column or condition, focusing on the columns and preserving all rows. They consider the relationship between tables.

Follow-up 3

What are the different types of set operations in SQL?

There are three main types of set operations in SQL:

  • UNION: Combines the results of two or more SELECT statements, and returns all distinct rows.

  • INTERSECT: Returns only the common rows between two SELECT statements.

  • EXCEPT: Returns only the rows from the first SELECT statement that are not present in the second SELECT statement.

3. How do you use the UNION operation in SQL?

UNION combines the results of two or more SELECT queries and removes duplicate rows from the final output. UNION ALL keeps duplicates (and is faster).

Basic syntax:

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

Requirements:

  • Both SELECT statements must return the same number of columns
  • Corresponding columns must have compatible data types
  • Column names in the result are taken from the first SELECT

Example — combining customer and supplier cities:

SELECT city, 'Customer' AS source FROM customers
UNION
SELECT city, 'Supplier' AS source FROM suppliers
ORDER BY city;

UNION vs UNION ALL:

-- UNION: removes duplicates (sort + dedup = slower)
SELECT email FROM newsletter_list_a
UNION
SELECT email FROM newsletter_list_b;

-- UNION ALL: keeps duplicates (no dedup = faster)
SELECT email FROM newsletter_list_a
UNION ALL
SELECT email FROM newsletter_list_b;

Ordering the combined result: ORDER BY applies to the final combined result, not to individual queries. Use column position or a name from the first query:

SELECT product_id, 'Q1' AS quarter, revenue FROM q1_sales
UNION ALL
SELECT product_id, 'Q2', revenue FROM q2_sales
ORDER BY product_id, quarter;

Interview tip: Always prefer UNION ALL over UNION when you know there are no duplicates or when duplicates are acceptable — the deduplication step in UNION requires a sort pass over the entire combined result set, which is expensive at scale.

↑ Back to top

Follow-up 1

What is the difference between UNION and UNION ALL?

The main difference between UNION and UNION ALL is that UNION removes duplicate rows from the result set, while UNION ALL does not. When using UNION, only distinct rows are returned, meaning that if there are any duplicate rows between the result sets of the SELECT statements, only one copy of the duplicate row will be included in the final result set. On the other hand, UNION ALL does not remove duplicates and simply combines all the rows from the SELECT statements.

Here is an example to illustrate the difference:

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

This will return a result set with distinct rows.

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

This will return a result set with all rows, including duplicates.

Follow-up 2

Can you provide an example of a UNION operation?

Certainly! Here is an example of using UNION in SQL:

Let's say we have two tables, 'employees' and 'customers', with the following columns:

  • employees: employee_id, first_name, last_name
  • customers: customer_id, first_name, last_name

To combine the first names from both tables into a single result set, we can use the following query:

SELECT first_name FROM employees
UNION
SELECT first_name FROM customers

This will return a result set with all the distinct first names from both tables.

Follow-up 3

What are the requirements for using UNION?

To use the UNION operation in SQL, the following requirements must be met:

  1. The number of columns in the SELECT statements must be the same.
  2. The data types of the corresponding columns in the SELECT statements must be compatible.
  3. The columns in the SELECT statements must be in the same order.

If these requirements are not met, the UNION operation will result in an error.

4. What is the INTERSECT operation in SQL?

INTERSECT returns only the rows that are present in both result sets. It is the set theory intersection operator — the overlap between two queries.

Syntax:

SELECT column1, column2 FROM table1
INTERSECT
SELECT column1, column2 FROM table2;

Example — customers who placed orders in both 2024 and 2025:

SELECT customer_id FROM orders WHERE YEAR(order_date) = 2024
INTERSECT
SELECT customer_id FROM orders WHERE YEAR(order_date) = 2025;

Key behaviors:

  • Duplicates are removed (like UNION, not UNION ALL)
  • Column count and compatible types required
  • INTERSECT ALL (preserves duplicates) is supported in PostgreSQL and SQL Server 2022+

Database support (important for interviews):

  • PostgreSQL: Fully supported, including INTERSECT ALL
  • SQL Server: Fully supported since 2005
  • Oracle: Supported (uses INTERSECT)
  • MySQL: Supported since MySQL 8.0.31 (2022) — older versions must use a JOIN workaround

JOIN equivalent (for databases lacking INTERSECT or for performance):

-- Equivalent to INTERSECT using EXISTS:
SELECT DISTINCT a.customer_id
FROM orders_2024 a
WHERE EXISTS (
    SELECT 1 FROM orders_2025 b WHERE b.customer_id = a.customer_id
);

-- Or using INNER JOIN:
SELECT DISTINCT a.customer_id
FROM orders_2024 a
INNER JOIN orders_2025 b ON a.customer_id = b.customer_id;

Interview note: INTERSECT operates on full rows (all selected columns must match). If you only need matching IDs, EXISTS or INNER JOIN gives more control.

↑ Back to top

Follow-up 1

How does INTERSECT differ from UNION?

The INTERSECT operation returns only the common rows between the result sets, while the UNION operation returns all the rows from both result sets, removing duplicates. In other words, INTERSECT performs an AND operation, while UNION performs an OR operation.

Follow-up 2

Can you provide an example of an INTERSECT operation?

Sure! Let's say we have two tables, 'TableA' and 'TableB', with the following data:

TableA:

id name
1 John
2 Mary

TableB:

id name
1 John
3 Adam

To find the common rows between the two tables, we can use the INTERSECT operation like this:

SELECT id, name FROM TableA
INTERSECT
SELECT id, name FROM TableB;

This will return the following result:

id name
1 John

Follow-up 3

What are the requirements for using INTERSECT?

To use the INTERSECT operation in SQL, the following requirements must be met:

  1. The number of columns and their data types must be the same in all SELECT statements.
  2. The columns must be in the same order in all SELECT statements.
  3. The result sets must have the same number of columns.
  4. The result sets must be union-compatible, meaning that the data types of corresponding columns must be compatible.

If these requirements are not met, the INTERSECT operation will result in an error.

5. What is the EXCEPT operation in SQL?

EXCEPT (called MINUS in Oracle) returns rows from the first query that do not appear in the second query — the set difference operation.

Syntax:

SELECT column1, column2 FROM table1
EXCEPT
SELECT column1, column2 FROM table2;

Example — customers who have never placed an order:

SELECT customer_id FROM customers
EXCEPT
SELECT DISTINCT customer_id FROM orders;

Example — products in the catalog but not sold in Q1:

SELECT product_id FROM products
EXCEPT
SELECT DISTINCT product_id FROM sales WHERE quarter = 'Q1';

Key behaviors:

  • Returns rows from the first query not matched in the second (order matters)
  • Duplicates are removed (like UNION)
  • EXCEPT ALL preserves duplicates (PostgreSQL, SQL Server 2022+)

Database support:

  • PostgreSQL, SQL Server: EXCEPT and EXCEPT ALL
  • Oracle: MINUS (same behavior)
  • MySQL: Supported since MySQL 8.0.31

NOT EXISTS / LEFT JOIN equivalent:

-- Equivalent to EXCEPT using NOT EXISTS:
SELECT DISTINCT c.customer_id
FROM customers c
WHERE NOT EXISTS (
    SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);

-- Using LEFT JOIN anti-pattern:
SELECT c.customer_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.customer_id IS NULL;

Interview gotcha: The LEFT JOIN ... WHERE IS NULL approach is a common alternative that works in all databases including older MySQL. It is often used in interview questions about finding "orphan" records.

↑ Back to top

Follow-up 1

How does EXCEPT differ from INTERSECT?

The EXCEPT operation returns the distinct rows from the left input query that are not present in the right input query, while the INTERSECT operation returns the distinct rows that are common to both the left and right input queries.

Follow-up 2

Can you provide an example of an EXCEPT operation?

Certainly! Here's an example:

SELECT column1, column2 FROM table1
EXCEPT
SELECT column1, column2 FROM table2;

This query will return the distinct rows from table1 that are not present in table2 based on the values of column1 and column2.

Follow-up 3

What are the requirements for using EXCEPT?

To use the EXCEPT operation in SQL, the following requirements must be met:

  1. The number of columns and their data types must be the same in both the left and right input queries.
  2. The columns being compared must have compatible data types.
  3. The left and right input queries must have the same number of columns in the same order.

6. What is a Common Table Expression (CTE) and how does it differ from a subquery?

A CTE (Common Table Expression) is a named, temporary result set defined using the WITH keyword at the start of a query. It can be referenced multiple times within the same query.

WITH dept_avg AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.name, e.salary, d.avg_salary
FROM employees e
JOIN dept_avg d ON e.department_id = d.department_id
WHERE e.salary > d.avg_salary;

CTE vs subquery:

Aspect CTE Subquery
Named Yes — reusable within the query No — anonymous
Reusability Can reference the same CTE multiple times Must duplicate subquery
Readability Highly readable (top-down logic flow) Can become deeply nested
Recursive Yes (WITH RECURSIVE) No
Performance Usually same as subquery (materialized in some databases) Same

Recursive CTE (important for hierarchy traversal):

WITH RECURSIVE org_chart AS (
    SELECT id, name, manager_id, 0 AS level
    FROM employees WHERE manager_id IS NULL   -- root (CEO)
    UNION ALL
    SELECT e.id, e.name, e.manager_id, oc.level + 1
    FROM employees e
    JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT * FROM org_chart ORDER BY level, name;

CTEs are supported in all major databases: PostgreSQL 8.4+, MySQL 8.0+, SQL Server 2005+, SQLite 3.35+.


↑ Back to top

Live mock interview

Mock interview: SQL Queries and Set Operations

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.