About Us Contact Us Privacy Policy Disclaimer Pakistan Teaching Jobs 2026-27

60 SQL Interview Questions and Answers for Beginners (2027) — With Practice Queries

SQL is the one skill that shows up in almost every data job interview — data analyst, data scientist, data engineer, even product and business roles. DevGlobalJobs, citing O*NET data, reported that SQL was named in about 758,000 of 46.9 million US job postings in 2025. That figure is reported, not independently verified by us, but the direction is not in doubt: if you want a data job, you will be asked SQL, and you will be asked to write it, not just talk about it.

This bank gives you 60 questions and answers, organised the way interviews actually unfold: basics first, then filtering, then JOINs, then aggregation, then subqueries, then changing data. Every technical question comes with a query you can run. At the end there is a 20-question MCQ self-test.

If SQL is part of a bigger career change, read this bank alongside our data analyst roadmap for beginners, which puts SQL in its place — after Excel, before Power BI and Python. And if you want to sharpen the spreadsheet side too, our Google Sheets formulas cheat sheet covers the 25 formulas you will actually use.

A programmer engaged in coding on a laptop in a tech-focused workspace, for SQL interview questions and answers for beginners border=

Photo by Matias Mango on Pexels

The practice tables — set these up first

Reading SQL without running it is like learning swimming from a book. Every query in this bank runs against six small tables. Set them up in any free SQLite editor (or SQLite online) and you can run every example as you read.

CREATE TABLE departments (
    department_id INTEGER PRIMARY KEY,
    department_name TEXT NOT NULL,
    location TEXT
);

CREATE TABLE employees (
    employee_id INTEGER PRIMARY KEY,
    first_name TEXT,
    last_name TEXT,
    email TEXT UNIQUE,
    salary REAL,
    hire_date TEXT,
    department_id INTEGER,
    manager_id INTEGER,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    customer_name TEXT,
    country TEXT,
    email TEXT
);

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER,
    order_date TEXT,
    total_amount REAL,
    status TEXT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

CREATE TABLE products (
    product_id INTEGER PRIMARY KEY,
    product_name TEXT,
    category TEXT,
    price REAL,
    stock INTEGER
);

CREATE TABLE order_items (
    order_item_id INTEGER PRIMARY KEY,
    order_id INTEGER,
    product_id INTEGER,
    quantity INTEGER,
    unit_price REAL,
    FOREIGN KEY (order_id) REFERENCES orders(order_id),
    FOREIGN KEY (product_id) REFERENCES products(product_id)
);

The data: 5 departments (Sales, Engineering, HR, Marketing, Finance); 11 employees — including Henry Taylor, whose salary is deliberately NULL, and Karen Young, who has no department; 6 customers; 10 orders; 7 products; 10 order items. The two deliberate gaps (a NULL salary, an employee with no department) are what make the NULL and LEFT JOIN questions work — real data is messy like this, and interviewers love testing whether you notice.

A note on dialects: SQL has one standard and several dialects. Everything here runs in SQLite, which is free and needs no setup. Where MySQL or SQL Server differ — RIGHT JOIN, FULL OUTER JOIN, TRUNCATE, CONCAT — the question says so. In an interview, if you are unsure which database the company uses, say so and give the standard version.

Section A — SQL basics (questions 1–12)

1. What is SQL?

SQL (Structured Query Language) is the standard language for talking to a relational database: a database that stores data in tables of rows and columns. You use it to ask questions (SELECT), add data (INSERT), change data (UPDATE), remove data (DELETE), and define the tables themselves (CREATE TABLE). It was standardised in the 1980s and it has outlasted every framework that was supposed to replace it — which is why it is still the first thing interviewers test.

2. What is the difference between SQL and MySQL?

SQL is the language. MySQL is one database system that speaks it — like English is a language and a particular newspaper is one publication in English. Others include PostgreSQL, Microsoft SQL Server, Oracle and SQLite. The core of the language (SELECT, WHERE, JOIN, GROUP BY) is the same everywhere; the differences are in extras like functions, data types and which joins are supported. Learn standard SQL first, then learn your employer's dialect.

3. What is a database, a table, a row and a column?

A database is the whole collection of related data — our company database. A table is one kind of thing inside it — employees. A row (or record) is one item — Alice Johnson's employee record. A column (or field) is one attribute of every item — salary. A table is like a spreadsheet: columns across the top, one row per item.

4. How do you get data out of a table?

With SELECT, naming the columns you want and the table they come from:

SELECT first_name, last_name
FROM employees;
Alice    Johnson
Bob      Smith
Carol    Davis
...

