SQL Interview Questions: This practical MySQL 8 interview guide helps students understand SQL concepts and develop strong query-writing skills. Learn database fundamentals, filtering, joins, subqueries, aggregate functions, indexes, transactions and query optimization through structured explanations and practical examples. Work through real-world database scenarios and 50 interview problems to strengthen your SQL preparation.
SQL Interview Questions: The MySQL 8 Sample Business Database
The database models a small distributor. A department has employees; a customer places orders; an order contains products through order items; suppliers provide products. The grain of each table is important: one row in orders is one order, while one row in order_items is one product line within an order.
CREATE DATABASE campus_store;
USE campus_store;
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(80) NOT NULL UNIQUE
);
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100) NOT NULL,
department_id INT NULL,
manager_id INT NULL,
salary DECIMAL(12,2) NOT NULL CHECK (salary >= 0),
hire_date DATE NOT NULL,
FOREIGN KEY (department_id) REFERENCES departments(department_id),
FOREIGN KEY (manager_id) REFERENCES employees(employee_id)
);
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(120) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
city VARCHAR(80),
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE suppliers (
supplier_id INT PRIMARY KEY,
supplier_name VARCHAR(120) NOT NULL,
country CHAR(2) NOT NULL
);
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(150) NOT NULL,
supplier_id INT NOT NULL,
category VARCHAR(80) NOT NULL,
unit_price DECIMAL(10,2) NOT NULL CHECK (unit_price >= 0),
stock_quantity INT NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0),
FOREIGN KEY (supplier_id) REFERENCES suppliers(supplier_id)
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
employee_id INT NULL,
order_date DATE NOT NULL,
status ENUM('pending','shipped','cancelled') NOT NULL DEFAULT 'pending',
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
);
CREATE TABLE order_items (
order_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL CHECK (quantity > 0),
unit_price DECIMAL(10,2) NOT NULL CHECK (unit_price >= 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
Why this design matters: foreign keys prevent an order from pointing to a missing customer, and the composite key prevents the same product being repeated in one order line. We store the historical sale price in order_items.unit_price because a product’s current price can change after an order is placed. For examples below, assume customers 1–5, products 101–105, departments 10–30 and orders 1001–1006 have been loaded.
Safe setup: use a transaction for test data, never run destructive statements against production, and keep an export before schema changes. MySQL’s ENUM is convenient but less portable than a lookup table or a checked status column in some systems.
Foundations, schema design and data modification
1. Databases, DBMS, RDBMS and SQL
A database is organised data; a DBMS stores, protects and retrieves it; an RDBMS represents related data in tables and enforces constraints. SQL is declarative: you state the result, and the optimizer chooses an execution strategy. MySQL is an RDBMS; SQL syntax is standardised, but vendors add dialect features.
2. Tables, rows, columns, keys and relationships
A table has a defined set of columns and each row is one entity or relationship instance. A primary key identifies one row, a foreign key references another table, and cardinality describes one-to-one, one-to-many or many-to-many relationships. customers to orders is one-to-many; products to orders is many-to-many through order_items.
3. Data types
Use INT for identifiers, DECIMAL for money, DATE for dates without time, DATETIME for a local timestamp, and VARCHAR for bounded text. Do not use floating-point types for currency. Size types deliberately, but do not truncate valid business values.
4. CREATE, ALTER, DROP and TRUNCATE
ALTER TABLE products ADD COLUMN discontinued_at DATE NULL;
ALTER TABLE products MODIFY unit_price DECIMAL(12,2) NOT NULL;
TRUNCATE TABLE staging_products;
DROP TABLE staging_products;
CREATE defines an object, ALTER changes its structure, TRUNCATE removes all rows efficiently, and DROP removes the object. MySQL DDL may cause implicit commits, so check the exact statement and backup policy before running it.
5. INSERT, UPDATE and DELETE
INSERT INTO departments (department_id, department_name)
VALUES (40, 'Support');
UPDATE products SET stock_quantity = stock_quantity - 1
WHERE product_id = 101 AND stock_quantity > 0;
DELETE FROM departments WHERE department_id = 40;
Always test the WHERE with a SELECT first, use a key-based predicate, check affected-row counts and protect multi-row changes with a transaction. An update that omits its predicate can change every row.
6. SELECT and aliases
SELECT c.customer_name AS customer,
o.order_id AS order_number
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id;
Aliases make a query readable and disambiguate repeated column names. Do not rely on SELECT * in production reports: explicit columns protect consumers from schema changes and reduce I/O.
7. WHERE, ORDER BY, DISTINCT and LIMIT
SELECT DISTINCT city
FROM customers
WHERE city IS NOT NULL
ORDER BY city
LIMIT 10;
Logical query processing filters before ordering, although the optimizer may reorder physical work. Use a deterministic tie-breaker with LIMIT, such as ORDER BY created_at DESC, customer_id DESC.
8. Comparison and logical operators
Use =, <>, <, >=, AND, OR and NOT. Parenthesise mixed conditions because AND binds more tightly than OR. SQL uses three-valued logic: a comparison with NULL is unknown, not true or false.
9. BETWEEN, IN, LIKE and IS NULL
SELECT *
FROM orders
WHERE order_date >= '2026-01-01'
AND order_date < '2026-02-01'
AND status IN ('shipped', 'pending');
SELECT * FROM customers WHERE customer_name LIKE 'A%';
SELECT * FROM customers WHERE city IS NULL;
Prefer half-open date ranges for timestamps. BETWEEN is inclusive at both ends; LIKE '%term' usually prevents a normal left-prefix index from being used.
10. Aggregate functions
COUNT(*) counts rows, COUNT(column) ignores nulls, and SUM, AVG, MIN and MAX aggregate values. Decide whether you need orders or order lines before counting; joining a one-to-many table can multiply rows.
11. GROUP BY and HAVING
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2
ORDER BY order_count DESC;
WHERE filters rows before grouping; HAVING filters groups after aggregation. Every selected non-aggregated expression must be grouped under strict MySQL settings.
12. Key types
A candidate key is any minimal unique identifier; the chosen one is the primary key. A composite key uses multiple columns, as in order_items(order_id, product_id). A unique key enforces another candidate such as customer email. A surrogate integer key is convenient, but business identifiers may still need a unique constraint.
13. Constraints and referential integrity
NOT NULL, CHECK, UNIQUE, primary keys and foreign keys make invalid states harder to store. Choose ON DELETE actions deliberately: cascading order lines may be correct for an order aggregate, while cascading customers could destroy audit history. In MySQL, use InnoDB for transactional foreign keys.
Joins, subqueries, sets and expressions
14. INNER, LEFT, RIGHT and FULL OUTER joins
SELECT c.customer_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id;
INNER keeps matched rows; LEFT keeps every left row and fills unmatched right columns with nulls; RIGHT reverses the perspective. MySQL 8 has no native FULL OUTER JOIN; emulate it with a LEFT JOIN unioned with unmatched right rows. A predicate on the right table in WHERE can accidentally turn a left join into an inner join, so put optional-side conditions in ON.
15. CROSS JOIN and SELF JOIN
SELECT d.department_name, s.status
FROM departments AS d
CROSS JOIN (SELECT 'pending' AS status UNION ALL SELECT 'shipped') AS s;
SELECT e.employee_name, m.employee_name AS manager_name
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id;
A cross join creates every combination and can grow as the product of row counts. A self join uses aliases of the same table, useful for employee-manager hierarchies.
16. Subqueries
SELECT product_name, unit_price
FROM products
WHERE unit_price > (SELECT AVG(unit_price) FROM products);
A scalar subquery returns one value; a table subquery returns rows and columns. Check cardinality: a scalar subquery returning two rows raises an error. A derived table in FROM can make a multi-stage calculation explicit.
17. Correlated subqueries
SELECT p.product_name, p.unit_price
FROM products AS p
WHERE p.unit_price > (
SELECT AVG(p2.unit_price)
FROM products AS p2
WHERE p2.category = p.category
);
The inner query references the current outer row. It is expressive but may execute repeatedly; an aggregate CTE or join can be easier for the optimizer and reader.
18. EXISTS and NOT EXISTS
SELECT c.customer_id, c.customer_name
FROM customers AS c
WHERE EXISTS (
SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id
);
EXISTS tests whether at least one related row exists and can stop after the first match. It avoids duplicate customer rows that a plain join might create. NOT EXISTS is usually safer than NOT IN when the subquery can contain nulls.
19. UNION and UNION ALL
Set operands must have the same number of compatible columns. UNION removes duplicates and may sort or hash; UNION ALL preserves duplicates and is faster when duplicates are meaningful or already impossible. Apply one final ORDER BY to the combined result.
20. CASE expressions
SELECT order_id,
CASE status
WHEN 'shipped' THEN 'complete'
WHEN 'cancelled' THEN 'closed'
ELSE 'open'
END AS lifecycle
FROM orders;
Use searched CASE WHEN condition THEN... for ranges and conditional aggregates such as SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END). Include an ELSE so unexpected values do not become null silently.
21. String, numeric and date functions
SELECT UPPER(TRIM(customer_name)) AS normalised_name,
ROUND(unit_price * 1.18, 2) AS price_with_tax,
DATE_FORMAT(order_date, '%Y-%m') AS order_month
FROM products
JOIN order_items USING (product_id)
JOIN orders USING (order_id);
MySQL functions include CONCAT, LOWER, TRIM, ROUND, ABS, DATE_ADD, DATEDIFF and DATE_FORMAT. Applying functions to an indexed column in a predicate can prevent a direct index range scan; rewrite the predicate as a range when possible.
22. NULL handling and COALESCE
SELECT c.customer_name, COALESCE(SUM(oi.quantity * oi.unit_price), 0) AS spend
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
LEFT JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.customer_name;
COALESCE returns the first non-null expression. It does not turn an unknown value into a fact; choose a business meaning for the fallback. Use NULLIF to avoid division by zero.
23. Common table expressions
WITH customer_spend AS (
SELECT o.customer_id, SUM(oi.quantity * oi.unit_price) AS spend
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY o.customer_id
)
SELECT c.customer_name, cs.spend
FROM customer_spend AS cs
JOIN customers AS c ON c.customer_id = cs.customer_id;
A CTE names an intermediate relation and improves readability. In MySQL 8 the optimizer may merge or materialize it; use EXPLAIN rather than assuming a CTE is always a temporary table.
24. Recursive CTEs
WITH RECURSIVE org AS (
SELECT employee_id, employee_name, manager_id, 0 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.employee_name, e.manager_id, org.level + 1
FROM employees AS e
JOIN org ON org.employee_id = e.manager_id
)
SELECT * FROM org ORDER BY level, employee_id;
The anchor produces roots; the recursive member finds children until no new rows appear. Guard against cycles and runaway depth with data validation and a depth predicate.
Window functions, views, indexes and optimization
25. Window functions
A window function calculates across related rows without collapsing them like GROUP BY. PARTITION BY defines groups and ORDER BY defines sequence. A window frame controls which ordered rows contribute.
SELECT employee_name, department_id, salary,
AVG(salary) OVER (PARTITION BY department_id) AS department_average
FROM employees;
26. ROW_NUMBER, RANK and DENSE_RANK
ROW_NUMBER gives unique sequence numbers; RANK gives ties the same rank and leaves gaps; DENSE_RANK gives ties the same rank without gaps. Always include a deterministic tie-breaker when selecting one row.
SELECT employee_name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_number,
RANK() OVER (ORDER BY salary DESC) AS salary_rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees;
27. LEAD, LAG and running totals
SELECT order_date,
SUM(order_total) OVER (
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total,
LAG(order_total) OVER (ORDER BY order_date) AS previous_total
FROM daily_orders;
LAG reads a previous row and LEAD reads a following row. Define ties and grain before using them; two orders on the same date need an additional ordering key.
28. Views and materialized views
A view stores a query definition and presents a stable interface; it normally computes when read. MySQL has no native materialized view. Simulate one with a summary table refreshed by a scheduled job or event, documenting freshness and refresh failure handling.
CREATE VIEW customer_order_totals AS
SELECT customer_id, COUNT(*) AS order_count
FROM orders GROUP BY customer_id;
29. Indexes and index types
InnoDB primarily uses B-tree indexes. A primary key is clustered in InnoDB; secondary indexes contain the indexed columns plus the primary key. Composite index order matters: an index on (customer_id, order_date) supports a customer equality and date range better than the reverse for that access pattern. Indexes speed reads but consume space and slow writes.
CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date);
CREATE INDEX idx_order_items_product ON order_items (product_id);
SHOW INDEX FROM orders;
30. Query execution and optimization
The optimizer estimates access paths, join order, indexes, filtering and algorithms. Start with correctness and a measurable slow query; inspect cardinality, predicates, selected columns and row multiplication. Avoid premature hints. Sargable predicates compare an indexed column directly to a value or range.
31. EXPLAIN plans
EXPLAIN ANALYZE
SELECT c.customer_name, SUM(oi.quantity * oi.unit_price) AS spend
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.customer_name;
Read access type, possible and chosen keys, estimated rows, actual timing and extra operations. EXPLAIN ANALYZE executes the query, so do not use it casually on expensive or mutating statements. Estimates that differ greatly from reality suggest stale statistics, skew or an inaccurate predicate assumption.
Transactions, modeling, procedures, triggers and security
32–35. Transactions, ACID, isolation, locks and deadlocks
Atomicity makes a multi-step change all-or-nothing; consistency preserves constraints; isolation controls what concurrent transactions observe; durability persists committed work. Use START TRANSACTION, COMMIT, ROLLBACK and SAVEPOINT for controlled units of work.
START TRANSACTION;
UPDATE products SET stock_quantity = stock_quantity - 2
WHERE product_id = 101 AND stock_quantity >= 2;
SAVEPOINT after_stock;
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (1007, 101, 2, 19.99);
COMMIT;
InnoDB commonly defaults to REPEATABLE READ; other levels include READ UNCOMMITTED, READ COMMITTED and SERIALIZABLE. Higher isolation can reduce anomalies but increase blocking. Locks are held on rows or index ranges; deadlocks occur when transactions acquire overlapping locks in different orders. Keep transactions short, lock objects in a consistent order, index predicates and retry a safely idempotent transaction after a deadlock.
36. Normalization: 1NF, 2NF, 3NF and BCNF
1NF stores atomic values and no repeating groups. 2NF removes partial dependency on part of a composite key. 3NF removes transitive dependency on a non-key attribute. BCNF requires every determinant to be a candidate key. Normalize to protect update correctness, then denormalize only with measured read requirements, documented ownership and refresh strategy.
37. Stored procedures and functions
DELIMITER //
CREATE PROCEDURE customer_orders(IN p_customer_id INT)
BEGIN
SELECT order_id, order_date, status
FROM orders
WHERE customer_id = p_customer_id
ORDER BY order_date DESC;
END//
DELIMITER ;
CALL customer_orders(1);
Procedures can return result sets and perform work; functions return a value and are usable in expressions. Keep business logic placement deliberate, version definitions, validate inputs and consider testing and deployment portability.
38. Triggers
CREATE TRIGGER order_items_validate_price
BEFORE INSERT ON order_items
FOR EACH ROW
SET NEW.unit_price = GREATEST(NEW.unit_price, 0);
Triggers run implicitly and can enforce auditing or invariants, but hidden side effects make debugging and bulk loads harder. Prefer explicit application or procedure logic when the rule must be visible and testable; never use a trigger as a substitute for a foreign key.
39. Database security and SQL injection
Use least-privilege accounts, TLS, encrypted backups, secret management, audit logging and separate read/write roles. SQL injection occurs when untrusted text changes query structure. Use prepared statements with bound parameters, never concatenate request values into SQL, validate identifiers through an allow-list, and avoid returning detailed database errors to users.
-- Application pseudocode, parameter syntax varies by driver:
SELECT customer_id, customer_name
FROM customers
WHERE email = ?;
40. Relational versus non-relational databases
Relational systems provide schemas, joins, constraints and transactions suited to connected business facts. Document, key-value, column-family and graph stores trade some relational features for flexible models or specialised access patterns. Choose from access patterns, consistency, scale, operational skills and data relationships—not from a claim that one model is universally faster.
41. MySQL-specific concepts and syntax
MySQL 8 provides InnoDB transactions, generated columns, CTEs, window functions, EXPLAIN ANALYZE, JSON functions and LIMIT. It uses backticks for identifiers, AUTO_INCREMENT, ENUM and ON DUPLICATE KEY UPDATE; these are not portable standard SQL. MySQL has no native FULL OUTER JOIN or materialized view. State the dialect in an interview and translate syntax when asked for PostgreSQL, SQL Server or Oracle.
50 progressive practical SQL interview problems
For every problem, first state the table grain and expected cardinality, then write the query, test nulls and ties, and inspect the plan. Outputs below are representative; exact values depend on the sample rows loaded into the schema.
1. Find duplicate customer emails
Problem: identify emails appearing more than once in an imported staging table.
SELECT email, COUNT(*) AS occurrences
FROM staging_customers
GROUP BY email
HAVING COUNT(*) > 1;
Expected output: one row per duplicate email and its count. Explanation: grouping establishes one group per email and HAVING removes singleton groups. Alternative: use ROW_NUMBER to label which duplicate to retain. Performance: index the email column if the staging table is large.
2. Find duplicate order lines
Problem: detect repeated order/product pairs.
SELECT order_id, product_id, COUNT(*) AS occurrences
FROM order_items GROUP BY order_id, product_id HAVING COUNT(*) > 1;
The composite key should prevent this in the final table. A staging query catches violations before loading. Grouping costs O(n) expected hash work or sorting work; a composite unique index prevents future duplicates.
3. Second-highest salary
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
This returns the second distinct salary and null if none exists. DENSE_RANK is preferable when you also need employee rows. Index salary for large tables.
4. Nth-highest salary
WITH ranked AS (
SELECT employee_id, employee_name, salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT * FROM ranked WHERE rnk = 3;
Replace 3 with a parameter. DENSE_RANK handles ties; ROW_NUMBER would arbitrarily split equal salaries unless a tie-breaker is intended.
5. Department-wise highest salary
WITH ranked AS (
SELECT e.*, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees AS e
)
SELECT * FROM ranked WHERE rnk = 1;
RANK returns all tied leaders. A correlated MAX subquery is an alternative; index (department_id, salary) can help.
6. Employees earning above department average
SELECT e.employee_name, e.salary
FROM employees AS e
JOIN (
SELECT department_id, AVG(salary) AS average_salary
FROM employees GROUP BY department_id
) AS a ON a.department_id = e.department_id
WHERE e.salary > a.average_salary;
The derived table computes one average per department before joining. A window AVG avoids a separate join. Both require scanning employees and may benefit from department statistics.
7. Customers with no orders
SELECT c.customer_id, c.customer_name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id
);
NOT EXISTS preserves customers with no match without producing null duplicates. An indexed orders.customer_id makes the anti-lookup efficient.
8. Customers with at least one shipped order
SELECT c.customer_id, c.customer_name
FROM customers AS c
WHERE EXISTS (
SELECT 1 FROM orders AS o
WHERE o.customer_id = c.customer_id AND o.status = 'shipped'
);
EXISTS can stop after one matching order. A join with DISTINCT is valid but may process more rows.
9. Top products by revenue
SELECT p.product_id, p.product_name,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM products AS p
JOIN order_items AS oi ON oi.product_id = p.product_id
JOIN orders AS o ON o.order_id = oi.order_id
WHERE o.status <> 'cancelled'
GROUP BY p.product_id, p.product_name
ORDER BY revenue DESC, p.product_id
LIMIT 5;
Revenue is calculated from historical line prices, not current product price. Filter cancelled orders before aggregation; indexes on order status and foreign keys help, but measure selectivity.
10. Monthly revenue
SELECT DATE_FORMAT(o.order_date, '%Y-%m') AS month,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'shipped'
GROUP BY month ORDER BY month;
DATE_FORMAT groups calendar months in MySQL. For a large indexed date range, filter with a half-open date predicate before grouping.
11. Running monthly revenue
WITH monthly AS (
SELECT DATE_FORMAT(o.order_date, '%Y-%m') AS month,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'shipped'
GROUP BY month
)
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS running_revenue
FROM monthly ORDER BY month;
Aggregate first to monthly grain, then window over the smaller result. This avoids summing line rows repeatedly.
12. Rank employees within departments
SELECT employee_name, department_id, salary,
DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees;
The partition restarts rank per department. Use ROW_NUMBER only when a unique ordering is required.
13. Compare each order with the previous order
SELECT order_id, order_date,
LAG(order_date) OVER (ORDER BY order_date, order_id) AS previous_date
FROM orders;
The order_id tie-breaker makes same-day order ordering deterministic. Compute date gaps in an outer query with DATEDIFF.
14. Find consecutive order dates
WITH dates AS (
SELECT DISTINCT order_date FROM orders
),
marked AS (
SELECT order_date,
LAG(order_date) OVER (ORDER BY order_date) AS previous_date
FROM dates
)
SELECT * FROM marked
WHERE DATEDIFF(order_date, previous_date) = 1;
Distinct dates prevent multiple orders on one day from creating false runs. For full streak lengths, use the gaps-and-islands technique with row numbers.
15. Remove duplicate staging rows safely
WITH ranked AS (
SELECT staging_id,
ROW_NUMBER() OVER (
PARTITION BY email ORDER BY imported_at, staging_id
) AS rn
FROM staging_customers
)
DELETE s FROM staging_customers AS s
JOIN ranked r ON r.staging_id = s.staging_id
WHERE r.rn > 1;
MySQL 8 supports CTEs with DML, but preview the ranked rows in a SELECT and transactionally verify the affected count first. Keep an audit copy before deletion.
16. Join customers, orders and employees
SELECT c.customer_name, o.order_id, e.employee_name AS handled_by
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN employees e ON e.employee_id = o.employee_id;
The left join keeps orders not yet assigned to an employee. The result grain is one row per order.
17. Find products without suppliers
SELECT p.product_id, p.product_name
FROM products p
LEFT JOIN suppliers s ON s.supplier_id = p.supplier_id
WHERE s.supplier_id IS NULL;
A valid foreign key prevents this in the final schema; the query is useful against a staging or legacy table. NOT EXISTS is an equivalent anti-join.
18. Find suppliers with no products
SELECT s.supplier_id, s.supplier_name
FROM suppliers s
WHERE NOT EXISTS (
SELECT 1 FROM products p WHERE p.supplier_id = s.supplier_id
);
It returns orphaned supplier master records. Index products.supplier_id.
19. Customers who bought every product in a category
SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE p.category = 'Books'
GROUP BY o.customer_id
HAVING COUNT(DISTINCT p.product_id) = (
SELECT COUNT(*) FROM products WHERE category = 'Books'
);
This is relational division: compare each customer’s distinct category coverage with the category’s product count. Handle an empty category explicitly.
20. Average order value by city
SELECT c.city, AVG(t.order_total) AS average_order_value
FROM customers c
JOIN (
SELECT o.order_id, o.customer_id,
SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders o JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.customer_id
) t ON t.customer_id = c.customer_id
GROUP BY c.city;
First aggregate at order grain, then average orders; averaging line values would answer a different question.
21. Product sales share
WITH sales AS (
SELECT product_id, SUM(quantity * unit_price) AS revenue
FROM order_items GROUP BY product_id
)
SELECT product_id, revenue,
revenue / NULLIF(SUM(revenue) OVER (), 0) AS share
FROM sales;
The window total preserves product rows. NULLIF prevents division by zero.
22. First order for each customer
WITH ranked AS (
SELECT o.*, ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY order_date, order_id
) AS rn
FROM orders o
)
SELECT * FROM ranked WHERE rn = 1;
ROW_NUMBER selects one deterministic first order. MIN(order_date) alone cannot return the corresponding order_id.
23. Latest order for each customer
SELECT * FROM (
SELECT o.*, ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC
) rn FROM orders o
) x WHERE rn = 1;
Use a descending date and ID tie-breaker. A correlated ORDER BY/LIMIT approach may be efficient with a composite index.
24. Customers whose latest order is cancelled
WITH latest AS (
SELECT o.*, ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC
) rn FROM orders o
)
SELECT customer_id FROM latest WHERE rn = 1 AND status = 'cancelled';
Filter after identifying the latest row; filtering cancelled orders first would answer a different question.
25. Three-month revenue moving average
WITH monthly AS (
SELECT DATE_FORMAT(order_date, '%Y-%m') month,
SUM(oi.quantity * oi.unit_price) revenue
FROM orders o JOIN order_items oi USING (order_id)
WHERE status = 'shipped' GROUP BY month
)
SELECT month, revenue,
AVG(revenue) OVER (
ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_average
FROM monthly;
ROWS counts available rows, not necessarily calendar months; create a calendar table when missing months must count as zero.
26. Employees hired in the same year
SELECT YEAR(hire_date) AS hire_year, COUNT(*) AS employees
FROM employees GROUP BY YEAR(hire_date) ORDER BY hire_year;
For an indexed date filter use a range rather than applying YEAR in WHERE. Grouping by year is appropriate for a report.
27. Departments with no employees
SELECT d.department_id, d.department_name
FROM departments d
LEFT JOIN employees e ON e.department_id = d.department_id
WHERE e.employee_id IS NULL;
This is an anti-join. A foreign key allows a department to exist without employees because department_id on employees is nullable.
28. Manager and direct-report counts
SELECT m.employee_id, m.employee_name, COUNT(e.employee_id) AS reports
FROM employees m
LEFT JOIN employees e ON e.manager_id = m.employee_id
GROUP BY m.employee_id, m.employee_name;
LEFT JOIN includes managers with zero reports. COUNT(child key), not COUNT(*), avoids counting the null placeholder row.
29. Employees above their manager’s salary
SELECT e.employee_name, e.salary, m.employee_name AS manager, m.salary AS manager_salary
FROM employees e JOIN employees m ON m.employee_id = e.manager_id
WHERE e.salary > m.salary;
This self join compares two roles in the same table. Index manager_id.
30. Products never ordered
SELECT p.product_id, p.product_name
FROM products p
WHERE NOT EXISTS (
SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id
);
NOT EXISTS avoids duplicate product rows. A left anti-join is equivalent; compare plans on your data.
31. Orders containing at least three products
SELECT order_id, COUNT(DISTINCT product_id) AS product_count
FROM order_items
GROUP BY order_id
HAVING COUNT(DISTINCT product_id) >= 3;
Distinct matters if a staging table allows repeated lines. In the constrained final schema COUNT(*) is enough.
32. Orders whose total exceeds the customer average
WITH totals AS (
SELECT o.order_id, o.customer_id,
SUM(oi.quantity * oi.unit_price) total
FROM orders o JOIN order_items oi USING (order_id)
GROUP BY o.order_id, o.customer_id
)
SELECT * FROM totals t
WHERE total > (
SELECT AVG(t2.total) FROM totals t2
WHERE t2.customer_id = t.customer_id
);
The CTE supplies order grain; the correlated comparison uses each customer’s own average. Materialization behaviour is optimizer-dependent, so inspect EXPLAIN.
33. Revenue by supplier
SELECT s.supplier_name,
SUM(oi.quantity * oi.unit_price) revenue
FROM suppliers s JOIN products p USING (supplier_id)
JOIN order_items oi USING (product_id)
GROUP BY s.supplier_id, s.supplier_name
ORDER BY revenue DESC;
Grouping by ID and name protects against same-named suppliers. Add an order status join when cancelled sales must be excluded.
34. Category with highest average product price
SELECT category, AVG(unit_price) average_price
FROM products GROUP BY category
ORDER BY average_price DESC LIMIT 1;
LIMIT 1 hides ties; use DENSE_RANK over grouped results when all tied categories are required.
35. Top two products per category
WITH ranked AS (
SELECT p.product_id, p.category,
SUM(oi.quantity * oi.unit_price) revenue,
DENSE_RANK() OVER (
PARTITION BY p.category
ORDER BY SUM(oi.quantity * oi.unit_price) DESC
) rnk
FROM products p JOIN order_items oi USING (product_id)
GROUP BY p.product_id, p.category
)
SELECT * FROM ranked WHERE rnk <= 2;
Use DENSE_RANK for ties. Aggregate before ranking so the window operates on product totals.
36. Month-over-month revenue change
WITH monthly AS (
SELECT DATE_FORMAT(o.order_date, '%Y-%m') month,
SUM(oi.quantity * oi.unit_price) revenue
FROM orders o JOIN order_items oi USING (order_id)
GROUP BY month
)
SELECT month, revenue,
revenue - LAG(revenue) OVER (ORDER BY month) change
FROM monthly;
The first month has null change. Use NULLIF for a percentage change when prior revenue is zero.
37. Find a three-day order streak
WITH dates AS (
SELECT DISTINCT customer_id, order_date FROM orders
),
numbered AS (
SELECT customer_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) rn
FROM dates
),
islands AS (
SELECT customer_id, order_date,
DATE_SUB(order_date, INTERVAL rn DAY) island_key
FROM numbered
)
SELECT customer_id, MIN(order_date) start_date, MAX(order_date) end_date,
COUNT(*) days
FROM islands GROUP BY customer_id, island_key HAVING COUNT(*) >= 3;
Subtracting row number makes consecutive dates share a key. This MySQL date expression is dialect-specific; PostgreSQL uses date minus an integer interval.
38. Detect missing order numbers
SELECT a.order_id + 1 AS missing_order_id
FROM orders a
LEFT JOIN orders b ON b.order_id = a.order_id + 1
WHERE b.order_id IS NULL;
This finds gaps after an existing order but not before the minimum or beyond the maximum. A numbers/calendar table is more complete for a range audit.
39. Find customers with orders in two consecutive months
WITH months AS (
SELECT DISTINCT customer_id,
EXTRACT(YEAR_MONTH FROM order_date) ym
FROM orders
)
SELECT DISTINCT a.customer_id
FROM months a JOIN months b
ON b.customer_id = a.customer_id
AND b.ym = EXTRACT(YEAR_MONTH FROM DATE_ADD(
STR_TO_DATE(CONCAT(a.ym, '01'), '%Y%m%d'), INTERVAL 1 MONTH));
Normalise to one row per customer-month first. A calendar dimension makes month arithmetic and missing periods easier to reason about.
40. Conditional order-status counts
SELECT customer_id,
SUM(status = 'shipped') AS shipped_count,
SUM(status = 'pending') AS pending_count,
SUM(status = 'cancelled') AS cancelled_count
FROM orders GROUP BY customer_id;
MySQL treats boolean expressions as 0/1; portable SQL uses SUM(CASE WHEN ... THEN 1 ELSE 0 END). Explain the dialect choice in an interview.
41. Customers above the 90th percentile of spend
WITH totals AS (
SELECT customer_id, SUM(quantity * unit_price) spend
FROM orders JOIN order_items USING (order_id)
GROUP BY customer_id
),
ranked AS (
SELECT totals.*, CUME_DIST() OVER (ORDER BY spend) distribution
FROM totals
)
SELECT * FROM ranked WHERE distribution >= 0.9;
CUME_DIST includes ties and is a relative distribution, not an exact percentile value. Define the business rule before choosing percentile semantics.
42. Pivot revenue into product categories
SELECT DATE_FORMAT(o.order_date, '%Y-%m') month,
SUM(CASE WHEN p.category = 'Books' THEN oi.quantity * oi.unit_price ELSE 0 END) books,
SUM(CASE WHEN p.category = 'Hardware' THEN oi.quantity * oi.unit_price ELSE 0 END) hardware
FROM orders o JOIN order_items oi USING (order_id)
JOIN products p USING (product_id)
GROUP BY month ORDER BY month;
Conditional aggregation is the portable pivot pattern. Dynamic categories require generated SQL or a reporting layer; never concatenate untrusted category names.
43. Reconcile order totals with line totals
SELECT o.order_id,
SUM(oi.quantity * oi.unit_price) AS line_total
FROM orders o JOIN order_items oi USING (order_id)
GROUP BY o.order_id
HAVING SUM(oi.quantity * oi.unit_price) < 0;
Here the example has no stored header total, so a real reconciliation compares this result with an invoice table. Use a tolerance for decimal calculations and report missing or duplicated lines separately.
44. Find products whose sales increased month over month
WITH monthly AS (
SELECT product_id, DATE_FORMAT(o.order_date, '%Y-%m') month,
SUM(oi.quantity) units
FROM orders o JOIN order_items oi USING (order_id)
GROUP BY product_id, month
),
compared AS (
SELECT monthly.*, LAG(units) OVER (
PARTITION BY product_id ORDER BY month
) previous_units
FROM monthly
)
SELECT * FROM compared WHERE units > previous_units;
Missing months are not automatically zero; use a calendar/product grid if a missing month must be interpreted as no sales.
45. Find the longest employee tenure by department
WITH ranked AS (
SELECT e.*, ROW_NUMBER() OVER (
PARTITION BY department_id ORDER BY hire_date, employee_id
) rn
FROM employees e
)
SELECT * FROM ranked WHERE rn = 1;
Earlier hire_date means longer tenure. The employee_id tie-breaker ensures one result; use RANK when ties should remain.
46. Use a recursive CTE to list all reports
WITH RECURSIVE reports AS (
SELECT employee_id, employee_name, manager_id, 0 depth
FROM employees WHERE employee_id = 1
UNION ALL
SELECT e.employee_id, e.employee_name, e.manager_id, r.depth + 1
FROM employees e JOIN reports r ON e.manager_id = r.employee_id
WHERE r.depth < 20
)
SELECT * FROM reports;
The depth guard protects against corrupt cycles. For production hierarchy queries, store and validate a path or use a closure table when recursive reads dominate.
47. Safely upsert a product
INSERT INTO products
(product_id, product_name, supplier_id, category, unit_price, stock_quantity)
VALUES (101, 'Notebook', 1, 'Books', 4.99, 20)
ON DUPLICATE KEY UPDATE
product_name = VALUES(product_name),
unit_price = VALUES(unit_price),
stock_quantity = VALUES(stock_quantity);
This is MySQL-specific. In newer MySQL versions, alias-based row references are preferred over deprecated VALUES usage; use the syntax supported by your target version and protect the operation with permissions and validation.
48. Identify a likely deadlock pattern
Problem: two transactions update products 101 and 102 in opposite order. Solution: establish a sorted lock order in both code paths, keep transactions short, index the predicates and retry only the failed transaction. Performance: fewer held locks reduce wait time; monitor InnoDB deadlock reports rather than hiding errors.
49. Find slow non-sargable date filtering
-- Less index-friendly:
SELECT * FROM orders WHERE YEAR(order_date) = 2026;
-- Prefer a half-open range:
SELECT * FROM orders
WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01';
The range keeps the column bare and can use an index range scan. Confirm with EXPLAIN; selectivity and statistics still matter.
50. Design a customer lifetime-value report
WITH totals AS (
SELECT c.customer_id, c.customer_name,
COUNT(DISTINCT o.order_id) order_count,
COALESCE(SUM(oi.quantity * oi.unit_price), 0) lifetime_value,
MAX(o.order_date) last_order_date
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.customer_name
)
SELECT *, DENSE_RANK() OVER (ORDER BY lifetime_value DESC) value_rank
FROM totals ORDER BY value_rank, customer_id;
First define whether cancelled orders count and whether lifetime value is gross or net. COUNT DISTINCT protects order count from line multiplication; COALESCE preserves customers with no orders. Index foreign keys and validate the report against hand-calculated cases.
Final revision checklist and FAQs
- Can I state the grain of every table before joining?
- Can I distinguish WHERE from HAVING and explain NULL’s three-valued logic?
- Can I choose EXISTS, a join, a subquery or a CTE and defend the choice?
- Can I handle ties with ROW_NUMBER, RANK or DENSE_RANK?
- Can I avoid accidental row multiplication across order lines?
- Can I write an indexed date range and interpret EXPLAIN ANALYZE?
- Can I explain ACID, isolation anomalies, locks and deadlock retries?
- Can I normalize a schema and justify a deliberate denormalization?
- Can I parameterize untrusted values and apply least privilege?
- Can I state which syntax is MySQL-specific and provide a portable alternative?
How should I answer a SQL interview question?
Restate the required output and grain, name relevant tables and keys, write the simplest correct query, walk through a small example, handle nulls and ties, then discuss complexity and indexes. If requirements are ambiguous, ask whether cancelled orders count and whether ties should return multiple rows.
What is the most common SQL interview mistake?
Joining tables without reasoning about cardinality. A customer joined to orders and order items no longer has one row per customer. Aggregate at the intended grain first, or use EXISTS when you only need to test relationship existence.
References: MySQL 8.0 Reference Manual, MySQL optimization, InnoDB isolation levels, PostgreSQL SQL tutorial for portable concepts. Continue with the Python interview resource and Data Science roadmap.