<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Programming Valley</title>
    <description>The latest articles on DEV Community by Programming Valley (@programmingvalley).</description>
    <link>https://dev.to/programmingvalley</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4285213%2F6028dde0-d327-4aee-a426-3be3baea9332.jpg</url>
      <title>DEV Community: Programming Valley</title>
      <link>https://dev.to/programmingvalley</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/programmingvalley"/>
    <language>en</language>
    <item>
      <title>25 SQL Interview Questions Every Data Analyst Should Know in 2027</title>
      <dc:creator>Programming Valley</dc:creator>
      <pubDate>Sat, 05 Dec 2026 16:54:28 +0000</pubDate>
      <link>https://dev.to/programmingvalley/25-sql-interview-questions-every-data-analyst-should-know-in-2027-4m2n</link>
      <guid>https://dev.to/programmingvalley/25-sql-interview-questions-every-data-analyst-should-know-in-2027-4m2n</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fprogrammingvalley.com%2Fwp-content%2Fuploads%2F2026%2F12%2Fsql-interview-questions-2027-cover.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fprogrammingvalley.com%2Fwp-content%2Fuploads%2F2026%2F12%2Fsql-interview-questions-2027-cover.png" alt="Title card reading &amp;quot;25 SQL Interview Questions to Know&amp;quot; beside a code window with a DENSE_RANK query and its ranked result." width="799" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Tested answers to the questions that come up again and again, from NULL traps to window functions, with the detail that makes each answer stand out.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;SQL interviews for data roles keep coming back to the same few dozen ideas: how NULL behaves, what each join keeps, how window functions rank rows, and a handful of classic problems such as the second highest salary. Knowing the definitions is rarely enough. A strong answer shows that you have actually run the query and know where it breaks.&lt;/p&gt;

&lt;p&gt;This article covers 25 of those questions in five parts. Each answer gives a short explanation, a query you can run, its real output and one point that makes the answer stand out. Every query was run on PostgreSQL 16 against a small sample company database, and where MySQL, SQL Server, Oracle or SQLite behave differently, the answer says so.&lt;/p&gt;

&lt;p&gt;If you would rather practice offline, the free &lt;a href="https://programmingvalley.com/book/sql-interview-preparation-handbook-from-basics-to-advanced/" rel="noopener noreferrer"&gt;SQL Interview Preparation Handbook&lt;/a&gt; covers 80 questions and 12 hands-on problems built on the same sample database.&lt;/p&gt;

&lt;h2&gt;The sample database&lt;/h2&gt;

&lt;p&gt;The examples use a handful of small tables:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;employees&lt;/strong&gt; (8 rows): name, department, manager, salary and status. One salary is NULL, one employee has no department and two people earn the same 9,000.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;departments&lt;/strong&gt; (4 rows): Engineering, Sales, Marketing and HR. HR has no employees yet.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;customers&lt;/strong&gt; (5 rows) and &lt;strong&gt;orders&lt;/strong&gt; (7 rows): one customer has never ordered, and one order was cancelled.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;sales&lt;/strong&gt; (7 rows): daily sales by product, with two dates that have more than one sale.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Those edge cases are deliberate. They are exactly where many otherwise reasonable answers go wrong.&lt;/p&gt;

&lt;h3&gt;Six popular answers that are wrong, or only half right&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;“NOT IN and NOT EXISTS are interchangeable.”&lt;/strong&gt; A single NULL in the subquery makes NOT IN return no rows at all (question 10).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;“A UNIQUE column can hold only one NULL.”&lt;/strong&gt; That is SQL Server’s behavior. PostgreSQL, MySQL, Oracle and SQLite accept many NULLs (question 6).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;“TRUNCATE can’t be rolled back.”&lt;/strong&gt; In PostgreSQL and SQL Server it can, inside a transaction. MySQL and Oracle commit it immediately (question 5).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;“HAVING only works with GROUP BY.”&lt;/strong&gt; Without GROUP BY, the whole table is treated as one group (question 2).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;“You can filter on ROW_NUMBER() in WHERE.”&lt;/strong&gt; Window functions are calculated after WHERE, so the filter belongs in an outer query (question 19).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;“A primary key always creates a clustered index.”&lt;/strong&gt; That is the default in SQL Server and always true in MySQL’s InnoDB, but PostgreSQL stores rows in a heap and keeps the primary key as a separate index (question 23).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;Part 1: Query fundamentals&lt;/h2&gt;

&lt;p&gt;These questions often open a SQL interview. They look simple, which is exactly why small mistakes in the answers stand out.&lt;/p&gt;

&lt;h3&gt;1. In what order does SQL run a SELECT statement?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You write SELECT first, but the database evaluates it near the end. The logical order is FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT (window functions are computed here), DISTINCT, ORDER BY and finally LIMIT or OFFSET. The optimizer may physically do the work in a different order, but the result must be the same as if it followed these steps.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fprogrammingvalley.com%2Fwp-content%2Fuploads%2F2026%2F12%2Fsql-query-execution-order.png" class="article-body-image-wrapper"&gt;&lt;img width="800" height="1000" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fprogrammingvalley.com%2Fwp-content%2Fuploads%2F2026%2F12%2Fsql-query-execution-order.png" alt="Diagram comparing the order you write a SELECT statement with the order the database evaluates it: FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT with window functions, DISTINCT, ORDER BY, then LIMIT. Notes explain why SELECT aliases are not available in WHERE and why window functions cannot be filtered in WHERE."&gt;&lt;/a&gt;Written order versus logical order of a SELECT statement. Image: Programming Valley&lt;p&gt;&lt;/p&gt;

