← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 1 of 26

Want the full pack? Interview packs · Mock interview · Mentora

Page 1 of 26

Questions 1–20 of 501 · 0 of 20 on this page marked learned

1.sql-0001Mediummid

In what order does a database logically process the clauses of a SELECT statement, and why does that order matter?

A SELECT is written as SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, but it is logically evaluated as FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. This order explains why WHERE cannot filter on an aggregate and why standard SQL does not let WHERE use a column alias.

Full answer

The order you type the clauses is not the order the database reasons about them. The logical order is:

  1. FROM (and JOIN): build the set of input rows.
  2. WHERE: keep only rows that pass the condition.
  3. GROUP BY: collapse the remaining rows into groups.
  4. HAVING: keep only groups that pass the condition.
  5. SELECT: compute the output columns and their aliases.
  6. ORDER BY: sort the output.
  7. LIMIT / OFFSET: cut the sorted output.

"Logical" matters here. The optimizer may physically do things in a different order, for example by using an index to read rows already sorted. It must still return the same answer as if it had followed the steps above.

Three everyday results fall out of this order. WHERE runs before grouping, so WHERE COUNT(*) > 1 is meaningless and you need HAVING. ORDER BY runs after SELECT, so it can sort by an alias. And in standard SQL, WHERE runs before SELECT, so an alias defined in SELECT does not exist yet when WHERE is checked.

PostgreSQL follows the standard and rejects an alias in WHERE:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, salary * 12 AS yearly
FROM employees
WHERE yearly > 1000000;
-- error on purpose
text
Error: column "yearly" does not exist

SQLite is more relaxed and resolves the alias anyway:

sql
SELECT name, salary * 12 AS yearly
FROM employees
WHERE yearly > 1000000
ORDER BY name;
nameyearly
Asha1440000
Mei1140000
Ravi1140000

ORDER BY can use the alias on both engines, because sorting happens after SELECT:

sql
SELECT name, salary * 12 AS yearly
FROM employees
WHERE salary IS NOT NULL
ORDER BY yearly DESC
LIMIT 3;
nameyearly
Asha1440000
Ravi1140000
Mei1140000

For portable code, repeat the expression in WHERE or wrap the query in a subquery or CTE and filter outside.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, salary * 12 AS yearly
FROM employees
WHERE yearly > 1000000
ORDER BY name;

SELECT name, salary * 12 AS yearly
FROM employees
WHERE salary IS NOT NULL
ORDER BY yearly DESC
LIMIT 3;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT
  • WHERE filters rows before grouping; HAVING filters groups after it
  • ORDER BY can use SELECT aliases because it runs after SELECT
  • The physical plan may differ, but the result must match the logical order

Common mistakes

  • Writing an aggregate such as COUNT(*) inside WHERE
  • Assuming an alias that works in SQLite's WHERE will also work in PostgreSQL or SQL Server

Follow-ups

  • Where do window functions fit in this order?
  • Why can HAVING sometimes use a SELECT alias in some engines but not others?

Tips

  • Say the logical order out loud, then give one bug it explains, such as the alias-in-WHERE error
  • Mention that the optimizer may reorder work physically without changing the result
2.sql-0002Easyfresher

Why do most teams avoid SELECT * in application code, and when is it acceptable?

SELECT * returns every column, which ties the application to the current table layout and can move far more data than the screen needs. Listing columns keeps queries stable when columns are added, lets covering indexes help, and makes the intent clear. SELECT * is fine for quick exploration and inside EXISTS.

Full answer

SELECT * means "every column, in table order". That sounds harmless, but it causes three kinds of trouble in real code.

First, the result shape depends on the table. If someone adds a 2 MB profile_photo column to employees, every SELECT * now drags that blob across the network, even for a page that shows only names. If code reads columns by position, adding or reordering a column can silently shift values into the wrong variables.

Second, it blocks some index tricks. When a query asks only for columns that live inside an index, the database can answer from the index alone (a covering index) and never touch the table. SELECT * almost always forces a trip to the table.

Third, it hides intent. A reviewer reading SELECT name, salary knows exactly what the code needs.

Compare the two forms on a small table:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT * FROM departments ORDER BY id;
idname
1Engineering
2Sales
3Support
4Legal
sql
SELECT name FROM departments ORDER BY name;
name
Engineering
Legal
Sales
Support

There are fair uses. In an ad-hoc session you often want to see everything. Inside EXISTS (SELECT * ...) the column list is ignored, because EXISTS only checks whether a row exists, so SELECT * and SELECT 1 behave the same there. Views defined with SELECT * are a trap in some engines, because the column list is fixed when the view is created.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT * FROM departments ORDER BY id;

SELECT name FROM departments ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SELECT * couples code to the table layout
  • It can transfer large columns nobody uses
  • Naming columns allows covering-index reads
  • Inside EXISTS the select list is irrelevant, so * is harmless there

Common mistakes

  • Reading result columns by position after a SELECT *
  • Assuming SELECT * inside EXISTS is slower than SELECT 1

Follow-ups

  • What is a covering index?
  • What happens to a view built with SELECT * when a column is added to the base table?

Tips

  • Give a concrete failure, such as a new large column slowing every page
  • Mention EXISTS as the one place where the select list does not matter
3.sql-0003Easyfresher

How do column aliases work in SQL, and how do you write an alias that contains a space?

An alias renames an output column or a table for the rest of the query, written with AS or simply after the expression. An alias with spaces or a reserved word must be quoted as an identifier, with double quotes in standard SQL. Single quotes make a string literal, not a name.

Full answer

An alias gives a name to an expression in the select list, or a short name to a table in FROM. AS is optional for both, but writing it for column aliases makes the code easier to read.

Here the computed column gets a readable heading, and the table gets the short alias e:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT e.name AS "Employee name", e.salary / 12 AS "Monthly pay"
FROM employees AS e
WHERE e.dept_id = 1
ORDER BY "Employee name";
Employee nameMonthly pay
Asha10000
Mei7916
Ravi7916

If the alias has a space, quote it with double quotes, which is the standard way to quote identifiers. MySQL also accepts backticks, and SQL Server accepts square brackets, but double quotes work on PostgreSQL, SQLite and (with ANSI settings) the others.

A table alias also matters for correctness, not only for typing less. When the same table appears twice, as in a self join, the aliases are the only way to say which copy a column comes from:

sql
SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.dept_id = 1
ORDER BY e.name;
employeemanager
MeiAsha
RaviAsha

