Skip to lesson

SQL and Database Design Questions

Almost every Java backend round starts with an SQL screen: you get a small table, write one query, then explain a concept such as indexes or ACID. The interviewer checks that you ask about ties and NULLs and can say the answer in one clear sentence.

Joins: INNER and LEFT

INNER JOIN returns only the rows that match in both tables. LEFT JOIN returns every row of the left table and fills the right side with NULL where nothing matches. RIGHT JOIN is the mirror image.

Always say which table you keep. The example uses a few departments and employees: Imran has no department, and Legal has no staff.

Example 1 · INNER JOIN vs LEFT JOIN

Runs in: MySQL 8 or later (any SQL client)

SQL
CREATE TABLE departments (dept_id INT PRIMARY KEY, name VARCHAR(30));CREATE TABLE employees (emp_id INT PRIMARY KEY, name VARCHAR(30), dept_id INT, salary INT);INSERT INTO departments VALUES (1, 'IT'), (2, 'HR'), (3, 'Sales'), (4, 'Legal');INSERT INTO employees VALUES  (101, 'Asha', 1, 72000), (102, 'Ravi', 1, 85000), (103, 'Meena', 2, 48000),  (104, 'Kabir', 3, 39000), (105, 'Divya', 1, 85000), (106, 'Imran', NULL, 30000);
-- INNER JOIN: only rows that match on both sidesSELECT e.name, d.name AS deptFROM employees eJOIN departments d ON d.dept_id = e.dept_idORDER BY e.emp_id;
-- LEFT JOIN: every department, even with no employeesSELECT d.name AS dept, COUNT(e.emp_id) AS staffFROM departments dLEFT JOIN employees e ON e.dept_id = d.dept_idGROUP BY d.dept_id, d.nameORDER BY d.dept_id;
Output
+-------+-------+
| name  | dept  |
+-------+-------+
| Asha  | IT    |
| Ravi  | IT    |
| Meena | HR    |
| Kabir | Sales |
| Divya | IT    |
+-------+-------+
+-------+-------+
| dept  | staff |
+-------+-------+
| IT    |     3 |
| HR    |     1 |
| Sales |     1 |
| Legal |     0 |
+-------+-------+

What this code does

  • The INNER JOIN drops Imran (no department) and Legal (no employees). The LEFT JOIN from departments keeps every department, and COUNT(e.emp_id) gives 0 for Legal because it counts only non-NULL ids.
  • Each example creates its own small tables, so you can paste it into an empty MySQL database and get exactly this result.

A self join joins a table to itself, such as employee to manager. A CROSS JOIN pairs every row with every row, so forgetting a join condition creates one by accident. MySQL has no FULL OUTER JOIN: use LEFT JOIN ... UNION ... RIGHT JOIN. UNION removes duplicates; UNION ALL keeps them and is faster.

Revise: Inner join (opens in a new tab), Left and right join (opens in a new tab), Self join (opens in a new tab).

Predict the output

How many rows?

Work out the row count before you pick.

Round 1 of 3

IT has Asha and Ravi, HR has Meena, Legal has nobody; Imran has no department. How many rows come back?

-- departments: IT, HR, Legal employees: Asha (IT), Ravi (IT), Meena (HR), Imran (no dept)
SELECT e.name, d.name
FROM employees e
JOIN departments d ON d.dept_id = e.dept_id;

WHERE, GROUP BY, HAVING and clause order

WHERE filters single rows before grouping and cannot use aggregates. HAVING filters whole groups after GROUP BY, so it can use aggregates such as COUNT(*) and SUM().

One query can filter twice: WHERE removes rows first, then GROUP BY makes groups, then HAVING removes groups. Watch both filters in this example.

15 orders enter. WHERE status <> CANCELLED keeps 13 rows. GROUP BY customer_id makes 8 groups. HAVING COUNT(*) >= 2 keeps 3 groups. WHERE judges single rows, HAVING judges the finished groups.