&lt;p&gt;That order explains a common error. An alias defined in SELECT does not exist yet when WHERE runs:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT name, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary &amp;gt; 100000;

-- ERROR:  column "annual_salary" does not exist&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Repeat the expression in WHERE instead. ORDER BY runs after SELECT, so it can use the alias:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT name, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 &amp;gt; 100000
ORDER BY annual_salary DESC;

-- name        | annual_salary
-- Sara Ali    |        180000
-- Mona Farid  |        132000
-- Omar Hassan |        108000
-- Lina Saleh  |        108000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; SQLite and DuckDB accept the alias in WHERE as an extension, so a query that works in a notebook can fail in PostgreSQL, MySQL, SQL Server or Oracle.&lt;/p&gt;

&lt;h3&gt;2. What is the difference between WHERE and HAVING?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;WHERE filters individual rows before they are grouped, so it cannot contain aggregate functions. HAVING filters groups after GROUP BY, so it usually does.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT d.dept_name,
       COUNT(*)                  AS staff,
       ROUND(AVG(e.salary), 0)   AS avg_salary
FROM employees e
JOIN departments d ON d.dept_id = e.dept_id
WHERE e.status = 'Active'          -- row filter, before grouping
GROUP BY d.dept_name
HAVING AVG(e.salary) &amp;gt; 8500;       -- group filter, after grouping

-- dept_name   | staff | avg_salary
-- Engineering |     3 |      11000
-- Sales       |     3 |       9000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sales shows 3 staff but an average of 9,000. One of its employees has a NULL salary: AVG ignores it, while COUNT(*) still counts the row.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Put plain row conditions in WHERE rather than HAVING, so fewer rows reach the grouping step. HAVING also works without GROUP BY: the whole table becomes one group, so &lt;code&gt;SELECT COUNT(*) FROM employees HAVING COUNT(*) &amp;gt; 5&lt;/code&gt; returns 8.&lt;/p&gt;

&lt;h3&gt;3. How does NULL behave in comparisons?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;NULL means unknown. Any comparison with it, even &lt;code&gt;NULL = NULL&lt;/code&gt;, returns UNKNOWN rather than TRUE or FALSE, and WHERE keeps only the rows that are TRUE. Rows can disappear without any error:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT COUNT(*) AS not_9000
FROM employees
WHERE salary &amp;lt;&amp;gt; 9000;

-- not_9000
--        5
-- 5, not 6: the NULL salary is neither equal nor unequal to 9000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Test for NULL with IS NULL or IS NOT NULL, or use the null-safe comparison IS DISTINCT FROM:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT COUNT(*) AS not_9000
FROM employees
WHERE salary IS DISTINCT FROM 9000;

-- not_9000
--        6&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; IS DISTINCT FROM works in PostgreSQL, SQL Server 2022 and later, and recent SQLite versions. MySQL has the null-safe operator &lt;code&gt;&amp;lt;=&amp;gt;&lt;/code&gt; instead: &lt;code&gt;NOT (salary &amp;lt;=&amp;gt; 9000)&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;4. What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;COUNT(*) counts rows. COUNT(column) counts the non-NULL values in that column, and COUNT(DISTINCT column) counts the different non-NULL values. SUM, AVG, MIN and MAX skip NULLs too, which can change an average:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT COUNT(*)                           AS all_rows,
       COUNT(salary)                      AS with_salary,
       COUNT(DISTINCT salary)             AS distinct_salaries,
       ROUND(AVG(salary), 2)              AS avg_salary,
       ROUND(AVG(COALESCE(salary, 0)), 2) AS avg_if_null_is_zero
FROM employees;

-- all_rows | with_salary | distinct_salaries | avg_salary | avg_if_null_is_zero
--        8 |           7 |                 6 |    9285.71 |                8125&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Ask whether a missing salary should count as zero or be left out: the two averages here differ by about 1,160. COUNT(1) returns the same number as COUNT(*), so there is no need to debate which is faster.&lt;/p&gt;

&lt;h3&gt;5. What is the difference between DELETE, TRUNCATE and DROP?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;DELETE removes the rows that match its WHERE clause, row by row, and fires any row-level delete triggers. TRUNCATE removes every row at once by releasing the table’s storage, which is much faster on large tables. DROP removes the table itself, including its structure and indexes.&lt;/p&gt;

&lt;p&gt;Whether TRUNCATE can be undone depends on the database. In PostgreSQL it can, inside a transaction:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BEGIN;
TRUNCATE TABLE returns;
SELECT COUNT(*) FROM returns;   -- 0
ROLLBACK;
SELECT COUNT(*) FROM returns;   -- 1: the row is back&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; SQL Server can also roll back TRUNCATE inside a transaction. MySQL and Oracle commit it immediately, as they do with other DDL statements, so “TRUNCATE can never be rolled back” is only half right.&lt;/p&gt;