Two scoping rules are worth knowing. A column alias is visible in ORDER BY, but in standard SQL it is not visible in WHERE or GROUP BY of the same query. A table alias, once given, replaces the table name: after FROM employees e, PostgreSQL rejects employees.name in that query.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT e.name AS "Employee name", e.salary / 12 AS "Monthly pay"
FROM employees AS e
WHERE e.dept_id = 1
ORDER BY "Employee name";

SELECT e.name AS employee, m.name AS manager
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.dept_id = 1
ORDER BY e.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • AS is optional, but clearer for column aliases
  • Quote aliases with spaces using double quotes
  • Table aliases are required to tell apart two copies of the same table
  • Column aliases are visible in ORDER BY, not in standard WHERE

Common mistakes

  • Using single quotes for an alias, which some engines accept but others treat as a string
  • Referring to the original table name after giving it an alias

Follow-ups

  • How would you sort by an alias that has a space in it?
  • Why does a self join need table aliases?

Tips

  • Use short, meaningful table aliases (e for employees, d for departments), not a, b, c
  • Mention the scoping rule for WHERE versus ORDER BY
4.sql-0004Easyfresher

What does SELECT DISTINCT do when it is applied to more than one column?

DISTINCT removes duplicate rows from the output, comparing all selected columns together. With two columns, a row is a duplicate only if both values match another row. DISTINCT treats NULLs as equal to each other for this purpose, so several NULLs collapse into one.

Full answer

DISTINCT is not a function applied to the first column. It applies to the whole output row. With SELECT DISTINCT city, year, two rows are duplicates only when the city and the year are both the same.

Using the students table:

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

One column first. Pune and Leeds appear twice each, and Dara has no city:

sql
SELECT DISTINCT city FROM students ORDER BY city;
city
NULL
Leeds
Pune

Now two columns. Asha and Chen are both from Pune in year 1, so they collapse into one row. Ben and Eli (Leeds, year 2) collapse too:

sql
SELECT DISTINCT city, year FROM students ORDER BY city, year;
cityyear
NULL3
Leeds2
Pune1

Notice the NULL row in both results. When DISTINCT compares rows, two NULLs count as "not distinct", so all missing cities fold into a single row. That is different from =, where NULL = NULL is not true. The standard calls this "IS NOT DISTINCT FROM" behaviour, and GROUP BY uses the same rule.

Writing SELECT DISTINCT(city), year does not change anything. The parentheses only wrap the expression city; DISTINCT still applies to the full row.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT DISTINCT city FROM students ORDER BY city;

SELECT DISTINCT city, year FROM students ORDER BY city, year;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • DISTINCT compares the whole selected row, not one column
  • NULLs are treated as equal for DISTINCT, so they collapse into one row
  • Parentheses after DISTINCT do not limit it to one column

Common mistakes

  • Writing DISTINCT(col1), col2 and expecting uniqueness on col1 only
  • Using DISTINCT to hide duplicate rows caused by a wrong join

Follow-ups

  • How is DISTINCT different from GROUP BY with no aggregates?
  • How do you keep one full row per city, not just the distinct city names?

Tips

  • If DISTINCT fixes a duplicate problem, ask whether a join is producing extra rows
  • Mention the NULL rule; interviewers often check it
5.sql-0005Easyfresher

Write a query that lists employees by department, with the highest salary first inside each department.

Use ORDER BY with two keys: the department first, then salary with DESC. Each key has its own direction, so dept_id ascending and salary descending can be mixed. Add a final tie-breaker such as name so rows with equal salaries come out in a predictable order.

Full answer

ORDER BY accepts a list. The database sorts by the first key, and only uses the second key to break ties within equal values of the first, and so on.

Each key gets its own direction. ORDER BY dept_id, salary DESC means "department ascending, then salary descending". A common slip is to think DESC applies to every column before it. It does not; it applies only to the key it follows.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT dept_id, name, salary
FROM employees
ORDER BY dept_id, salary DESC, name;
dept_idnamesalary
NULLLenaNULL
1Asha120000
1Mei95000
1Ravi95000
2Tom70000
2Sara62000
3Diego55000
3Omar48000

Ravi and Mei both earn 95000 in Engineering. Without the last key, name, the database may return them in either order, and that order can change between runs or after an index is added. A unique final key makes the output fully determined, which matters for pagination and for tests that compare output.

Lena has no department. On SQLite, NULL sorts before every other value in ascending order, so her row appears first. PostgreSQL does the opposite and puts NULLs last in ascending order. If the position of missing values matters, say so explicitly with NULLS FIRST or NULLS LAST, which both engines accept.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT dept_id, name, salary
FROM employees
ORDER BY dept_id, salary DESC, name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Each ORDER BY key has its own ASC or DESC
  • Later keys only break ties in earlier keys
  • End with a unique key for a stable, repeatable order
  • NULL placement differs by engine; NULLS FIRST or LAST makes it explicit

Common mistakes

  • Thinking DESC applies to all listed columns
  • Relying on ties coming back in insert order

Follow-ups

  • How would you put employees with no department at the end on every engine?
  • Why does a stable order matter for OFFSET pagination?

Tips

  • Mention the tie-breaker without being asked; it shows you have debugged flaky tests
6.sql-0006Mediummid

Where do NULL values appear when you sort, and how do you control it?

Engines disagree. SQLite and MySQL treat NULL as smaller than any value, so NULLs come first in ascending order. PostgreSQL and Oracle treat NULL as larger, so NULLs come last in ascending order. Write NULLS FIRST or NULLS LAST to make the order explicit; SQLite has supported it since 3.30.

Full answer

A NULL has no value, so the standard leaves it to each engine to decide whether NULLs sort high or low. The difference shows up as soon as you move a query between databases.

Here is the same query on SQLite, sorting salaries ascending:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, salary FROM employees ORDER BY salary, name LIMIT 3;
namesalary
LenaNULL
Omar48000
Diego55000

And on PostgreSQL:

sql
SELECT name, salary FROM employees ORDER BY salary DESC, name LIMIT 3;
namesalary
LenaNULL
Asha120000
Mei95000

Lena's unknown salary is first on SQLite and last on PostgreSQL. In descending order each engine flips its choice.

The portable fix is to say what you want:

sql
SELECT name, salary FROM employees ORDER BY salary DESC NULLS LAST, name LIMIT 3;
namesalary
Asha120000
Mei95000
Ravi95000

If an engine lacks NULLS LAST (older MySQL versions, for example), the usual workaround is to sort on a flag first: ORDER BY salary IS NULL, salary. The expression salary IS NULL is 0 for known values and 1 for NULL, so NULLs go to the end.