Always name the columns you need. SELECT * is fine while learning, but in production it fetches columns nobody asked for — see question 60.

5. How do you select all columns?

SELECT *
FROM employees;

The * means "every column". Useful for a quick look at a table you do not know yet; a bad habit in real queries and in interviews, where it suggests you did not think about what you need.

6. What is a primary key?

A primary key is the column (or combination of columns) that uniquely identifies each row. In our employees table it is employee_id: no two employees can share one, and it can never be NULL. You declare it when you create the table:

employee_id INTEGER PRIMARY KEY

Interviewers often follow up: can a table have two primary keys? No — one primary key per table, though it can be made of several columns together (a composite key). It can, however, have many UNIQUE columns, like our email.

7. What is a foreign key?

A foreign key is a column in one table that points at the primary key of another table — it is how tables are linked. In employees, department_id is a foreign key pointing at departments.department_id. It stops you inserting an employee into department 99 when no such department exists (if the database enforces it), and it is what makes JOINs possible. The line in our schema is:

FOREIGN KEY (department_id) REFERENCES departments(department_id)

8. What are the main SQL data types?

The common ones, across dialects: INTEGER (whole numbers), REAL / DECIMAL (numbers with decimals — use DECIMAL for money), TEXT / VARCHAR (strings — VARCHAR(100) means up to 100 characters), DATE / DATETIME (dates and times), and BOOLEAN (true/false). The exact names vary: SQL Server calls text NVARCHAR, Oracle calls it VARCHAR2. In an interview, naming INT, VARCHAR, DATE and DECIMAL is enough.

9. What is the difference between DELETE, TRUNCATE and DROP?

  • DELETE FROM employees WHERE ... removes rows. With no WHERE it removes all rows, but the table and its structure survive, and it can be rolled back inside a transaction.
  • TRUNCATE TABLE employees removes all rows at once, faster than DELETE, and resets auto-increment counters — but it cannot have a WHERE, and in most databases it cannot be rolled back. (SQLite does not have TRUNCATE at all; DELETE FROM employees is the equivalent there.)
  • DROP TABLE employees removes the whole table — structure, data, indexes, everything. There is no undo.

The one-line version interviewers remember: DELETE removes rows, TRUNCATE empties a table, DROP deletes the table itself.

10. What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY. This query finds departments with more than two employees:

SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 2;
department_id  headcount
1              3
2              4

You cannot put COUNT(*) > 2 in a WHERE — at the WHERE stage the groups do not exist yet. This is one of the most-asked beginner questions in SQL interviews, and the most common wrong answer is "they are the same".

11. What is NULL, and how do you test for it?

NULL means "no value" — not zero, not an empty string, just unknown. Henry Taylor's salary is NULL because it was never entered. You test for it with IS NULL, never with = NULL (which is itself NULL, never true):

SELECT first_name, last_name
FROM employees
WHERE salary IS NULL;
Henry  Taylor

12. What is the difference between DISTINCT and GROUP BY?

Both can remove duplicates, but they do different jobs. DISTINCT removes duplicate rows from the result:

SELECT DISTINCT department_id
FROM employees;
2, 1, 3, 4, 5, NULL

Note that NULL appears once — DISTINCT treats all NULLs as one value. GROUP BY groups rows so you can aggregate them (COUNT, SUM, AVG per group). If all you want is a list of unique values, DISTINCT is the clearer tool; if you want a calculation per group, you need GROUP BY.

Section B — Filtering, sorting and functions (questions 13–22)

13. How do you filter rows?

With WHERE, which keeps only the rows that match a condition:

SELECT first_name, last_name, salary
FROM employees
WHERE salary > 70000;
Alice  Johnson  75000
Carol  Davis    82000
Emma   Brown    90000
Grace  Lee      71000

14. How do AND, OR and NOT work?

They combine conditions. AND needs both to be true; OR needs at least one; NOT flips a condition:

SELECT first_name, last_name
FROM employees
WHERE salary > 60000 AND department_id = 2;
Alice  Johnson
Carol  Davis
Emma   Brown
Ivy    Chen

Watch out for mixing AND and OR without brackets: AND binds tighter than OR, so WHERE a = 1 OR b = 2 AND c = 3 means a = 1 OR (b = 2 AND c = 3). When in doubt, add brackets — interviewers notice.

15. How do you find values in a range?

With BETWEEN, which is inclusive at both ends:

SELECT first_name, salary
FROM employees
WHERE salary BETWEEN 60000 AND 80000;

That returns 6 employees: Alice, Bob, Grace, Ivy, Jack and Karen — Bob at exactly 60,000 is included, and so is anyone at exactly 80,000. BETWEEN is shorthand for salary >= 60000 AND salary <= 80000.