&lt;h3&gt;6. What is the difference between a PRIMARY KEY and a UNIQUE constraint?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Both reject duplicate values. A primary key also forbids NULLs and identifies each row, so a table can have only one. A table can have several UNIQUE constraints, and they accept NULLs. In the sample database, &lt;code&gt;employees.email&lt;/code&gt; and &lt;code&gt;departments.dept_name&lt;/code&gt; are both UNIQUE:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;INSERT INTO employees (emp_id, name, email) VALUES (9,  'Test One', NULL);
INSERT INTO employees (emp_id, name, email) VALUES (10, 'Test Two', NULL);
-- Both rows are accepted: UNIQUE allows several NULLs here

INSERT INTO departments VALUES (5, 'Sales', 'Riyadh');
-- ERROR:  duplicate key value violates unique constraint "departments_dept_name_key"&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; How many NULLs a UNIQUE column accepts depends on the database: PostgreSQL, MySQL, Oracle and SQLite accept many, SQL Server only one. PostgreSQL 15 and later can allow just one with &lt;code&gt;UNIQUE NULLS NOT DISTINCT&lt;/code&gt;. For candidate, alternate and composite keys, see &lt;a href="https://programmingvalley.com/types-of-keys-in-a-database/" rel="noopener noreferrer"&gt;Types of Keys in a Database&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Part 2: Joins and set operations&lt;/h2&gt;

&lt;p&gt;Join questions test whether you know which rows each join keeps, and especially which rows it silently drops.&lt;/p&gt;

&lt;h3&gt;7. What are the different types of joins?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;INNER JOIN keeps only matching rows. LEFT JOIN keeps every row from the left table and fills the right side with NULLs where nothing matches; RIGHT JOIN does the same for the right table, and FULL JOIN keeps unmatched rows from both. CROSS JOIN pairs every row with every row. On employees (8 rows) and departments (4 rows) they return:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;INNER JOIN:&lt;/strong&gt; 7 rows. The employee without a department is dropped.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;LEFT JOIN:&lt;/strong&gt; 8 rows. That employee is kept, with a NULL department.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;RIGHT JOIN:&lt;/strong&gt; 8 rows. HR is kept, with no employee.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;FULL JOIN:&lt;/strong&gt; 9 rows. Both unmatched rows are kept.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;CROSS JOIN:&lt;/strong&gt; 32 rows, 8 × 4.&lt;/li&gt;
&lt;/ul&gt;

&lt;pre&gt;&lt;code&gt;SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON d.dept_id = e.dept_id
ORDER BY e.emp_id;

-- name         | dept_name
-- Sara Ali     | Engineering
-- Omar Hassan  | Engineering
-- Lina Saleh   | Engineering
-- Mona Farid   | Sales
-- Karim Nabil  | Sales
-- Nour Samir   | Sales
-- Hana Mostafa | Marketing
-- Adam Tarek   | NULL&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Quote row counts, not only definitions: “FULL JOIN returns 9 rows here because one employee has no department and one department has no employees” shows you know what each join keeps. MySQL has no FULL JOIN; combine a LEFT JOIN with the unmatched rows of a RIGHT JOIN using UNION ALL. For a diagram of each join, see &lt;a href="https://programmingvalley.com/sql-joins-explained-a-visual-guide/" rel="noopener noreferrer"&gt;SQL Joins Explained: A Visual Guide&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;8. Why does a LEFT JOIN sometimes return the same rows as an INNER JOIN?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Because a condition on the right-hand table was placed in WHERE. Unmatched rows have NULL in those columns, the condition evaluates to UNKNOWN and WHERE removes them. This query is meant to list every customer with their number of shipped orders:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT c.name, COUNT(o.order_id) AS shipped_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'Shipped'
GROUP BY c.name
ORDER BY c.name;

-- name         | shipped_orders
-- Acme Corp    |              3
-- Blue Sky LLC |              1
-- Delta Shop   |              1&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nile Traders, whose only order was cancelled, and Alpha Retail, which never ordered, have disappeared. Move the condition into ON, so it decides which orders match without removing any customers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT c.name, COUNT(o.order_id) AS shipped_orders
FROM customers c
LEFT JOIN orders o
       ON o.customer_id = c.customer_id
      AND o.status = 'Shipped'
GROUP BY c.name
ORDER BY c.name;

-- name         | shipped_orders
-- Acme Corp    |              3
-- Alpha Retail |              0
-- Blue Sky LLC |              1
-- Delta Shop   |              1
-- Nile Traders |              0&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Conditions on the table whose rows you want to keep belong in WHERE. Conditions on the optional table belong in ON.&lt;/p&gt;

&lt;h3&gt;9. What is a self join?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A join between a table and itself, using two aliases. It relates rows in the same table, such as employees and their managers. A classic interview version asks for employees who earn as much as or more than their manager:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.emp_id = e.manager_id
WHERE e.salary &amp;gt;= m.salary;

-- name       | salary | manager     | manager_salary
-- Lina Saleh |   9000 | Omar Hassan |           9000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; To list every employee with their manager, use a LEFT JOIN instead. An INNER JOIN drops the person at the top, who has no manager.&lt;/p&gt;