This matters for top-N reports. ORDER BY salary DESC LIMIT 3 on PostgreSQL puts the NULL salary at the very top, which is rarely what a "highest paid" report wants.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, salary FROM employees ORDER BY salary, name LIMIT 3;

SELECT name, salary FROM employees ORDER BY salary DESC NULLS LAST, name LIMIT 3;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • NULL sort position is engine-specific
  • SQLite and MySQL: NULLs first ascending; PostgreSQL and Oracle: NULLs last ascending
  • NULLS FIRST and NULLS LAST make the intent explicit
  • ORDER BY col IS NULL, col is a portable fallback

Common mistakes

  • Writing a top-N query with DESC on PostgreSQL and getting NULL as the top value
  • Assuming tests on SQLite prove the order in production PostgreSQL

Follow-ups

  • How would you sort NULLs last on an engine without NULLS LAST?
  • Do indexes store NULLs, and does that affect sorted reads?

Tips

  • Name at least two engines and which way each sorts NULLs
  • Offer the explicit NULLS LAST version as the answer you would ship
7.sql-0007Easyfresher

What does SELECT 7 / 2 return, and how do you get 3.5 instead?

When both operands are integers, SQLite and PostgreSQL perform integer division and return 3, dropping the fraction. Make one side non-integer with 7 / 2.0, or cast with CAST(7 AS REAL) in SQLite or 7::numeric in PostgreSQL. MySQL is the odd one out and returns 3.5000 for 7 / 2.

Full answer

Integer division catches people in averages and percentage columns. In SQLite and PostgreSQL, an integer divided by an integer is an integer, and the fraction is thrown away (truncated toward zero).

SQLite:

sql
SELECT 7 / 2 AS a, -7 / 2 AS b, 7 % 2 AS remainder;
abremainder
3-31

PostgreSQL gives the same values:

sql
SELECT 7 / 2 AS a, -7 / 2 AS b, 7 % 2 AS remainder;
abremainder
3-31

Look at -7 / 2: the result is -3, not -4. The fraction is truncated toward zero, which is not the same as rounding down.

To keep the fraction, make at least one operand non-integer:

sql
SELECT 7 / 2.0 AS a, CAST(7 AS REAL) / 2 AS b, ROUND(100.0 * 2 / 3, 2) AS pct;
abpct
3.53.566.67

A real case: a pass percentage computed as passed * 100 / total with integers returns whole numbers only, and passed / total * 100 returns 0 for every class where not everyone passed, because passed / total is 0 before the multiplication. Multiply first, or write 100.0 * passed / total.

MySQL does not follow this rule. Its / always returns a decimal (7 / 2 is 3.5000) and it has a separate DIV operator for integer division. This was not run here; it comes from the MySQL documentation.

sql
SELECT 7 / 2 AS a, -7 / 2 AS b, 7 % 2 AS remainder;

SELECT 7 / 2.0 AS a, CAST(7 AS REAL) / 2 AS b, ROUND(100.0 * 2 / 3, 2) AS pct;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Integer / integer is integer division in SQLite and PostgreSQL
  • The fraction is truncated toward zero, so -7 / 2 is -3
  • Use 2.0, CAST, or 100.0 * x / y to keep decimals
  • MySQL's / returns a decimal; DIV is its integer division

Common mistakes

  • Computing passed / total * 100 and getting 0
  • Assuming the same expression behaves the same on MySQL and PostgreSQL

Follow-ups

  • How do you round the result to two decimal places?
  • What does the modulo operator return for negative numbers?

Tips

  • Show the passed / total * 100 bug; it is the version interviewers like
  • Mention truncation toward zero for negative numbers
8.sql-0008Mediummid

How do single quotes and double quotes differ in SQL, and what surprising thing does SQLite do with double quotes?

Single quotes mark a string value; double quotes mark an identifier such as a column or table name. SQLite, for backward compatibility, treats a double-quoted word as a string if no column of that name exists. That hides typos: a misspelled column becomes a constant string instead of an error, while PostgreSQL raises an error.

Full answer

In standard SQL the rule is simple:

  • 'Pune' with single quotes is a string value.
  • "city" with double quotes is an identifier, a name of a column, table or alias. Quoting lets an identifier contain spaces, keep its exact case, or use a reserved word.

The bug usually looks like a filter written with the wrong quotes:

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
SELECT name FROM students WHERE city = "Leeds" ORDER BY name;
name
Ben
Eli

SQLite returns Ben and Eli, so the query looks correct. It only works by accident. SQLite looked for a column named Leeds, found none, and quietly treated "Leeds" as the string 'Leeds'. PostgreSQL does not guess:

sql
SELECT name FROM students WHERE city = "Leeds";  -- error on purpose
text
Error: column "Leeds" does not exist

The accident breaks as soon as the quoted word happens to be a real column name. Here "city" refers to the column itself, so the condition compares each city with itself and is true for every row that has a city:

sql
SELECT name FROM students WHERE "city" = "city" ORDER BY name;
name
Asha
Ben
Chen
Eli

The typo case is worse. A misspelled column in double quotes becomes a constant string and the query runs:

sql
SELECT name, "citty" AS city FROM students ORDER BY name LIMIT 2;
namecity
Ashacitty
Bencitty

PostgreSQL rejects the same typo, which is what you want:

sql
SELECT name, "citty" AS city FROM students;  -- error on purpose
text
Error: column "citty" does not exist

Use single quotes for values, double quotes only for names, and turn off this compatibility behaviour where you can (SQLite builds can disable it with the SQLITE_DQS compile option).

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT name FROM students WHERE city = "Leeds" ORDER BY name;

SELECT name FROM students WHERE "city" = "city" ORDER BY name;

SELECT name, "citty" AS city FROM students ORDER BY name LIMIT 2;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Single quotes: string literals
  • Double quotes: identifiers (columns, tables, aliases)
  • SQLite falls back to treating an unknown double-quoted name as a string
  • That fallback turns typos into silent constant values

Common mistakes

  • Writing WHERE name = "Asha" and getting a match on SQLite that fails elsewhere
  • Trusting SQLite to report a misspelled double-quoted column

Follow-ups

  • How do you include a single quote inside a string literal?
  • Why might a team quote every identifier, and what does that do to case sensitivity in PostgreSQL?

Tips

  • State the standard rule first, then the SQLite exception
  • Mention that this is a reason to test queries on the production engine