16. How do you match against a list of values?

With IN:

SELECT first_name, department_id
FROM employees
WHERE department_id IN (1, 2);

That returns the 7 employees in Sales or Engineering. IN is cleaner than a chain of ORs, and it works with a subquery too — see question 44.

17. How do you search for a pattern in text?

With LIKE and wildcards: % matches any number of characters, _ matches exactly one:

SELECT first_name, last_name
FROM employees
WHERE last_name LIKE 'S%';
Bob  Smith

'S%' means "starts with S". '%son%' means "contains son anywhere". '_ohnson' would match "Johnson" with any single first character. In most databases LIKE is case-insensitive for plain text; if you need a case-sensitive match, check the database's collation.

18. How do you sort results?

With ORDER BY. ASC (ascending) is the default; DESC reverses it. The three highest-paid employees:

SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;
Emma   Brown   90000
Carol  Davis   82000
Alice  Johnson 75000

You can sort by several columns — ORDER BY department_id, salary DESC sorts by department first, then by salary within each department. And you can sort by a column you did not select.

19. How do you limit the number of rows returned?

With LIMIT (SQLite, MySQL, PostgreSQL) — or TOP in SQL Server:

SELECT first_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;

That returns Emma, Carol, Alice, Grace and Ivy. LIMIT 5 OFFSET 10 skips the first 10 rows and returns the next 5 — the standard way to page through results. Always pair LIMIT with ORDER BY: without it, "the first 5 rows" means whichever rows the database happens to return first, which is not guaranteed.

20. How do you combine text or change its case?

With string functions. UPPER() and LOWER() change case; concatenation joins values together. In SQLite and PostgreSQL you join with ||; in MySQL you use the CONCAT() function:

SELECT first_name || ' ' || last_name AS full_name
FROM employees;
Alice Johnson
Bob Smith
Carol Davis
...

AS full_name gives the computed column a name — always do this, or the column arrives with an unreadable generated name.

21. What are aggregate functions?

Functions that collapse many rows into one value: COUNT() (how many), SUM() (total), AVG() (average), MIN() (smallest), MAX() (largest):

SELECT COUNT(*), AVG(salary), MIN(salary), MAX(salary), SUM(salary)
FROM employees;
COUNT(*)  AVG(salary)  MIN(salary)  MAX(salary)  SUM(salary)
11        69000        54000        90000        690000

Two things to notice: the average is exactly 69,000, and it is computed over 10 salaries, not 11 — AVG ignores NULL. That is question 22's trap in disguise.

22. What is the difference between COUNT(*) and COUNT(column)?

COUNT(*) counts rows. COUNT(column) counts rows where that column is not NULL:

SELECT COUNT(*) AS all_rows, COUNT(salary) AS with_salary
FROM employees;
all_rows  with_salary
11        10

There are 11 employees but only 10 salaries, because Henry Taylor's salary is NULL. If an interviewer asks "how many employees are there?", the answer is COUNT(*) — and if they ask "how many employees have a salary recorded?", it is COUNT(salary).

Close-up of a network server rack with blinking LEDs, where the databases SQL queries run border=

Photo by Brett Sayles on Pexels

Section C — JOINs (questions 23–32)

JOINs are the heart of SQL interviews. If you can do nothing else, learn these.

23. What is a JOIN?

A JOIN combines rows from two tables using a related column — usually a foreign key matching a primary key. Our employees.department_id matches departments.department_id, so a JOIN can show each employee next to their department's name instead of a bare number. Without JOINs you would need one query per table and a lot of manual matching.

24. What is an INNER JOIN?

It returns only the rows that match in both tables:

SELECT e.first_name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

Alice → Engineering, Bob → Sales, Carol → Engineering, and so on — 10 rows. Karen Young does not appear: she has no department_id, so there is no matching department row. e and d are table aliases — short names that keep the query readable. The word INNER is optional; JOIN alone means INNER JOIN.

25. What is a LEFT JOIN?

It returns all rows from the left table, plus matching rows from the right — with NULL where there is no match:

SELECT e.first_name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;

This returns all 11 employees, including Karen Young with a NULL department name. The classic interview use: "find customers who never placed an order" is a LEFT JOIN from customers to orders, keeping the rows where the order side is NULL.

26. What is a RIGHT JOIN?

The mirror image of LEFT JOIN: all rows from the right table, plus matches from the left. It returns every department, even one with no employees:

SELECT e.first_name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;