&lt;h3&gt;10. Why can NOT IN return no rows at all?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Because of NULL. &lt;code&gt;x NOT IN (a, b, NULL)&lt;/code&gt; means &lt;code&gt;x &amp;lt;&amp;gt; a AND x &amp;lt;&amp;gt; b AND x &amp;lt;&amp;gt; NULL&lt;/code&gt;, and the last comparison is never TRUE. This query looks for employees who manage nobody, but the top manager has a NULL manager_id:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-- Employees who manage nobody
SELECT name
FROM employees
WHERE emp_id NOT IN (SELECT manager_id FROM employees);

-- name
-- (0 rows)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;NOT EXISTS checks whether a matching row exists instead of comparing values, so NULLs do not affect it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT e.name
FROM employees e
WHERE NOT EXISTS (
  SELECT 1 FROM employees r WHERE r.manager_id = e.emp_id
);

-- name
-- Lina Saleh
-- Karim Nabil
-- Nour Samir
-- Hana Mostafa
-- Adam Tarek&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Returning the rows that have no match is called an anti-join. Write it with NOT EXISTS or with LEFT JOIN … WHERE key IS NULL. If you do use NOT IN, filter the NULLs out of the subquery with &lt;code&gt;WHERE manager_id IS NOT NULL&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;11. What is the difference between UNION and UNION ALL?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Both stack the results of two queries with matching columns. UNION removes duplicate rows, which costs an extra sort or hash step; UNION ALL keeps every row. Customer cities and department locations give 9 rows with UNION ALL but only 4 with UNION:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT city FROM customers
UNION
SELECT location FROM departments
ORDER BY city;

-- city
-- Alexandria
-- Cairo
-- Dubai
-- London&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;INTERSECT returns the rows found in both queries (Cairo, Dubai and London here) and EXCEPT returns the rows in the first query but not the second (Alexandria).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Use UNION ALL unless you actually need duplicates removed. Oracle used MINUS instead of EXCEPT before version 21c, and MySQL added INTERSECT and EXCEPT in version 8.0.31.&lt;/p&gt;

&lt;h2&gt;Part 3: Subqueries, CTEs and window functions&lt;/h2&gt;

&lt;p&gt;These questions move from writing queries to reasoning about them, and a few precise details separate good answers from great ones.&lt;/p&gt;

&lt;h3&gt;12. What is a correlated subquery?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A subquery that refers to a column of the outer query, so it is logically evaluated once for each outer row. Here it compares every employee with the average salary of their own department:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT e.name, e.dept_id, e.salary
FROM employees e
WHERE e.salary &amp;gt; (
  SELECT AVG(i.salary)
  FROM employees i
  WHERE i.dept_id = e.dept_id    -- refers to the outer row
);

-- name       | dept_id | salary
-- Sara Ali   |       1 |  15000
-- Mona Farid |       2 |  11000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Engineering averages 11,000 and Sales 9,000, so only Sara and Mona earn more than their department’s average. The employee with no department drops out, because &lt;code&gt;i.dept_id = NULL&lt;/code&gt; never matches.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Mention the window-function alternative: compute &lt;code&gt;AVG(salary) OVER (PARTITION BY dept_id)&lt;/code&gt; in a CTE, then filter. Optimizers often rewrite correlated subqueries as joins, so check the execution plan before claiming one version is faster.&lt;/p&gt;

&lt;h3&gt;13. What is a CTE, and how does a recursive CTE work?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Advanced&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A common table expression (CTE) is a named result set defined with WITH. It exists only for the statement that follows and makes long queries easier to read. A recursive CTE has two parts joined by UNION ALL: an anchor query that returns the starting rows, and a recursive step that joins back to the CTE until it adds no new rows. That makes it the standard tool for hierarchies such as an org chart:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;WITH RECURSIVE org AS (
  SELECT emp_id, name, 1 AS level,
         CAST(name AS VARCHAR(500)) AS chain
  FROM employees
  WHERE manager_id IS NULL                -- anchor: the top of the tree
  UNION ALL
  SELECT e.emp_id, e.name, o.level + 1,
         CAST(o.chain || ' &amp;gt; ' || e.name AS VARCHAR(500))
  FROM employees e
  JOIN org o ON e.manager_id = o.emp_id   -- recursive step
)
SELECT level, chain
FROM org
ORDER BY chain;

-- level | chain
--     1 | Sara Ali
--     2 | Sara Ali &amp;gt; Adam Tarek
--     2 | Sara Ali &amp;gt; Hana Mostafa
--     2 | Sara Ali &amp;gt; Mona Farid
--     3 | Sara Ali &amp;gt; Mona Farid &amp;gt; Karim Nabil
--     3 | Sara Ali &amp;gt; Mona Farid &amp;gt; Nour Samir
--     2 | Sara Ali &amp;gt; Omar Hassan
--     3 | Sara Ali &amp;gt; Omar Hassan &amp;gt; Lina Saleh&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; SQL Server and Oracle write recursive CTEs without the RECURSIVE keyword. If the data might contain a cycle, cap the depth in the recursive step, for example with &lt;code&gt;WHERE o.level &amp;lt; 20&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;14. What are window functions, and how do they differ from GROUP BY?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Both compute values over a set of rows. GROUP BY collapses each group into a single row, while a window function keeps every row and adds its result alongside. The OVER clause defines the window: PARTITION BY splits the rows into groups and ORDER BY sets the order within each group.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT name, dept_id, salary,
       ROUND(AVG(salary) OVER (PARTITION BY dept_id), 0) AS dept_avg,
       salary - ROUND(AVG(salary) OVER (PARTITION BY dept_id), 0) AS diff