9.sql-0009Easyfresher

Can you run a SELECT without a FROM clause? What is the DUAL table?

Yes in SQLite, PostgreSQL, MySQL and SQL Server: SELECT 1 + 1 returns one row with no table involved. Oracle, before version 23ai, required a FROM clause, so it provides a one-row table called DUAL for this purpose. The pattern is handy for testing expressions and functions.

Full answer

A SELECT without FROM evaluates its expressions once and returns a single row. It is the quickest way to test how a function or operator behaves before using it on a real table.

sql
SELECT 1 + 1 AS two, UPPER('pune') AS city, LENGTH('canteen') AS letters;
twocityletters
2PUNE7

This is useful in interviews too. If you are unsure whether LENGTH counts bytes or characters, or what ROUND(2.5) returns, a one-line SELECT answers it.

Oracle historically required every SELECT to have a FROM clause. To make the expression form possible, it ships a table named DUAL with exactly one row and one column, so people write SELECT SYSDATE FROM dual. MySQL accepts FROM DUAL for compatibility, and recent Oracle releases also allow omitting FROM. Those Oracle and MySQL details were not run here.

Since there is no table, there are no rows to filter. A WHERE clause on a FROM-less SELECT still works in PostgreSQL and SQLite: if the condition is false you get zero rows.

sql
SELECT 'shown' AS label WHERE 1 = 0;
label

(0 rows)

sql
SELECT 1 + 1 AS two, UPPER('pune') AS city, LENGTH('canteen') AS letters;

SELECT 'shown' AS label WHERE 1 = 0;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • SELECT without FROM returns one row of computed values
  • It is a fast way to test functions and operators
  • Oracle used the one-row DUAL table because it required FROM

Common mistakes

  • Writing FROM dual on PostgreSQL, where no such table exists

Follow-ups

  • What does ROUND(2.5) return on SQLite and on PostgreSQL?
  • How would you generate several rows without a table?

Tips

  • Use this trick live in a coding round to check a function before relying on it
10.sql-0010Easyfresher

What are DDL, DML, DQL, DCL and TCL in SQL? Give an example statement for each.

They are groups of SQL statements by purpose. DDL defines structure (CREATE, ALTER, DROP), DML changes data (INSERT, UPDATE, DELETE), DQL reads data (SELECT), DCL controls access (GRANT, REVOKE) and TCL manages transactions (BEGIN, COMMIT, ROLLBACK, SAVEPOINT).

Full answer

The labels are a way to talk about what a statement does.

  • DDL, data definition language, changes the shape of the database: CREATE TABLE, ALTER TABLE, DROP INDEX, TRUNCATE in many engines.
  • DML, data manipulation language, changes rows: INSERT, UPDATE, DELETE, MERGE.
  • DQL, data query language, reads rows: SELECT. Some books fold SELECT into DML.
  • DCL, data control language, manages permissions: GRANT SELECT ON orders TO analyst, REVOKE.
  • TCL, transaction control language, groups work into transactions: BEGIN, COMMIT, ROLLBACK, SAVEPOINT.

A short script that touches four of the five groups:

sql
CREATE TABLE canteen_bill (id INTEGER PRIMARY KEY, item TEXT, price INTEGER);
BEGIN;
INSERT INTO canteen_bill (item, price) VALUES ('Tea', 15), ('Samosa', 20);
COMMIT;
SELECT item, price FROM canteen_bill ORDER BY id;
itemprice
Tea15
Samosa20

The grouping has practical meaning. DDL often takes stronger locks than DML because it changes the structure every query depends on. Whether DDL can be rolled back depends on the engine. PostgreSQL and SQLite run DDL inside transactions, so a CREATE TABLE inside a rolled-back transaction disappears:

sql
BEGIN;
CREATE TABLE scratch (x INTEGER);
ROLLBACK;
SELECT COUNT(*) AS tables_named_scratch FROM sqlite_master WHERE name = 'scratch';
tables_named_scratch
0

MySQL commits implicitly before most DDL statements, so the same script would leave the table in place there (from the MySQL documentation, not run here). SQLite has no users, so it has no GRANT or REVOKE.

sql
CREATE TABLE canteen_bill (id INTEGER PRIMARY KEY, item TEXT, price INTEGER);
BEGIN;
INSERT INTO canteen_bill (item, price) VALUES ('Tea', 15), ('Samosa', 20);
COMMIT;
SELECT item, price FROM canteen_bill ORDER BY id;

BEGIN;
CREATE TABLE scratch (x INTEGER);
ROLLBACK;
SELECT COUNT(*) AS tables_named_scratch FROM sqlite_master WHERE name = 'scratch';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • DDL: structure; DML: rows; DQL: reading; DCL: permissions; TCL: transactions
  • DDL usually takes heavier locks than DML
  • PostgreSQL and SQLite can roll back DDL; MySQL implicitly commits most DDL

Common mistakes

  • Assuming every engine can roll back a DROP TABLE inside a transaction
  • Listing the acronyms without saying why the distinction matters

Follow-ups

  • Is TRUNCATE DDL or DML, and why does it matter?
  • Why are schema migrations safer on an engine with transactional DDL?

Tips

  • Add one practical point, such as transactional DDL, after the definitions
11.sql-0011Mediummid

Is SQL case-sensitive? Consider keywords, identifiers and the data itself.

Keywords are never case-sensitive. Unquoted identifiers are case-insensitive in most engines, and PostgreSQL folds them to lower case. Data comparisons depend on the engine and collation: SQLite and PostgreSQL compare strings with = case-sensitively, SQLite's LIKE ignores ASCII case, PostgreSQL's LIKE does not, and MySQL's default collations ignore case.

Full answer

The question has three parts, and the answer differs for each.

Keywords such as select and SELECT mean the same thing everywhere.

Unquoted identifiers are case-insensitive. PostgreSQL does this by folding them to lower case, so Employees and employees are the same table. Quoting an identifier keeps its exact case: "Employees" in PostgreSQL is a different name from employees.

The data is where engines differ. On SQLite, = is case-sensitive but LIKE ignores case for ASCII letters:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT
  (SELECT COUNT(*) FROM employees WHERE name = 'asha')    AS eq_lower,
  (SELECT COUNT(*) FROM employees WHERE name LIKE 'asha')  AS like_lower;
eq_lowerlike_lower
01

PostgreSQL treats both as case-sensitive, and offers ILIKE for a case-insensitive match:

sql
SELECT
  (SELECT COUNT(*) FROM employees WHERE name = 'asha')     AS eq_lower,
  (SELECT COUNT(*) FROM employees WHERE name LIKE 'asha')  AS like_lower,
  (SELECT COUNT(*) FROM employees WHERE name ILIKE 'asha') AS ilike_lower;
eq_lowerlike_lowerilike_lower
001

For portable case-insensitive matching, compare lower-cased values: LOWER(name) = LOWER('asha'). Be aware this can stop a plain index on name from being used. PostgreSQL can index the expression LOWER(name), and SQLite can declare a column COLLATE NOCASE.

MySQL's default collations are case-insensitive, so 'asha' = 'Asha' is true there. That comes from the MySQL documentation and was not run here.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT
  (SELECT COUNT(*) FROM employees WHERE name = 'asha')    AS eq_lower,
  (SELECT COUNT(*) FROM employees WHERE name LIKE 'asha')  AS like_lower;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Keywords: never case-sensitive
  • Unquoted identifiers: case-insensitive; PostgreSQL folds them to lower case
  • Data: depends on engine and collation
  • SQLite LIKE ignores ASCII case; PostgreSQL LIKE does not; ILIKE does

Common mistakes

  • Creating a PostgreSQL table with a quoted mixed-case name and then querying it unquoted
  • Wrapping an indexed column in LOWER() and losing the index

Follow-ups

  • How would you make a case-insensitive unique constraint on email?
  • What is a collation?

Tips

  • Split the answer into keywords, identifiers and data; it shows structured thinking
12.sql-0012Easyfresher

A query without ORDER BY has always returned rows in insert order. Is it safe to rely on that?

No. A table is an unordered set, and without ORDER BY the database may return rows in any order. The order you see comes from how rows are stored and which plan is chosen, and it can change after an index is added, data is updated, the table is vacuumed or the engine is upgraded.

Full answer

Relational tables have no built-in row order. When you omit ORDER BY, you are telling the database "any order is fine", and it will return rows in whatever order is cheapest for the plan it picked.

That order often looks like insert order on a small, fresh table, because the engine is reading pages from start to end. Many things can change it:

  • An index is added, and the planner starts reading through the index instead.
  • Rows are updated or deleted, and new rows reuse freed space in the middle of the table.
  • PostgreSQL runs a parallel scan, and workers return rows as they finish.
  • A JOIN switches from a nested loop to a hash join.

A tiny demonstration. Three members are inserted in the order Zara, Amit, Maya, and a plain read returns them in that order:

sql
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
INSERT INTO members (name) VALUES ('Zara'), ('Amit'), ('Maya');
SELECT name FROM members;
name
Zara
Amit
Maya

Now add an index on name and ask for the same rows with a harmless filter. The planner answers from the index, so the rows come back in index order:

sql
CREATE INDEX idx_members_name ON members(name);
SELECT name FROM members WHERE name > '';
name
Amit
Maya
Zara
sql
EXPLAIN QUERY PLAN SELECT name FROM members WHERE name > '';
text
QUERY PLAN
SEARCH members USING COVERING INDEX idx_members_name (name>?)

Nothing about the data changed, but the "natural" order did. If the order matters to the user, to a test, or to pagination, write ORDER BY, and end it with a unique column so ties are resolved too.

sql
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
INSERT INTO members (name) VALUES ('Zara'), ('Amit'), ('Maya');
SELECT name FROM members;

CREATE INDEX idx_members_name ON members(name);
SELECT name FROM members WHERE name > '';

EXPLAIN QUERY PLAN SELECT name FROM members WHERE name > '';

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Tables are unordered sets
  • Without ORDER BY, the order depends on the plan
  • Adding an index can change the order you see
  • Always end ORDER BY with a unique key when order matters

Common mistakes

  • Writing tests that compare query output without ORDER BY
  • Paginating with LIMIT and OFFSET but no ORDER BY

Follow-ups

  • Why can LIMIT without ORDER BY return different rows on different runs?
  • What is a stable sort key?

Tips

  • Give one concrete cause of order changing, such as a new index
13.sql-0013Mediummid

How do you sort rows in a custom order, for example order status as pending, then shipped, then cancelled?

Sort by a CASE expression that maps each status to a number: ORDER BY CASE status WHEN 'pending' THEN 1 WHEN 'shipped' THEN 2 ELSE 3 END. Alphabetical order would give cancelled, pending, shipped, which is rarely the business order. For a list that changes, store the rank in a lookup table and join to it.

Full answer

Alphabetical sorting on a status column gives cancelled, pending, shipped. A support dashboard usually wants the open work first. ORDER BY accepts any expression, so map each status to a rank with CASE:

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT id, status, order_date
FROM orders
ORDER BY CASE status
           WHEN 'pending'   THEN 1
           WHEN 'shipped'   THEN 2
           WHEN 'cancelled' THEN 3
           ELSE 4
         END,
         order_date;
idstatusorder_date
105pending2026-03-09
101shipped2026-01-05
102shipped2026-02-11
104shipped2026-03-01
106shipped2026-03-12
103cancelled2026-02-14

The ELSE branch catches unexpected statuses, such as a new 'returned' value someone adds later, and pushes them to the end instead of making them disappear or jump to the top.

When the same order is used in many queries, a hard-coded CASE in each one becomes a maintenance problem. A small lookup table keeps the rank in one place and can carry labels for the UI too:

sql
CREATE TABLE status_rank (status TEXT PRIMARY KEY, rank INTEGER NOT NULL);
INSERT INTO status_rank VALUES ('pending',1),('shipped',2),('cancelled',3);
SELECT o.id, o.status
FROM orders o
LEFT JOIN status_rank s ON s.status = o.status
ORDER BY COALESCE(s.rank, 99), o.id;
idstatus
105pending
101shipped
102shipped
104shipped
106shipped
103cancelled

The LEFT JOIN keeps orders whose status is missing from the lookup table, and COALESCE(s.rank, 99) sends them last. With an inner join those orders would vanish from the report, which is a worse failure than appearing in the wrong place.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT id, status, order_date
FROM orders
ORDER BY CASE status
           WHEN 'pending'   THEN 1
           WHEN 'shipped'   THEN 2
           WHEN 'cancelled' THEN 3
           ELSE 4
         END,
         order_date;