Example 2 · WHERE filters rows, HAVING filters groups

Runs in: MySQL 8 or later (any SQL client)

SQL
CREATE TABLE employees (emp_id INT PRIMARY KEY, name VARCHAR(30), dept VARCHAR(10), salary INT);INSERT INTO employees VALUES  (101, 'Asha', 'IT', 72000), (102, 'Ravi', 'IT', 85000), (103, 'Meena', 'HR', 48000),  (104, 'Kabir', 'Sales', 39000), (105, 'Divya', 'IT', 85000), (107, 'Neha', 'HR', 52000);
-- WHERE filters rows before grouping; HAVING filters groups afterSELECT dept, COUNT(*) AS staff, AVG(salary) AS avg_salaryFROM employeesWHERE salary > 40000GROUP BY deptHAVING COUNT(*) >= 2ORDER BY dept;
Output
+------+-------+------------+
| dept | staff | avg_salary |
+------+-------+------------+
| HR   |     2 | 50000.0000 |
| IT   |     3 | 80666.6667 |
+------+-------+------------+

What this code does

  • WHERE salary > 40000 first removes Kabir. GROUP BY dept then makes one row per department, and HAVING COUNT(*) >= 2 removes Sales, which has no rows left.
  • AVG returns a decimal in MySQL, which is why the averages show four decimal places.

COUNT(*) counts rows; COUNT(col) skips NULLs. Every selected column must be grouped or aggregated. That is also why an alias made in SELECT works in ORDER BY but not in WHERE.

Revise: WHERE vs HAVING (opens in a new tab), Order of execution (opens in a new tab).

Order of execution

Order the database runs a query

Put the clauses in the order MySQL runs them.

Classic queries: second highest, Nth highest, duplicates

DENSE_RANK, RANK and ROW_NUMBER are window functions that number rows without collapsing them. For a tie at the top, ROW_NUMBER gives 1, 2, 3; RANK gives 1, 1, 3; DENSE_RANK gives 1, 1, 2.

The interviewer shows a small table and asks for the second highest salary. Two people share the top salary here, so the answer must not be the top salary again.

Example 3 · Second highest salary, three ways, and highest per department

Runs in: MySQL 8 or later (any SQL client)

SQL
CREATE TABLE employees (emp_id INT PRIMARY KEY, name VARCHAR(30), dept VARCHAR(10), salary INT);INSERT INTO employees VALUES  (101, 'Asha', 'IT', 72000), (102, 'Ravi', 'IT', 85000), (103, 'Meena', 'HR', 48000),  (104, 'Kabir', 'Sales', 39000), (105, 'Divya', 'IT', 85000), (107, 'Neha', 'HR', 52000);
-- 1. Subquery: the highest salary below the maximumSELECT MAX(salary) AS second_highestFROM employeesWHERE salary < (SELECT MAX(salary) FROM employees);
-- 2. DISTINCT + LIMIT/OFFSET: Nth highest is OFFSET N-1SELECT DISTINCT salary AS second_highestFROM employeesORDER BY salary DESCLIMIT 1 OFFSET 1;
-- 3. Window function: highest paid in each department, ties includedSELECT dept, name, salaryFROM (SELECT dept, name, salary,             DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk      FROM employees) rankedWHERE rnk = 1ORDER BY dept, name;
Output
+----------------+
| second_highest |
+----------------+
|          72000 |
+----------------+
+----------------+
| second_highest |
+----------------+
|          72000 |
+----------------+
+-------+-------+--------+
| dept  | name  | salary |
+-------+-------+--------+
| HR    | Neha  |  52000 |
| IT    | Divya |  85000 |
| IT    | Ravi  |  85000 |
| Sales | Kabir |  39000 |
+-------+-------+--------+