FROM employees
WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC NULLS LAST;

-- name         | dept_id | salary | dept_avg |  diff
-- Sara Ali     |       1 |  15000 |    11000 |  4000
-- Omar Hassan  |       1 |   9000 |    11000 | -2000
-- Lina Saleh   |       1 |   9000 |    11000 | -2000
-- Mona Farid   |       2 |  11000 |     9000 |  2000
-- Karim Nabil  |       2 |   7000 |     9000 | -2000
-- Nour Samir   |       2 |   NULL |     9000 |  NULL
-- Hana Mostafa |       3 |   8000 |     8000 |     0&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;GROUP BY dept_id would return three rows. The window version keeps all seven employees who have a department and shows how far each one is from the department average.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Window functions are computed after WHERE, GROUP BY and HAVING, so you cannot filter on them in the WHERE clause of the same query (question 19).&lt;/p&gt;

&lt;h3&gt;15. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;All three number the rows of an ordered window. With a tie, ROW_NUMBER still gives unique numbers (3, 4), RANK gives the tied rows the same number and then skips one (3, 3, 5), and DENSE_RANK gives them the same number without a gap (3, 3, 4). Run it on salaries in PostgreSQL, though, and there is a surprise:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num,
       RANK()       OVER (ORDER BY salary DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees;

-- name         | salary | row_num | rnk | dense_rnk
-- Nour Samir   |   NULL |       1 |   1 |         1
-- Sara Ali     |  15000 |       2 |   2 |         2
-- Mona Farid   |  11000 |       3 |   3 |         3
-- Omar Hassan  |   9000 |       4 |   4 |         4
-- Lina Saleh   |   9000 |       5 |   4 |         4
-- Hana Mostafa |   8000 |       6 |   6 |         5
-- Karim Nabil  |   7000 |       7 |   7 |         6
-- Adam Tarek   |   6000 |       8 |   8 |         7&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;PostgreSQL treats NULL as larger than any value, so the missing salary ranks first in descending order. Oracle does the same, while MySQL, SQL Server and SQLite put NULLs last in descending order. Make the order explicit:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT name, salary,
       ROW_NUMBER() OVER (ORDER BY salary DESC NULLS LAST) AS row_num,
       RANK()       OVER (ORDER BY salary DESC NULLS LAST) AS rnk,
       DENSE_RANK() OVER (ORDER BY salary DESC NULLS LAST) AS dense_rnk
FROM employees;

-- name         | salary | row_num | rnk | dense_rnk
-- Sara Ali     |  15000 |       1 |   1 |         1
-- Mona Farid   |  11000 |       2 |   2 |         2
-- Omar Hassan  |   9000 |       3 |   3 |         3
-- Lina Saleh   |   9000 |       4 |   3 |         3
-- Hana Mostafa |   8000 |       5 |   5 |         4
-- Karim Nabil  |   7000 |       6 |   6 |         5
-- Adam Tarek   |   6000 |       7 |   7 |         6
-- Nour Samir   |   NULL |       8 |   8 |         7&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Which of the two 9,000 rows gets ROW_NUMBER 3 is not guaranteed. Add a tiebreaker such as &lt;code&gt;emp_id&lt;/code&gt; to the ORDER BY whenever the numbering must be repeatable. MySQL and SQL Server do not support NULLS LAST, but they already sort NULLs last in descending order.&lt;/p&gt;

&lt;h3&gt;16. How do you calculate a running total, and what is the RANGE trap?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Use SUM() as a window function ordered by date, adding PARTITION BY product_id if you need a running total per product. The trap: with ORDER BY and no explicit frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats all rows with the same date as a single step:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT sale_date, amount,
       SUM(amount) OVER (ORDER BY sale_date) AS default_frame,
       SUM(amount) OVER (ORDER BY sale_date, sale_id
                         ROWS BETWEEN UNBOUNDED PRECEDING
                                  AND CURRENT ROW) AS rows_frame
FROM sales
ORDER BY sale_date, sale_id;

-- sale_date  | amount | default_frame | rows_frame
-- 2026-01-01 |    900 |           950 |        900
-- 2026-01-01 |     50 |           950 |        950
-- 2026-01-02 |   1800 |          2750 |       2750
-- 2026-01-03 |     25 |          2775 |       2775
-- 2026-01-04 |    900 |          3975 |       3675
-- 2026-01-04 |    300 |          3975 |       3975
-- 2026-01-05 |     75 |          4050 |       4050&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;On 4 January the default frame shows 3,975 on both rows, because it includes every row that shares the current date. The ROWS frame adds one row at a time: 3,675, then 3,975.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; For running totals, write the ROWS frame explicitly and include a unique column in the ORDER BY. Explaining why the default frame gives odd results on duplicate dates shows you have debugged a real running total.&lt;/p&gt;

&lt;h3&gt;17. How do you compare a row with the previous one?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;With LAG, which reads a value from an earlier row in the window order; LEAD reads a later one. No self join is needed. Here is month-over-month revenue growth, excluding cancelled orders:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;WITH monthly AS (
  SELECT CAST(DATE_TRUNC('month', order_date) AS DATE) AS month,
         SUM(total_amount) AS revenue
  FROM orders
  WHERE status &amp;lt;&amp;gt; 'Cancelled'
  GROUP BY 1
)
SELECT month, revenue,
       LAG(revenue) OVER (ORDER BY month) AS prev_revenue,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
             / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS growth_pct
FROM monthly
ORDER BY month;

-- month      | revenue | prev_revenue | growth_pct
-- 2026-01-01 |     370 |         NULL |       NULL
-- 2026-02-01 |     300 |          370 |      -18.9
-- 2026-03-01 |     770 |          300 |      156.7&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Wrap the divisor in &lt;code&gt;NULLIF(…, 0)&lt;/code&gt; so a month with zero revenue returns NULL instead of a division-by-zero error. DATE_TRUNC is PostgreSQL syntax; SQL Server 2022 has DATETRUNC, and MySQL can use &lt;code&gt;DATE_FORMAT(order_date, '%Y-%m-01')&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Chapter 5 of the free &lt;a href="https://programmingvalley.com/book/sql-interview-preparation-handbook-from-basics-to-advanced/" rel="noopener noreferrer"&gt;SQL Interview Preparation Handbook&lt;/a&gt; covers window functions and advanced queries in nine questions, including PIVOT, MERGE and dynamic SQL, on the same sample data.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Part 4: Classic coding problems&lt;/h2&gt;

&lt;p&gt;Live-coding rounds often draw on a small set of classic problems. Each one tests a pattern, and how you handle ties, NULLs and empty results matters as much as the query itself.&lt;/p&gt;

&lt;h3&gt;18. How do you find the second (or Nth) highest salary?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Beginner&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The quick answer uses MAX twice:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary &amp;lt; (SELECT MAX(salary) FROM employees);

-- second_highest
--          11000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For any N, rank the salaries with DENSE_RANK so that ties do not use up a position. The two 9,000 salaries share third place:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT DISTINCT salary AS nth_highest
FROM (
  SELECT salary,
         DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
  WHERE salary IS NOT NULL
) ranked
WHERE rnk = 3;          -- change 3 to any N

-- nth_highest
--        9000&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Leave out &lt;code&gt;WHERE salary IS NOT NULL&lt;/code&gt; and PostgreSQL ranks the NULL salary first, so asking for the second highest returns 15,000, which is actually the highest.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Ask what to return when there is no Nth salary. The MAX version returns NULL; the DENSE_RANK version returns no rows.&lt;/p&gt;

&lt;h3&gt;19. How do you get the top N rows in each group?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Rank the rows inside each group with a window function, then filter in an outer query. Filtering in the same query fails, because window functions are computed after WHERE:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SELECT name, dept_id, salary
FROM employees
WHERE DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) &amp;lt;= 2;