CREATE TABLE status_rank (status TEXT PRIMARY KEY, rank INTEGER NOT NULL);
INSERT INTO status_rank VALUES ('pending',1),('shipped',2),('cancelled',3);
SELECT o.id, o.status
FROM orders o
LEFT JOIN status_rank s ON s.status = o.status
ORDER BY COALESCE(s.rank, 99), o.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ORDER BY accepts any expression, including CASE
  • Map each value to a rank; use ELSE for unknown values
  • For reusable orders, keep ranks in a lookup table
  • Use a LEFT JOIN so unknown statuses are not dropped

Common mistakes

  • Relying on alphabetical order for business states
  • Using an inner join to the lookup table and losing rows with new statuses

Follow-ups

  • How would you sort by priority and then by order date within each status?
  • Could an enum type in PostgreSQL solve this?

Tips

  • Mention the lookup-table version as the long-term design
14.sql-0014Easyfresher

A column stores roll numbers as text. Why does ORDER BY put '10' before '9', and how do you fix it?

Text sorts character by character, so '10' comes before '9' because '1' is smaller than '9'. Cast to a number in the ORDER BY, or better, store numbers in a numeric column. In SQLite, ORDER BY CAST(roll AS INTEGER) gives 1, 2, 9, 10.

Full answer

String comparison works like a dictionary. It compares the first character, and only looks at the next one when the first characters tie. '10' starts with '1', which is smaller than '9', so '10' sorts first no matter how long it is.

sql
CREATE TABLE roll_call (roll TEXT, name TEXT);
INSERT INTO roll_call VALUES ('9','Ira'),('10','Jon'),('2','Kim'),('1','Lia');
SELECT roll, name FROM roll_call ORDER BY roll;
rollname
1Lia
10Jon
2Kim
9Ira

The quick fix is to sort by the numeric value:

sql
SELECT roll, name FROM roll_call ORDER BY CAST(roll AS INTEGER);
rollname
1Lia
2Kim
9Ira
10Jon

The real fix is to store numbers as numbers. A text column accepts '9', ' 9' and 'nine', and all of them break numeric sorting or casting in different ways. If the value has letters, like 'CS-10', either split it into a prefix and a numeric part, or pad the number to a fixed width ('CS-009', 'CS-010') so text order and numeric order agree.

There is an SQLite detail here. SQLite uses type affinity, so if the column had been declared INTEGER, the text '10' would have been converted to the integer 10 on insert and sorted correctly. Declaring it TEXT keeps it as text.

sql
CREATE TABLE roll_call (roll TEXT, name TEXT);
INSERT INTO roll_call VALUES ('9','Ira'),('10','Jon'),('2','Kim'),('1','Lia');
SELECT roll, name FROM roll_call ORDER BY roll;

SELECT roll, name FROM roll_call ORDER BY CAST(roll AS INTEGER);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Text is compared character by character
  • CAST in ORDER BY gives numeric order
  • Store numeric values in numeric columns
  • Zero-padding makes text order match numeric order

Common mistakes

  • Fixing the sort with CAST while leaving bad data types in the schema
  • Casting values that contain letters, which gives 0 or an error depending on engine

Follow-ups

  • What does CAST('12abc' AS INTEGER) return in SQLite?
  • How does type affinity affect this in SQLite?

Tips

  • Explain the cause in one line before giving the fix
15.sql-0015Easyfresher

A table has a column named order. Why does CREATE TABLE fail, and how do you fix it?

ORDER is a reserved word, so the parser reads it as the start of an ORDER BY clause and raises a syntax error. Quote it as an identifier with double quotes, or better, rename it to something like sort_order or position so nobody has to quote it again.

Full answer

SQL reserves certain words for its own grammar: SELECT, FROM, ORDER, GROUP, USER, TABLE and many more. When one appears where a name is expected, the parser gets confused:

sql
CREATE TABLE playlist (id INTEGER, order INTEGER);  -- error on purpose
text
Error: near "order": syntax error

Double quotes turn the word into an identifier and the statement works:

sql
CREATE TABLE playlist (id INTEGER, "order" INTEGER);
INSERT INTO playlist VALUES (1, 2), (2, 1);
SELECT id, "order" FROM playlist ORDER BY "order";
idorder
21
12

The catch is that every future query must quote it too, and forgetting the quotes in one place produces a confusing syntax error far from the table definition. Renaming the column is the better fix:

sql
CREATE TABLE playlist2 (id INTEGER, sort_order INTEGER);
INSERT INTO playlist2 VALUES (1, 2), (2, 1);
SELECT id, sort_order FROM playlist2 ORDER BY sort_order;
idsort_order
21
12

Reserved word lists differ between engines. user is reserved in PostgreSQL but usable as a plain column name in SQLite, so a schema that works in local SQLite tests can fail on PostgreSQL. Names like user, order, group, desc and date are common candidates for trouble.

sql
-- error on purpose
CREATE TABLE playlist (id INTEGER, order INTEGER);

CREATE TABLE playlist (id INTEGER, "order" INTEGER);
INSERT INTO playlist VALUES (1, 2), (2, 1);
SELECT id, "order" FROM playlist ORDER BY "order";

CREATE TABLE playlist2 (id INTEGER, sort_order INTEGER);
INSERT INTO playlist2 VALUES (1, 2), (2, 1);
SELECT id, sort_order FROM playlist2 ORDER BY sort_order;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Reserved words cannot be used as bare identifiers
  • Double quotes allow it, but every query then needs the quotes
  • Renaming to a descriptive non-reserved word is the lasting fix
  • Reserved word lists differ by engine

Common mistakes

  • Quoting the name in CREATE TABLE and forgetting the quotes in later queries
  • Testing only on SQLite and missing a word that PostgreSQL reserves

Follow-ups

  • Why is a table called user a problem in PostgreSQL?
  • What naming conventions help avoid reserved words?

Tips

  • Recommend the rename, not just the quoting
16.sql-0016Mediummid

LIMIT, FETCH FIRST and TOP all restrict how many rows come back. Which engines support which, and what is the standard form?

The SQL standard form is OFFSET n ROWS FETCH FIRST m ROWS ONLY, supported by PostgreSQL, Oracle and SQL Server, while PostgreSQL, MySQL and SQLite use LIMIT m OFFSET n. SQL Server also has SELECT TOP m, and SQLite does not accept FETCH FIRST. In every form, ORDER BY is what makes the chosen rows meaningful.

Full answer

Every engine can return "the first few rows", but the spelling differs.

  • LIMIT 3 OFFSET 2: PostgreSQL, MySQL, SQLite.
  • OFFSET 2 ROWS FETCH FIRST 3 ROWS ONLY: the SQL standard; PostgreSQL, Oracle (12c and later), SQL Server (2012 and later, which needs ORDER BY).
  • SELECT TOP 3 ...: SQL Server.