What this code does

  • Ravi and Divya share the top salary 85000. Both the subquery and DISTINCT ... LIMIT 1 OFFSET 1 correctly give 72000; without DISTINCT, the OFFSET query would return 85000 again.
  • DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) ranks within each department, so rnk = 1 returns the top earner per department, including both IT ties.

Say why DISTINCT matters: without it, LIMIT 1 OFFSET 1 returns the top salary a second time. The Nth highest is OFFSET N-1. PARTITION BY dept restarts the numbering per department, and duplicates are found with GROUP BY col HAVING COUNT(*) > 1.

Revise: Ranking window functions (opens in a new tab), Classic SQL interview questions (opens in a new tab).

Find the bug

Spot the wrong clause

One line of each query is wrong. Click it.

Show every e-mail that is registered more than once.

Round 1 of 3

Normalisation, primary and foreign keys

1NF means every column holds one atomic value. 2NF means every non-key column depends on the whole key. 3NF means no non-key column depends on another non-key column. Together they store each fact once.

A foreign key stops a row from pointing at a parent that does not exist. The example shows one accepted insert and one rejected insert.

Example 4 · Primary and foreign keys protecting the data

Runs in: MySQL 8 or later (any SQL client)

SQL
CREATE TABLE departments (  dept_id INT PRIMARY KEY,  name    VARCHAR(30) NOT NULL UNIQUE);CREATE TABLE employees (  emp_id  INT PRIMARY KEY,  name    VARCHAR(30) NOT NULL,  dept_id INT,  FOREIGN KEY (dept_id) REFERENCES departments (dept_id));INSERT INTO departments VALUES (1, 'IT');INSERT INTO employees VALUES (101, 'Asha', 1);SELECT e.name, d.name AS dept FROM employees e JOIN departments d ON d.dept_id = e.dept_id;INSERT INTO employees VALUES (102, 'Ravi', 99);
Output
+------+------+
| name | dept |
+------+------+
| Asha | IT   |
+------+------+

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`practice`.`employees`, CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`dept_id`) REFERENCES `departments` (`dept_id`))

What this code does

  • The foreign key on employees.dept_id accepts Asha (department 1 exists) and rejects Ravi with error 1452, because department 99 does not exist: referential integrity.
  • PRIMARY KEY makes emp_id unique and not null; UNIQUE on departments.name stops two departments with the same name.

A primary key is unique, not null, one per table. A foreign key references a key in another table and enforces referential integrity. A composite key has several columns; a unique key allows one row per value but, in MySQL, many NULLs. One-minute answer: "Normalise to 3NF to remove redundancy; denormalise on purpose for read-heavy reports when joins become the bottleneck."

Revise: Second and third normal form (opens in a new tab), Foreign keys (opens in a new tab).

Indexes and the leftmost-prefix rule

An index is a separate sorted structure (a B+ tree in InnoDB) that lets the database find rows without scanning the whole table. It speeds up WHERE, JOIN and ORDER BY but costs disk space and slows INSERT, UPDATE and DELETE.

Interviewers ask what an index speeds up, what it costs, and why a query sometimes ignores it. A composite index on (city, name) is the usual example.

The primary key is the clustered index in InnoDB; the others are secondary. A composite index (city, name) helps a search on city or on city plus name, not on name alone. Check what a query uses with EXPLAIN.

Revise: Cost of indexes (opens in a new tab), When an index is not used (opens in a new tab).

Predict the output

Will MySQL use the index?

The table has the index idx_city_name on (city, name).

Round 1 of 3

Can MySQL seek in the index for this query?

CREATE INDEX idx_city_name ON customers (city, name);
SELECT * FROM customers WHERE name = 'Asha';

ACID and isolation levels

ACID is the four guarantees of a database transaction: Atomicity (all or nothing), Consistency (constraints hold), Isolation (concurrent work does not interfere) and Durability (committed data survives a crash).

The classic ACID answer is a bank transfer. The example shows ROLLBACK undoing both updates and COMMIT keeping both.