-- ERROR:  window functions are not allowed in WHERE&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Put the ranking in a CTE and filter outside it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;WITH ranked AS (
  SELECT d.dept_name, e.name, e.salary,
         DENSE_RANK() OVER (PARTITION BY e.dept_id
                            ORDER BY e.salary DESC) AS rnk
  FROM employees e
  JOIN departments d ON d.dept_id = e.dept_id
  WHERE e.salary IS NOT NULL
)
SELECT dept_name, name, salary, rnk
FROM ranked
WHERE rnk &amp;lt;= 2
ORDER BY dept_name, rnk, name;

-- dept_name   | name         | salary | rnk
-- Engineering | Sara Ali     |  15000 |   1
-- Engineering | Lina Saleh   |   9000 |   2
-- Engineering | Omar Hassan  |   9000 |   2
-- Marketing   | Hana Mostafa |   8000 |   1
-- Sales       | Mona Farid   |  11000 |   1
-- Sales       | Karim Nabil  |   7000 |   2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;DENSE_RANK returns three Engineering rows because Omar and Lina tie for second place. Use ROW_NUMBER if the answer must contain exactly two rows per department, and say which tiebreaker decides.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Snowflake, BigQuery, DuckDB and Databricks support QUALIFY, which filters on a window function directly: &lt;code&gt;QUALIFY DENSE_RANK() OVER (…) &amp;lt;= 2&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;20. How do you find and delete duplicate rows?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Group by the columns that define a duplicate and keep the groups with more than one row. After adding a second Acme Corp row in Cairo:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;INSERT INTO customers VALUES (106, 'Acme Corp', NULL, 'Cairo', 'Egypt', NULL, NULL);

SELECT name, city, COUNT(*) AS copies
FROM customers
GROUP BY name, city
HAVING COUNT(*) &amp;gt; 1;

-- name      | city  | copies
-- Acme Corp | Cairo |      2&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To delete the extra copies but keep one, number the rows inside each group and delete every row after the first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DELETE FROM customers
WHERE customer_id IN (
  SELECT customer_id
  FROM (
    SELECT customer_id,
           ROW_NUMBER() OVER (PARTITION BY name, city
                              ORDER BY customer_id) AS rn
    FROM customers
  ) numbered
  WHERE rn &amp;gt; 1
);