PostgreSQL accepts both of its forms:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, salary FROM employees
ORDER BY salary DESC NULLS LAST, name
OFFSET 1 ROWS FETCH FIRST 2 ROWS ONLY;
namesalary
Mei95000
Ravi95000

SQLite accepts LIMIT but not the standard syntax:

sql
SELECT name, salary FROM employees
ORDER BY salary DESC NULLS LAST, name
LIMIT 2 OFFSET 1;
namesalary
Mei95000
Ravi95000
sql
SELECT name FROM employees ORDER BY salary DESC FETCH FIRST 2 ROWS ONLY;  -- error on purpose
text
Error: near "FETCH": syntax error

The standard form has one feature LIMIT lacks: FETCH FIRST 2 ROWS WITH TIES also returns any rows that tie with the last one on the ORDER BY key. PostgreSQL supports it since version 13:

sql
SELECT name, salary FROM employees
ORDER BY salary DESC NULLS LAST
FETCH FIRST 2 ROWS WITH TIES;
namesalary
Asha120000
Ravi95000
Mei95000

Ravi and Mei both earn 95000 and share second place, so WITH TIES returns three rows for "top 2". A plain LIMIT 2 would have dropped one of them, and which one would depend on the plan.

The TOP and Oracle details come from vendor documentation and were not run here. Whatever the syntax, without ORDER BY the database is free to pick any rows.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, salary FROM employees
ORDER BY salary DESC NULLS LAST, name
LIMIT 2 OFFSET 1;

-- error on purpose
SELECT name FROM employees ORDER BY salary DESC FETCH FIRST 2 ROWS ONLY;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Standard: OFFSET ... FETCH FIRST n ROWS ONLY
  • LIMIT/OFFSET: PostgreSQL, MySQL, SQLite
  • TOP: SQL Server
  • WITH TIES returns extra rows that tie with the last row

Common mistakes

  • Using LIMIT without ORDER BY and expecting the same rows each time
  • Assuming SQLite accepts FETCH FIRST because PostgreSQL does

Follow-ups

  • How would you get top 3 salaries including ties on SQLite?
  • Why does OFFSET get slow on large tables?

Tips

  • Mention WITH TIES; it shows you know the standard goes beyond LIMIT
17.sql-0017Easyfresher

Explain what a table, a row, a column, a primary key and a foreign key are in a relational database.

A table stores one kind of thing, each row is one instance of it, and each column is one attribute with a type. A primary key is a column or set of columns whose value uniquely identifies a row. A foreign key is a column that must match a primary key (or unique key) in another table, which is how tables link.

Full answer

Think of a college register.

  • A table holds one kind of thing: students, courses, enrolments.
  • A row is one instance: the student Asha.
  • A column is one attribute every row has, with a data type: name TEXT, year INTEGER.
  • A primary key identifies each row uniquely and never repeats: students.id. It cannot be NULL. A table has at most one primary key, but the key can span several columns, like (student_id, course_id) in enrolments.
  • A foreign key is a column whose value must exist as a key in another table. enrolments.student_id must be the id of a real student. This is called referential integrity.
sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

PRAGMA foreign_keys = ON;

The foreign key is what makes a join meaningful. To list each student with their marks, you match enrolments.student_id to students.id:

sql
SELECT s.name, c.title, e.marks
FROM enrolments e
JOIN students s ON s.id = e.student_id
JOIN courses  c ON c.id = e.course_id
WHERE s.id = 1
ORDER BY c.title;
nametitlemarks
AshaAlgorithms92
AshaDatabases88

With foreign keys enforced, the database refuses an enrolment for a student who does not exist:

sql
INSERT INTO enrolments VALUES (99, 10, 70);  -- error on purpose
text
Error: FOREIGN KEY constraint failed

SQLite only enforces foreign keys after PRAGMA foreign_keys = ON; PostgreSQL always enforces them.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

PRAGMA foreign_keys = ON;

SELECT s.name, c.title, e.marks
FROM enrolments e
JOIN students s ON s.id = e.student_id
JOIN courses  c ON c.id = e.course_id
WHERE s.id = 1
ORDER BY c.title;

-- error on purpose
INSERT INTO enrolments VALUES (99, 10, 70);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Table: one kind of entity; row: one instance; column: one typed attribute
  • Primary key: unique, not NULL, one per table, can be composite
  • Foreign key: value must exist in the referenced table
  • SQLite enforces foreign keys only when the pragma is on

Common mistakes

  • Saying a table can have several primary keys (it can have several unique keys, but one primary key)
  • Assuming SQLite checks foreign keys by default

Follow-ups

  • How does a primary key differ from a unique constraint?
  • What is a composite key and when do you need one?

Tips

  • Use one small example schema and point to each concept in it
18.sql-0018Mediummid

When would you choose a relational SQL database over a document store, and when the other way round?

Choose a relational database when data has clear relationships, you need joins, constraints and multi-row transactions, and the questions you will ask are varied. Choose a document store when each record is read and written as one self-contained unit, the shape varies between records, and you rarely query across records. Most products start relational and add other stores for specific needs.

Full answer

The honest answer starts with the access pattern, not with a brand name.

A relational database fits when:

  • Entities relate to each other: customers have orders, orders have items, items reference products.
  • You need the database to enforce rules: foreign keys, unique emails, CHECK constraints.
  • A business action changes several rows at once and must be all-or-nothing, such as moving stock and creating an order.
  • You do not know every question in advance. SQL lets an analyst join and group the same data in new ways next month.

A document store such as MongoDB fits when:

  • Each record is loaded and saved as a whole, like a user's settings or a product page with a varying set of attributes.
  • Different records legitimately have different fields.
  • Queries almost always fetch by one key, and cross-record reporting is rare or done in a separate system.

The cost of a document model shows up when the access pattern changes. If orders are embedded inside customer documents, a report of "all orders last week across all customers" becomes awkward, and data duplicated across documents has to be kept in sync by application code.

The line is also less sharp than it used to be. PostgreSQL stores and indexes JSON (the jsonb type), and many document stores now offer multi-document transactions. A common, sensible setup is a relational database as the source of truth, with a cache, a search index or a document store added for a specific read pattern.

Key points

  • Start from the access pattern and the consistency needs
  • Relational: relationships, constraints, multi-row transactions, ad-hoc questions
  • Document: self-contained records, varying shape, key-based access
  • PostgreSQL jsonb blurs the line for semi-structured fields