One version note: RIGHT JOIN works in SQLite 3.39.0 and later (June 2022), as it does in MySQL and PostgreSQL; older SQLite versions did not have it. The LEFT JOIN with the tables swapped gives the same result and works in every version. Interviewers sometimes ask this precisely to see whether you know the dialect limits.

27. What is a FULL OUTER JOIN?

It returns all rows from both tables, with NULL on whichever side has no match: every employee (even Karen, with no department) and every department (even one with no employees). MySQL does not support it directly — you fake it with a UNION of a LEFT JOIN and a RIGHT JOIN. SQLite supports FULL OUTER JOIN from version 3.39.0 (June 2022) onward; older versions did not. It is the rarest JOIN in real work, but a favourite interview question precisely because candidates overcomplicate it.

28. What is a CROSS JOIN?

It pairs every row of one table with every row of the other — a cartesian product. Five departments times seven products is 35 combinations:

SELECT d.department_name, p.product_name
FROM departments d
CROSS JOIN products p;

Genuine uses are rare (generating combinations, like every size × every colour). The interview point is the warning: a CROSS JOIN on two big tables explodes — a million rows times a million rows is a trillion — and forgetting the ON clause of an INNER JOIN accidentally creates one. That is the classic "my query returned a billion rows" bug.

29. What is a SELF JOIN?

A table joined to itself — used when rows in a table relate to other rows in the same table. Our employees have managers who are also employees, so a SELF JOIN shows each person next to their manager:

SELECT e.first_name AS employee, m.first_name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.employee_id;
employee  manager
Bob       Alice
Carol     Alice
David     Bob
Emma      Alice
Grace     Bob
...

Alice and Frank have no manager (manager_id is NULL), so an INNER JOIN drops them; a LEFT JOIN would keep them with a NULL manager. The aliases e and m are essential here — without them, the database cannot tell the two copies of employees apart.

30. Can you combine a JOIN with a WHERE?

Yes — JOIN first, then WHERE filters the joined result. Orders over 1,000 with the customer's name:

SELECT c.customer_name, o.order_id, o.total_amount
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
WHERE o.total_amount > 1000;
Acme Corp       101  1200.00
Global Traders  103  2300.00
Tech Solutions  105  1750.00
Pacific Imports 107  3200.00
Acme Corp       110  2100.00

31. INNER JOIN vs LEFT JOIN — which one do I use?

Ask one question: do I want rows that have no match? If no — only employees who actually belong to a department — use INNER JOIN. If yes — every employee, even one with no department yet — use LEFT JOIN. Karen Young is the test case in our data: INNER JOIN returns 10 rows, LEFT JOIN returns 11. Most real-world reporting queries are LEFT JOINs, because dropping unmatched rows silently is how reports go wrong.

32. JOIN or subquery — which is better?

Often both give the same answer. Employees in Engineering, two ways:

-- With a subquery
SELECT first_name
FROM employees
WHERE department_id IN (
    SELECT department_id FROM departments WHERE department_name = 'Engineering'
);

-- With a JOIN
SELECT e.first_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id
WHERE d.department_name = 'Engineering';

Both return Alice, Carol, Emma and Ivy. As a rule of thumb, use a JOIN when you need columns from both tables, and a subquery when you only need a list of values to filter by. Performance differences are usually tiny on small data; readability is the real deciding factor.

Section D — GROUP BY and aggregation (questions 33–42)

33. How does GROUP BY work?

It collects rows that share a value into groups, so aggregate functions can run per group. Employees per department:

SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id;
department_id  headcount
NULL           1
1              3
2              4
3              1
4              1
5              1

Note the NULL group: Karen Young, with no department, forms a group of her own. Every column in the SELECT must either be in the GROUP BY or wrapped in an aggregate function — SELECT first_name, COUNT(*) ... GROUP BY department_id is an error in most databases, because which first name would it show for a group of four?

34. How do you filter groups?

With HAVING (see question 10). Departments with more than two employees:

SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 2;

Departments 1 (3 people) and 2 (4 people). The order of operations to remember: WHERE → GROUP BY → HAVING → ORDER BY.

35. How do you find the average salary per department?

SELECT department_id, ROUND(AVG(salary), 2) AS avg_salary
FROM employees
GROUP BY department_id;
department_id  avg_salary
NULL           66000.00
1              61333.33
2              78750.00
3              54000.00
4              71000.00
5              NULL

Department 5 (Finance) averages to NULL — its only employee, Henry, has a NULL salary, and the average of no values is NULL, not zero. That is exactly the kind of detail an interviewer hopes you will spot.

36. How do you show department names with the average salary?

JOIN first, then GROUP BY the name:

SELECT d.department_name, ROUND(AVG(e.salary), 2) AS avg_salary
FROM departments d
INNER JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name;
Engineering  78750.00
Finance      NULL
HR           54000.00
Marketing    71000.00
Sales        61333.33

37. Which department has the most employees?

GROUP BY, count, sort by the count, take the top row:

SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id
ORDER BY headcount DESC
LIMIT 1;
2  4

Engineering, with 4 people.

38. How do you find the highest and lowest salary in each department?

SELECT department_id, MIN(salary) AS lowest, MAX(salary) AS highest
FROM employees
GROUP BY department_id;

Engineering runs from 68,000 to 90,000; Sales from 58,000 to 65,000. MIN and MAX also work on text and dates — MIN(hire_date) gives the earliest hire.

39. How do you find how much each customer spent in total?

Join customers to orders, then sum per customer:

SELECT c.customer_name, SUM(o.total_amount) AS total_spent
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_name
ORDER BY total_spent DESC;
Acme Corp       4150.50
Pacific Imports 3200.00
Global Traders  2940.00
Tech Solutions  2200.00
Euro Goods      980.00
Noor Traders    150.00

Acme Corp is the biggest customer. Notice this is a JOIN plus a GROUP BY plus an ORDER BY — the three pieces combine constantly in real interview questions.

40. Can you GROUP BY more than one column?

Yes — it creates one group per combination. Orders by status:

SELECT status, COUNT(*) AS num_orders, SUM(total_amount) AS total_value
FROM orders
GROUP BY status;
Cancelled  1  980.00
Completed  5  7640.50
Pending    2  600.00
Shipped    2  4400.00

Grouping by status, YEAR(order_date) would give one row per status per year — the standard shape of a monthly or yearly report.

41. What is a window function?

A function that calculates across a set of rows without collapsing them the way GROUP BY does. ROW_NUMBER() ranks employees inside each department while keeping every row visible:

SELECT first_name, salary,
       ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
FROM employees
WHERE department_id = 2;
Emma   90000  1
Carol  82000  2
Alice  75000  3
Ivy    68000  4

PARTITION BY is "restart the ranking for each department"; ORDER BY inside the OVER clause decides the ranking order. The key difference from GROUP BY: the query still returns one row per employee, with the rank attached.

42. What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

All three rank rows, but they treat ties differently:

  • ROW_NUMBER() gives 1, 2, 3, 4 — never a tie, even for equal values.
  • RANK() gives tied rows the same rank, then skips the next number: 1, 2, 2, 4.
  • DENSE_RANK() gives tied rows the same rank and does not skip: 1, 2, 2, 3.
SELECT first_name, salary,
       RANK() OVER (ORDER BY salary DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
ORDER BY salary DESC;

Our salaries are all different, so the top of the list reads Emma 1/1, Carol 2/2, Alice 3/3. The difference only shows when two people share a salary — which is exactly when the interviewer asks. Use DENSE_RANK() for "second-highest salary" problems (question 50), because it survives ties.

Section E — Subqueries, set operations and CASE (questions 43–52)

43. What is a subquery?

A query inside another query. The inner query runs first and its result is used by the outer query. Employees earning more than the average salary:

SELECT first_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Alice  75000
Carol  82000
Emma   90000
Grace  71000

The average is 69,000, so four people qualify. Subqueries can appear in SELECT, FROM, WHERE and HAVING — if you can write the inner query on its own, you can use it as a subquery.

44. How do you use a subquery with IN?

To filter by a list the subquery produces. Customers who have placed at least one order:

SELECT customer_name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders);

All six customers have ordered, so all six names come back. If a customer had never ordered, they would be missing — which is precisely how you find them, by flipping it to NOT IN (careful with NULLs — see question 46's NOT EXISTS alternative).

45. Can a subquery go in the FROM clause?

Yes — it becomes a temporary table, called a derived table, which you must alias. Customers who spent more than 2,000 in total:

SELECT customer_name, total_spent
FROM (
    SELECT customer_id, SUM(total_amount) AS total_spent
    FROM orders
    GROUP BY customer_id
) t
INNER JOIN customers c ON t.customer_id = c.customer_id
WHERE total_spent > 2000;
Acme Corp       4150.50
Global Traders  2940.00
Tech Solutions  2200.00
Pacific Imports 3200.00

46. What is the difference between EXISTS and IN?

Both test whether rows exist, but they work differently. EXISTS stops as soon as it finds one matching row, and it handles NULL correctly where NOT IN does not. Customers with at least one completed order:

SELECT customer_name
FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.customer_id AND o.status = 'Completed'
);
Acme Corp
Global Traders
Tech Solutions
Pacific Imports