-- DELETE 1: customer 106 is removed, 101 is kept&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Run the inner SELECT first and check the count, inside a transaction. If a column in the duplicate key can be NULL, remember that GROUP BY and PARTITION BY put all NULLs in one group, so rows that are simply missing a value can look like duplicates. The extra level of subquery also keeps the statement valid in MySQL, which does not let a DELETE read directly from the table it is deleting from.&lt;/p&gt;

&lt;h3&gt;21. How do you find consecutive days (gaps and islands)?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Advanced&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Number the dates in order and subtract the row number from each date. Within a run of consecutive days both values go up by one at each step, so the difference stays constant and identifies the streak:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;WITH days AS (
  SELECT DISTINCT sale_date
  FROM sales
  WHERE product_id = 1
),
grouped AS (
  SELECT sale_date,
         sale_date - CAST(ROW_NUMBER() OVER (ORDER BY sale_date) AS INT) AS grp
  FROM days
)
SELECT MIN(sale_date) AS streak_start,
       MAX(sale_date) AS streak_end,
       COUNT(*)       AS days
FROM grouped
GROUP BY grp
ORDER BY streak_start;

-- streak_start | streak_end | days
-- 2026-01-01   | 2026-01-02 |    2
-- 2026-01-04   | 2026-01-04 |    1&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Laptop sales happened on 1 and 2 January and then on 4 January, so there are two streaks: one of two days and one of a single day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; The same idea finds login streaks, consecutive months of activity and uptime windows. The date arithmetic differs by database: SQL Server uses &lt;code&gt;DATEADD(day, -ROW_NUMBER() OVER (ORDER BY sale_date), sale_date)&lt;/code&gt;, and SQLite needs &lt;code&gt;julianday()&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Part 5: Design, performance and transactions&lt;/h2&gt;

&lt;p&gt;These questions come up most often in data engineering and backend interviews, but indexes in particular matter for anyone who queries large tables.&lt;/p&gt;

&lt;h3&gt;22. What is normalization, and when would you denormalize?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Normalization organizes tables so that each fact is stored in one place, which prevents update anomalies. The first three normal forms cover most interviews:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;First normal form (1NF):&lt;/strong&gt; each column holds a single value, such as one phone number rather than a comma-separated list, and each row is unique.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Second normal form (2NF):&lt;/strong&gt; 1NF, and every non-key column depends on the whole primary key, not on part of a composite key.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Third normal form (3NF):&lt;/strong&gt; 2NF, and non-key columns depend only on the key, not on other non-key columns.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The sample database follows this. An employee row stores only dept_id, and each department’s location is stored once in departments. If the location were copied onto every employee row, moving a department would mean updating many rows, and missing one would leave the data inconsistent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Denormalization deliberately adds redundancy to make reads faster, as in data warehouse star schemas and reporting tables. Say what it costs: more storage and extra work to keep the copies in sync.&lt;/p&gt;

&lt;h3&gt;23. How do indexes speed up queries, and when do they not help?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;An index, usually a B-tree, lets the database find rows by key without reading the whole table. In a test on a 1-million-row table in PostgreSQL 16, looking up one customer’s orders took about 33 ms with a sequential scan. After an index was added on customer_id, the same query used it and finished in under 0.1 ms:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CREATE INDEX idx_big_orders_customer ON big_orders (customer_id);

EXPLAIN ANALYZE
SELECT * FROM big_orders WHERE customer_id = 4242;

-- Before the index:
--   Parallel Seq Scan on big_orders                Execution Time: ~33 ms
-- After the index:
--   Bitmap Index Scan on idx_big_orders_customer   Execution Time: ~0.03 ms&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An index stops helping when the query wraps the indexed column in an expression. With an index on created_at, the first filter below still scans the whole table (about 34 ms), while the second uses the index (about 0.3 ms). Both return the same 2,880 rows:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;-- Cannot use the index on created_at
WHERE CAST(created_at AS DATE) = DATE '2026-03-01'

-- Can use it
WHERE created_at &amp;gt;= DATE '2026-03-01'
  AND created_at &amp;lt;  DATE '2026-03-02'&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Name the costs: every index takes storage (the customer_id index added about 15% to the size of this table) and slows down INSERT, UPDATE and DELETE. Know the clustered versus non-clustered distinction too: a clustered index stores the table’s rows in key order, so there can be only one. For more on index types, see &lt;a href="https://programmingvalley.com/database-indexing/" rel="noopener noreferrer"&gt;Database Indexing Explained&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;24. What are ACID properties and transaction isolation levels?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Advanced&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;ACID describes what a transaction guarantees: &lt;strong&gt;atomicity&lt;/strong&gt; (all of its changes happen or none do), &lt;strong&gt;consistency&lt;/strong&gt; (it takes the database from one valid state to another without breaking constraints), &lt;strong&gt;isolation&lt;/strong&gt; (concurrent transactions interfere only as much as the isolation level allows) and &lt;strong&gt;durability&lt;/strong&gt; (committed changes survive a crash).&lt;/p&gt;