Example 5 · Atomicity: ROLLBACK undoes both updates, COMMIT keeps both

Runs in: MySQL 8 or later (any SQL client)

SQL
CREATE TABLE wallets (owner VARCHAR(20) PRIMARY KEY, balance INT NOT NULL);INSERT INTO wallets VALUES ('asha', 1000), ('ravi', 500);
START TRANSACTION;UPDATE wallets SET balance = balance - 300 WHERE owner = 'asha';UPDATE wallets SET balance = balance + 300 WHERE owner = 'ravi';ROLLBACK;                       -- something failed: undo both updatesSELECT * FROM wallets ORDER BY owner;
START TRANSACTION;UPDATE wallets SET balance = balance - 300 WHERE owner = 'asha';UPDATE wallets SET balance = balance + 300 WHERE owner = 'ravi';COMMIT;                         -- both updates become permanent togetherSELECT * FROM wallets ORDER BY owner;
Output
+-------+---------+
| owner | balance |
+-------+---------+
| asha  |    1000 |
| ravi  |     500 |
+-------+---------+
+-------+---------+
| owner | balance |
+-------+---------+
| asha  |     700 |
| ravi  |     800 |
+-------+---------+

What this code does

  • The first transfer is rolled back, so both balances are unchanged, as if neither update happened. The second commits, and both changes become permanent together.
  • This is the A in ACID. In JDBC the same thing is setAutoCommit(false), commit() and rollback(); in Spring it is @Transactional.

READ UNCOMMITTED allows a dirty read (uncommitted data). READ COMMITTED stops that but allows a non-repeatable read (a row changes between two reads). REPEATABLE READ, the InnoDB default, keeps re-reads stable and mostly prevents phantom rows. SERIALIZABLE is safest and slowest.

Revise: ACID and a bank transfer (opens in a new tab), Isolation levels (opens in a new tab).

DELETE vs TRUNCATE vs DROP

DELETE removes chosen rows and can be rolled back. TRUNCATE empties the whole table fast and resets AUTO_INCREMENT. DROP removes the table itself, with its structure, data and indexes.

Three statements remove data in three different ways. Watch the ids and the last error in this example.

Example 6 · DELETE vs TRUNCATE vs DROP

Runs in: MySQL 8 or later (any SQL client)

SQL
CREATE TABLE logins (id INT AUTO_INCREMENT PRIMARY KEY, user VARCHAR(20));INSERT INTO logins (user) VALUES ('asha'), ('ravi'), ('meena');
DELETE FROM logins WHERE user = 'ravi';        -- removes chosen rowsINSERT INTO logins (user) VALUES ('kabir');    -- AUTO_INCREMENT continuesSELECT * FROM logins ORDER BY id;
TRUNCATE TABLE logins;                          -- removes all rows, resets AUTO_INCREMENTINSERT INTO logins (user) VALUES ('divya');SELECT * FROM logins;
DROP TABLE logins;                              -- removes the table itselfSELECT * FROM logins;
Output
+----+-------+
| id | user  |
+----+-------+
|  1 | asha  |
|  3 | meena |
|  4 | kabir |
+----+-------+
+----+-------+
| id | user  |
+----+-------+
|  1 | divya |
+----+-------+

ERROR 1146 (42S02): Table 'practice.logins' doesn't exist

What this code does

  • After DELETE, the next id is 4: the AUTO_INCREMENT counter continues. After TRUNCATE, the table is empty and numbering restarts at 1.
  • After DROP TABLE, the table no longer exists, so the final SELECT fails with error 1146.

DELETE is DML: it takes a WHERE, fires triggers and keeps the AUTO_INCREMENT counter. TRUNCATE is DDL: no WHERE, and in MySQL it commits at once, so it cannot be rolled back; it also fails on a table that a foreign key references.

Revise: DELETE and TRUNCATE (opens in a new tab).

Next step

Check your understanding

12 quick questions