The classic trap: WHERE customer_id NOT IN (SELECT customer_id FROM orders) returns nothing at all if the subquery contains a single NULL — because NOT IN against NULL is unknown, not true. NOT EXISTS has no such problem. Interviewers ask this one to separate people who memorised syntax from people who understand NULL.

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

Both stack the results of two queries on top of each other. UNION removes duplicates; UNION ALL keeps them (and is faster, because it skips the de-duplication step):

SELECT first_name AS name FROM employees
UNION
SELECT customer_name FROM customers;

The two queries must return the same number of columns, with compatible types. Use UNION ALL unless you have a reason to remove duplicates — it is the faster default.

48. What are INTERSECT and EXCEPT?

Set operations, like UNION, but for overlap and difference:

-- Department IDs that appear in both tables
SELECT department_id FROM employees
INTERSECT
SELECT department_id FROM departments;
1, 2, 3, 4, 5
-- Products that have never been ordered
SELECT product_id FROM products
EXCEPT
SELECT product_id FROM order_items;
5

The Desk (product 5) is the only product nobody has ordered. Note: MySQL does not support INTERSECT or EXCEPT — the workaround is INNER JOIN for INTERSECT and LEFT JOIN ... IS NULL or NOT EXISTS for EXCEPT.

49. What is a correlated subquery?

A subquery that refers to the outer query — it runs once per row of the outer query, not once in total. Employees earning more than their own department's average:

SELECT e.first_name, e.salary, e.department_id
FROM employees e
WHERE e.salary > (
    SELECT AVG(salary) FROM employees
    WHERE department_id = e.department_id
);
Bob    65000  1
Carol  82000  2
Emma   90000  2

Bob earns 65,000 against a Sales average of 61,333.33, so he qualifies — even though he is below the company average of 69,000. The e.department_id inside the subquery is the correlation: the subquery re-runs for each employee with that employee's department. Correlated subqueries are slower than JOINs on big tables, and interviewers ask about them because they test whether you can read the inner query's dependency.

50. How do you find the second-highest salary?

The classic interview question — and the one most often answered wrong. The safe way:

SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
82000

The common wrong answer is ORDER BY salary DESC LIMIT 1 OFFSET 1, which returns the second row, not the second salary — if two people share the top salary of 90,000, it returns 90,000 again. The robust way is DENSE_RANK() (question 42), which handles ties correctly:

SELECT salary
FROM (
    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r
    FROM employees
) ranked
WHERE r = 2;

51. What is a CASE expression?

SQL's IF statement — it returns different values depending on conditions. Salary bands:

SELECT first_name, salary,
       CASE
           WHEN salary >= 80000 THEN 'High'
           WHEN salary >= 65000 THEN 'Medium'
           ELSE 'Entry'
       END AS band
FROM employees;
Alice  75000  Medium
Bob    65000  Medium
Carol  82000  High
David  58000  Entry
Emma   90000  High

CASE is evaluated top to bottom and stops at the first match. It is the standard way to bucket values, and it works inside SELECT, WHERE and ORDER BY.

52. What is a CTE (Common Table Expression)?

A named temporary result you define with WITH and then use like a table — mainly a readability tool that turns a nested subquery into something a human can follow:

WITH high_earners AS (
    SELECT first_name, salary
    FROM employees
    WHERE salary > 75000
)
SELECT * FROM high_earners;
Carol  82000
Emma   90000

CTEs can also be chained (WITH a AS (...), b AS (...)) and, in most databases, written recursively for hierarchies. In an interview, reaching for a CTE instead of a triple-nested subquery signals that you write SQL other people can read.

Section F — Changing data and defining tables (questions 53–60)

53. How do you add a row?

With INSERT, naming the columns and the values in the same order:

INSERT INTO departments (department_id, department_name, location)
VALUES (6, 'Support', 'Austin');

If you list every column, the column names are optional — but always list them. An INSERT without a column list breaks the moment someone adds a column to the table.

54. How do you change existing data?

With UPDATE — and almost always with a WHERE:

UPDATE employees
SET salary = 70000
WHERE employee_id = 10;

The WHERE is the whole point. UPDATE employees SET salary = 70000 with no WHERE gives every employee a salary of 70,000. In an interview, say out loud that you would check the WHERE twice and run the SELECT version of it first. In production, run it inside a transaction (question 59).

55. How do you remove rows?

With DELETE, again with a WHERE:

DELETE FROM employees
WHERE employee_id = 11;

Same warning as UPDATE: no WHERE means every row goes. DELETE removes rows only — the table, its columns and its indexes survive (contrast with DROP in question 9).

56. How do you create a table?