&lt;p&gt;Isolation levels decide how much of other transactions’ changes a transaction can see. Two PostgreSQL sessions show the difference. Session A reads an employee’s salary of 7,000, session B updates it to 7,500 and commits, and then session A reads it again:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;READ COMMITTED&lt;/strong&gt; (PostgreSQL’s default): the second read returns 7,500. This is a non-repeatable read.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;REPEATABLE READ:&lt;/strong&gt; the second read still returns 7,000, because session A works from a snapshot taken at its first query. It sees 7,500 only after it commits.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The four standard levels, from weakest to strongest, are READ UNCOMMITTED, which allows dirty reads; READ COMMITTED, which prevents them; REPEATABLE READ, which also prevents non-repeatable reads; and SERIALIZABLE, which also prevents phantom rows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Defaults differ: READ COMMITTED in PostgreSQL, SQL Server and Oracle, and REPEATABLE READ in MySQL’s InnoDB. PostgreSQL never allows dirty reads, even if you ask for READ UNCOMMITTED.&lt;/p&gt;

&lt;h3&gt;25. How do you prevent SQL injection?&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Intermediate&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Never build SQL by pasting user input into the query text. Use parameterized queries, so the input is always treated as a value and never as SQL. In this Python example with psycopg2, the same malicious input returns every customer when it is concatenated and none when it is passed as a parameter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;name = "x' OR '1'='1"

# Vulnerable: the input becomes part of the SQL
cur.execute(f"SELECT name FROM customers WHERE name = '{name}'")
print(len(cur.fetchall()))   # 5: every customer

# Safe: the input is passed as a parameter
cur.execute("SELECT name FROM customers WHERE name = %s", (name,))
print(len(cur.fetchall()))   # 0&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Interview tip:&lt;/strong&gt; Add the supporting layers: give the application’s database account only the permissions it needs, validate input, and never concatenate input into dynamic SQL inside stored procedures either. Placeholder styles vary by driver, for example &lt;code&gt;%s&lt;/code&gt; in psycopg2 and &lt;code&gt;?&lt;/code&gt; in sqlite3.&lt;/p&gt;

&lt;h2&gt;A quick cheat sheet of SQL interview patterns&lt;/h2&gt;

&lt;p&gt;Most coding questions are variations on a few patterns. When you read a question, match it to a pattern before you start typing:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fprogrammingvalley.com%2Fwp-content%2Fuploads%2F2026%2F12%2Fsql-interview-patterns-cheat-sheet.png" class="article-body-image-wrapper"&gt;&lt;img width="800" height="1000" src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fprogrammingvalley.com%2Fwp-content%2Fuploads%2F2026%2F12%2Fsql-interview-patterns-cheat-sheet.png" alt="Cheat sheet matching nine common SQL interview tasks to the pattern that solves them, including DENSE_RANK for the Nth highest value, NOT EXISTS for rows with no match, LAG for comparing with the previous row and a recursive CTE for hierarchies."&gt;&lt;/a&gt;Nine patterns behind most SQL coding questions. Image: Programming Valley&lt;p&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Nth highest value:&lt;/strong&gt; DENSE_RANK() in a subquery, filtered on the rank.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Top N per group:&lt;/strong&gt; DENSE_RANK() or ROW_NUMBER() OVER (PARTITION BY …), filtered in an outer query.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Rows with no match:&lt;/strong&gt; NOT EXISTS, or LEFT JOIN … WHERE key IS NULL.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Duplicates:&lt;/strong&gt; GROUP BY … HAVING COUNT(*) &amp;gt; 1; to delete them, ROW_NUMBER() and rn &amp;gt; 1.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Running total:&lt;/strong&gt; SUM() OVER (ORDER BY … ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Compare with the previous row:&lt;/strong&gt; LAG() or LEAD().&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Consecutive streaks:&lt;/strong&gt; the date minus ROW_NUMBER() (gaps and islands).&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Hierarchies:&lt;/strong&gt; WITH RECURSIVE.&lt;/li&gt;

&lt;li&gt;
&lt;strong&gt;Compare with a group average:&lt;/strong&gt; AVG() OVER (PARTITION BY …).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the interview itself, name the pattern before you write it, check the edge cases out loud (NULLs, ties and empty results) and say which database your syntax assumes.&lt;/p&gt;

&lt;h2&gt;Go deeper&lt;/h2&gt;

&lt;p&gt;These 25 answers cover some of the most common SQL interview questions. To keep going, Programming Valley’s free &lt;a href="https://programmingvalley.com/book/sql-interview-preparation-handbook-from-basics-to-advanced/" rel="noopener noreferrer"&gt;SQL Interview Preparation Handbook&lt;/a&gt; has 80 questions and 12 hands-on problems on the same sample database. Each one comes with a short answer to say first, a fuller explanation and tested SQL, and the book adds cheat sheets for query order, joins and window functions, a table of dialect differences across PostgreSQL, SQL Server, MySQL and Oracle, and a 7-day study plan. It is a 112-page PDF, free to download without signing up.&lt;/p&gt;

&lt;p&gt;If an answer here could be clearer, or your interviews keep asking something that is not on this list, leave a comment below.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This article was originally published on &lt;a href="https://programmingvalley.com/sql-interview-questions-every-data-analyst-should-know/" rel="noopener noreferrer"&gt;Programming Valley&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>sql</category>
      <category>database</category>
      <category>datascience</category>
      <category>career</category>
    </item>
  </channel>
</rss>