Common mistakes

  • Choosing a document store because the schema is not designed yet
  • Claiming NoSQL is always faster or always scales better

Follow-ups

  • How would you store product attributes that differ by category in PostgreSQL?
  • What does eventual consistency mean for a user-facing feature?

Tips

  • Tie the choice to one concrete feature, such as an order checkout or a settings page
  • Avoid absolute claims about speed; talk about access patterns
19.sql-0019Mediummid

When you only want unique values, should you use SELECT DISTINCT or GROUP BY?

For returning unique combinations of columns, SELECT DISTINCT a, b and SELECT a, b GROUP BY a, b give the same rows, and planners often execute them the same way. GROUP BY is needed as soon as you also want an aggregate per group, such as a count. DISTINCT states intent more clearly when no aggregate is involved.

Full answer

Both remove duplicates, and for a plain "unique values" query they return the same result:

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);
sql
SELECT DISTINCT city FROM students WHERE city IS NOT NULL ORDER BY city;
city
Leeds
Pune
sql
SELECT city FROM students WHERE city IS NOT NULL GROUP BY city ORDER BY city;
city
Leeds
Pune

Most planners turn both into the same work: sort or hash the rows on the listed columns and keep one per key. You can check what SQLite plans for each with EXPLAIN QUERY PLAN:

sql
EXPLAIN QUERY PLAN SELECT DISTINCT city FROM students;
text
QUERY PLAN
SCAN students
USE TEMP B-TREE FOR DISTINCT
sql
EXPLAIN QUERY PLAN SELECT city FROM students GROUP BY city;
text
QUERY PLAN
SCAN students
USE TEMP B-TREE FOR GROUP BY

SQLite reports a temporary B-tree for each: one "FOR DISTINCT", the other "FOR GROUP BY". Either way it builds the same kind of structure to find unique keys.

The difference is what you can do next. GROUP BY lets you attach aggregates to each unique value:

sql
SELECT city, COUNT(*) AS students FROM students WHERE city IS NOT NULL GROUP BY city ORDER BY city;
citystudents
Leeds2
Pune2

DISTINCT cannot do that. Use DISTINCT when you only want unique rows, because it reads as exactly that. Use GROUP BY when you need counts, sums or other per-group values. Using GROUP BY without aggregates just to remove duplicates works, but reviewers will wonder whether an aggregate was forgotten.

sql
CREATE TABLE students (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  city TEXT,
  year INTEGER
);
CREATE TABLE courses (
  id      INTEGER PRIMARY KEY,
  title   TEXT NOT NULL,
  credits INTEGER
);
CREATE TABLE enrolments (
  student_id INTEGER REFERENCES students(id),
  course_id  INTEGER REFERENCES courses(id),
  marks      INTEGER,
  PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1,'Asha','Pune',1),(2,'Ben','Leeds',2),(3,'Chen','Pune',1),(4,'Dara',NULL,3),(5,'Eli','Leeds',2);
INSERT INTO courses VALUES (10,'Databases',4),(20,'Algorithms',4),(30,'Statistics',3),(40,'Ethics',2);
INSERT INTO enrolments VALUES
  (1,10,88),(1,20,92),(2,10,75),(2,30,NULL),
  (3,10,64),(3,20,71),(3,30,80),(5,20,55);

SELECT DISTINCT city FROM students WHERE city IS NOT NULL ORDER BY city;

SELECT city FROM students WHERE city IS NOT NULL GROUP BY city ORDER BY city;

EXPLAIN QUERY PLAN SELECT DISTINCT city FROM students;

EXPLAIN QUERY PLAN SELECT city FROM students GROUP BY city;

SELECT city, COUNT(*) AS students FROM students WHERE city IS NOT NULL GROUP BY city ORDER BY city;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • DISTINCT and GROUP BY without aggregates return the same rows
  • Planners usually execute them the same way
  • GROUP BY is required for per-group aggregates
  • Pick the one that states the intent

Common mistakes

  • Using DISTINCT to cover duplicates caused by a bad join
  • Claiming one is always faster without checking the plan

Follow-ups

  • What does COUNT(DISTINCT city) do?
  • How would you get the number of unique cities per year?

Tips

  • Back up any performance claim with EXPLAIN on the target engine
20.sql-0020Easyfresher

Can ORDER BY refer to a column by its position, as in ORDER BY 2? Is that a good idea?

Yes. ORDER BY 2 sorts by the second column in the select list, and most engines support it. It is fine for quick ad-hoc queries, but risky in saved code: if someone adds or reorders a column in the SELECT list, the sort silently changes to a different column. Naming the column or alias is safer.

Full answer

A number in ORDER BY refers to a position in the select list, counting from 1. ORDER BY 2 DESC means "sort by the second output column, descending".

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
SELECT name, salary FROM employees WHERE dept_id = 1 ORDER BY 2 DESC, 1;
namesalary
Asha120000
Mei95000
Ravi95000

This is handy at a SQL prompt. In code that will be edited later, it is fragile. Suppose a teammate adds a column at the front:

sql
SELECT dept_id, name, salary FROM employees WHERE dept_id = 1 ORDER BY 2 DESC, 1;
dept_idnamesalary
1Ravi95000
1Mei95000
1Asha120000

The query still runs, but now it sorts by name, not by salary, and nobody gets an error. Sorting by the column name or alias keeps working whatever happens to the column order:

sql
SELECT dept_id, name, salary FROM employees WHERE dept_id = 1 ORDER BY salary DESC, name;
dept_idnamesalary
1Asha120000
1Mei95000
1Ravi95000

Positions work in GROUP BY too (GROUP BY 1) on PostgreSQL, MySQL and SQLite, with the same trade-off. A position outside the list, such as ORDER BY 5 with three columns, is an error.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

SELECT name, salary FROM employees WHERE dept_id = 1 ORDER BY 2 DESC, 1;

SELECT dept_id, name, salary FROM employees WHERE dept_id = 1 ORDER BY 2 DESC, 1;

SELECT dept_id, name, salary FROM employees WHERE dept_id = 1 ORDER BY salary DESC, name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ORDER BY n sorts by the n-th select list column
  • Editing the select list silently changes the sort
  • Prefer names or aliases in saved queries

Common mistakes

  • Adding a column to the SELECT and breaking a positional sort without noticing

Follow-ups

  • Does GROUP BY 1 work the same way?
  • What happens with ORDER BY 0?

Tips

  • Say it works, then say why you would not commit it