With CREATE TABLE, declaring each column, its type, and its constraints — our employees table from the setup section is the example:

CREATE TABLE employees (
    employee_id INTEGER PRIMARY KEY,
    first_name TEXT,
    last_name TEXT,
    email TEXT UNIQUE,
    salary REAL,
    hire_date TEXT,
    department_id INTEGER,
    manager_id INTEGER,
    FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

The constraints are the interesting part: PRIMARY KEY for identity, UNIQUE so no two employees share an email, NOT NULL where a value is mandatory, FOREIGN KEY to keep the links honest.

57. How do you change a table that already exists?

With ALTER TABLE:

ALTER TABLE employees
ADD COLUMN phone TEXT;

You can also use it to drop a column or add a constraint. One interview favourite: adding a NOT NULL column to a table that already has rows fails unless you give it a DEFAULT — the existing rows need a value.

58. DROP vs TRUNCATE — once more, precisely?

DROP TABLE employees deletes the table definition and all its data — gone, no rollback in most setups. TRUNCATE TABLE employees deletes all rows but keeps the table, and usually resets the auto-increment counter. TRUNCATE is faster because it does not log each row deletion, and it cannot take a WHERE. SQLite has no TRUNCATE; DELETE FROM employees is the SQLite equivalent. If an interviewer asks which is faster for emptying a table, the answer is TRUNCATE.

59. What is a transaction?

A group of statements that succeed or fail together — the database's "all or nothing" guarantee. Transfer 500 from one account to another and the two updates must either both happen or neither happen:

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;
COMMIT;

If anything fails in between, ROLLBACK undoes all of it. The four guarantees have the acronym ACID: Atomicity, Consistency, Isolation, Durability. Beginners are expected to know BEGIN / COMMIT / ROLLBACK; seniors are expected to explain isolation levels.

60. How do you speed up a slow query?

In this order: first, select only the columns you need — SELECT * fetches everything, including columns the query never uses. Second, add an index on the columns used in WHERE and JOIN:

CREATE INDEX idx_emp_dept ON employees(department_id);

Third, look at the execution plan — EXPLAIN QUERY PLAN in SQLite, EXPLAIN in MySQL and PostgreSQL — and check whether the database is scanning the whole table when it could use the index. An index is a trade-off: it makes reads faster and writes slower, and every index costs storage, so index the columns you actually filter and join on, not everything. Saying "add an index" without checking the plan is the beginner answer; checking the plan first is the interview answer.

20-question MCQ self-test

Answer before checking the key. Every question runs against the practice tables above — if you have them set up, run the query and check your answer against the real result.

1. Which keyword retrieves data from a table?

A. GET
B. SELECT
C. FETCH
D. SHOW

2. Which clause filters rows before grouping?

A. HAVING
B. WHERE
C. FILTER
D. GROUP BY

3. How many rows does SELECT COUNT(*) FROM employees return as its answer?

A. 10
B. 11
C. 1 row containing 11
D. 0

4. Which is the correct way to find employees with no salary recorded?

A. WHERE salary = NULL
B. WHERE salary IS NULL
C. WHERE salary = 0
D. WHERE salary IS 0

5. Which JOIN returns all rows from the left table, plus matches from the right?

A. INNER JOIN
B. RIGHT JOIN
C. LEFT JOIN
D. CROSS JOIN

6. How many rows does this return?

SELECT first_name FROM employees
WHERE salary > 70000 AND department_id = 2;

A. 2
B. 3
C. 4
D. 5

7. What is the first row of this result?

SELECT first_name, salary FROM employees
ORDER BY salary DESC LIMIT 3;

A. Alice, 75000
B. Carol, 82000
C. Emma, 90000
D. Grace, 71000

8. Which clause finds departments with more than two employees?

A. WHERE COUNT(*) > 2
B. HAVING COUNT(*) > 2
C. GROUP BY COUNT(*) > 2
D. FILTER COUNT(*) > 2

9. What does SELECT COUNT(DISTINCT department_id) FROM employees return?

A. 4
B. 5
C. 6
D. 11

10. What is the difference between DELETE and DROP?

A. They are the same
B. DELETE removes rows; DROP removes the whole table
C. DELETE removes the table; DROP removes rows
D. DELETE is faster than DROP

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

A. UNION is faster
B. UNION removes duplicates; UNION ALL keeps them
C. UNION ALL removes duplicates; UNION keeps them
D. They are identical

12. Which query correctly returns the second-highest salary?

A. SELECT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1
B. SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees)
C. SELECT MIN(salary) FROM employees
D. SELECT salary FROM employees ORDER BY salary ASC LIMIT 1

13. Which departments does this return?

SELECT department_id, COUNT(*)
FROM employees
GROUP BY department_id
HAVING COUNT(*) >= 3;

A. Department 2 only
B. Departments 1 and 2
C. Departments 1, 2 and 3
D. All departments

14. Which last names does WHERE last_name LIKE 'S%' match?

A. Names ending in S
B. Names starting with S
C. Names containing S anywhere
D. Names exactly equal to S

15. What does AVG(salary) do with NULL values?

A. Treats them as 0
B. Ignores them
C. Returns NULL for the whole average
D. Raises an error

16. Which of these is a DDL (Data Definition Language) statement?

A. SELECT
B. INSERT
C. CREATE TABLE
D. UPDATE

17. How many distinct countries are in the customers table?

A. 3
B. 4
C. 5
D. 6

18. Karen Young has no department. Which is true?

A. An INNER JOIN shows her with a NULL department
B. A LEFT JOIN shows her with a NULL department; an INNER JOIN leaves her out
C. Both JOINs leave her out
D. Both JOINs show her

19. Which pattern finds customers who never placed an order?

A. INNER JOIN orders ... WHERE o.order_id IS NULL
B. LEFT JOIN orders ... WHERE o.customer_id IS NULL
C. RIGHT JOIN orders ... WHERE o.customer_id IS NOT NULL
D. CROSS JOIN orders

20. How do you find duplicate emails in the employees table?

A. SELECT email FROM employees WHERE email = email
B. SELECT email, COUNT(*) FROM employees GROUP BY email HAVING COUNT(*) > 1
C. SELECT DISTINCT email FROM employees
D. SELECT email FROM employees ORDER BY email

Answers

  1. B — SELECT retrieves data.
  2. B — WHERE filters rows before grouping; HAVING filters groups after. (Q10)
  3. C — COUNT(*) returns one row containing the number 11. (Q21)
  4. B — IS NULL is the only correct test; = NULL is never true. (Q11)
  5. C — LEFT JOIN keeps all left-table rows. (Q25)
  6. B — Alice, Carol and Emma: 3 rows. (Q14)
  7. C — Emma Brown, 90,000, is the highest salary. (Q18)
  8. B — aggregates can only be filtered with HAVING. (Q10/Q34)
  9. B — 5: departments 1–5. DISTINCT counts NULL as one value but COUNT(DISTINCT ...) ignores NULL. (Q12/Q22)
  10. B — DELETE removes rows; DROP removes the whole table. (Q9)
  11. B — UNION de-duplicates; UNION ALL keeps everything. (Q47)
  12. B — the MAX ... WHERE salary < MAX version survives ties at the top; A returns the second row, not the second salary. (Q50)
  13. B — department 1 has 3 people, department 2 has 4. (Q34)
  14. B — 'S%' means "starts with S". (Q17)
  15. B — aggregate functions ignore NULL (except COUNT(*)). (Q21/Q35)
  16. C — CREATE TABLE defines structure; SELECT, INSERT and UPDATE work with data. (Q56)
  17. B — USA, UK, Germany, Pakistan: 4 distinct countries.
  18. B — the INNER JOIN drops her; the LEFT JOIN keeps her with NULL. (Q24/Q25)
  19. B — LEFT JOIN keeps every customer, and IS NULL on the order side marks the ones with no order. (Q25)
  20. B — group by the column and keep the groups with more than one row. (Our table has no duplicate emails, so this correctly returns no rows — the pattern is what matters.)

How did you do? 17–20: you are ready for the beginner SQL screen — practise the JOIN and window-function questions once more and move on to timed practice. 13–16: solid, but re-run the questions you missed against the practice tables; SQL sticks when you have seen the result. Below 13: work through Sections A–D again with the tables open, running each query yourself before reading the answer.

A woman typing code on a laptop in a modern indoor setting, for practising SQL interview questions border=

Photo by Christina Morillo on Pexels

What to practise next

Sixty questions is a start, not a finish. The highest-value practice from here is timed: give yourself 10 minutes, pick five questions from Sections C and D, and write the queries from memory against the practice tables. Then change the data — add an employee, cancel an order — and check your queries still return the right answers. Interviewers can tell the difference between someone who has read SQL and someone who has run it.

From here, the natural next step is our data analyst roadmap: SQL is step two of four (Excel → SQL → Power BI → Python), and the roadmap tells you what to build with it. For the spreadsheet half of the job, our Google Sheets formulas cheat sheet covers the 25 formulas you will actually use, and our statistics notes for TLT, ECT, PST and JEST exams cover the averages, percentages and probability that sit behind every aggregate function in this bank.

Post a Comment

Previous Post Next Post