// free study notes

SQL basics interview questions

The questions interviewers use to check that you know the language itself, without an ORM in the way. Every answer ships with runnable SQL.

12 questions
  • 8 easy
  • 4 medium
  • 0 hard
Practice mode: all topics, shuffled

What this page covers

  • 12 questions on SQL basics, tagged easy, medium or hard, each with a worked answer in runnable SQL.
  • One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
  • Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
The shop schema
customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, status, total)
order_items(order_id, product_id, quantity, unit_price)
products(product_id, name, category, price)
employees(employee_id, name, manager_id, department, salary, hired_on)

The questions

What is the logical evaluation order of a SELECT query?

Средний

Most engines evaluate a query roughly in this order: FROM and JOIN first, then WHERE, then GROUP BY, then HAVING, then the SELECT list, then ORDER BY and LIMIT.

SELECT city, COUNT(*) AS customers      -- 5. SELECT
FROM customers                           -- 1. FROM / JOIN
WHERE signup_date >= '2025-01-01'        -- 2. WHERE
GROUP BY city                            -- 3. GROUP BY
HAVING COUNT(*) > 10                     -- 4. HAVING
ORDER BY customers DESC                  -- 6. ORDER BY

The practical consequence: a column alias defined in the SELECT list cannot be used in WHERE, because WHERE runs first. Every engine accepts the alias in ORDER BY, which runs last. HAVING is where engines split: MySQL and SQLite accept a SELECT alias there as an extension, while PostgreSQL and SQL Server make you repeat the expression. Window functions and DISTINCT are evaluated with the SELECT list, which is why a window function cannot appear in WHERE either.

What does NULL mean, and why does NULL = NULL not return true?

Easy

NULL means unknown. A value may be missing, or not apply, or not be entered yet, and the engine cannot say whether two unknowns are equal. So NULL = NULL does not return true; it returns NULL, which the WHERE clause treats as not-true and filters out.

-- Returns zero rows even if the column holds NULLs:
SELECT * FROM customers WHERE city = NULL;

-- The correct forms:
SELECT * FROM customers WHERE city IS NULL;
SELECT * FROM customers WHERE city IS NOT NULL;

This three-valued logic (true, false, unknown) is the root of most NULL surprises, including NOT IN with a NULL in the list.

How do you count or sum correctly when NULLs are involved?

Easy

Aggregates skip NULLs: COUNT(column) counts only non-NULL values while COUNT(*) counts rows. SUM, AVG, MIN and MAX ignore NULL rows entirely, and AVG therefore divides by the number of non-NULL values, not the number of rows.

-- Suppose orders has a nullable discount column holding 10, NULL, 20.
-- Returns 3, 2, 15 and 15: AVG divides 30 by 2, not by 3.
SELECT COUNT(*) AS rows_all,
COUNT(discount) AS rows_with_discount,
AVG(discount) AS mean_of_non_null,
COALESCE(AVG(discount), 0) AS mean_or_zero
FROM orders;

If missing discounts should count as zero, the average you want is AVG(COALESCE(discount, 0)), which returns 10. COALESCE(AVG(discount), 0) only replaces the result when every row is NULL. Mixing those two up is the mistake this question is fishing for. ISNULL (SQL Server) and IFNULL (MySQL, SQLite) are the two-argument shorthands.

What is the difference between UNION and UNION ALL?

Easy

UNION ALL concatenates two result sets and keeps everything. UNION additionally removes duplicate rows, which costs a sort or a hash to detect them. If duplicates are impossible or acceptable, UNION ALL is faster.

-- One contact list; UNION deduplicates people in both tables:
SELECT name, email FROM customers
UNION
SELECT name, email FROM subscribers;

-- UNION ALL keeps two rows for anyone who is in both tables:
SELECT name, email FROM customers
UNION ALL
SELECT name, email FROM subscribers;

Both require the same number of columns with compatible types in each branch, and the result takes its column names from the first branch. UNION compares whole rows, so the same email with a different name spelling still comes back twice.

What does DISTINCT do, and when can it hide a bug?

Easy

DISTINCT removes duplicate rows from the result. It applies to the whole selected row, not just the column it is written next to: SELECT DISTINCT city, name returns one row per city and name pair.

SELECT DISTINCT city FROM customers;

The interview follow-up: an unexpected DISTINCT is often a symptom of join fan-out. If joining orders to order_items tripled your row counts and you papered over it with DISTINCT, your SUM and COUNT aggregates are still wrong. Fix the grain of the join first; use DISTINCT to answer a genuine distinct-values question.

What is the difference between DELETE and TRUNCATE?

Easy

DELETE removes the rows that match its WHERE clause one by one, logs each row and fires DELETE triggers. TRUNCATE empties the whole table by deallocating its pages, so its cost does not grow with the row count. It takes no WHERE, fires no DELETE triggers, and is refused while another table's foreign key references the table (PostgreSQL lets you add CASCADE).

-- Precise, logged, rollable back, slower on big tables:
DELETE FROM orders WHERE status = 'cancelled';

-- Every row, at a cost that does not grow with table size:
TRUNCATE TABLE staging_orders;

The engine differences are what make the answer strong. TRUNCATE can be rolled back inside a transaction on PostgreSQL and SQL Server, but on MySQL it causes an implicit commit. SQL Server and MySQL reset the identity or AUTO_INCREMENT counter; PostgreSQL keeps the sequence going unless you write TRUNCATE ... RESTART IDENTITY. SQLite has no TRUNCATE at all: DELETE FROM t without a WHERE clause takes a fast path instead.

What is the difference between CHAR, VARCHAR and TEXT?

Easy

CHAR(n) stores fixed-length strings padded with spaces, which suits codes of a known length such as two-letter country codes. VARCHAR(n) stores variable-length strings up to n characters. TEXT stores long strings: up to 1 GB on PostgreSQL (where VARCHAR without a length means the same thing), 64 KB for MySQL's TEXT, with MEDIUMTEXT and LONGTEXT above it. SQL Server's TEXT type is deprecated; use VARCHAR(MAX) or NVARCHAR(MAX).

CREATE TABLE products (
product_id   BIGINT PRIMARY KEY,
country_code CHAR(2) NOT NULL,        -- always exactly 2 characters
name         VARCHAR(200) NOT NULL,   -- bounded, indexed comfortably
description  TEXT                     -- long free-form text
);

In PostgreSQL VARCHAR(n) and TEXT are stored the same way, so the choice is about whether you want the length enforced. MySQL and SQL Server differ: MySQL cannot index a full TEXT column without a prefix length, and SQL Server cannot use a MAX column as an index key. The CHAR detail worth knowing is padding: CHAR(5) stores 'ab' as 'ab ', and comparisons ignore the trailing spaces.

What is the difference between a PRIMARY KEY and a UNIQUE constraint?

Средний

Both enforce uniqueness. A PRIMARY KEY is the table's identity: at most one per table, implicitly NOT NULL, and usually the target of foreign keys. A table can have several UNIQUE constraints, and they allow NULLs. PostgreSQL, MySQL, SQLite and Oracle accept many NULLs in a UNIQUE column because NULL is not equal to NULL; SQL Server allows only one, unless you use a filtered unique index with WHERE col IS NOT NULL. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT for the opposite behavior.

CREATE TABLE customers (
customer_id BIGINT PRIMARY KEY,          -- identity, never business meaning
email       VARCHAR(320) NOT NULL UNIQUE, -- business key, still enforced
name        VARCHAR(200) NOT NULL
);

On InnoDB the primary key is always the clustered index, and on SQL Server it is by default, so its width is copied into every secondary index. In PostgreSQL the table is a heap and the primary key is a unique B-tree like any other index.

How does pagination work, and why is OFFSET slow on deep pages?

Средний

LIMIT (or TOP / FETCH FIRST) caps the row count and OFFSET skips rows. The engine still produces and discards the skipped rows, so page 1000 of a 10-row page (OFFSET 9990) reads 10,000 rows to return 10. Keyset pagination seeks straight to the last seen key instead.

-- Page by page (fine for the first few pages):
SELECT order_id, order_date
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10 OFFSET 200;

-- Keyset pagination (fast at any depth):
SELECT order_id, order_date
FROM orders
WHERE (order_date, order_id) < ('2025-06-01', 481516)
ORDER BY order_date DESC, order_id DESC
LIMIT 10;

The tiebreaker column makes the sort total, which is the other half of the answer: without it, rows that tie on order_date can repeat or vanish between pages. An index on (order_date, order_id) lets the keyset query seek directly. Row-value comparison works on PostgreSQL, MySQL and SQLite; on SQL Server spell it out as order_date < @d OR (order_date = @d AND order_id < @id). The cost of keyset paging is that you can only go to the next or previous page, not jump to page 37.

What does the BETWEEN operator do, and what is the classic date bug?

Easy

BETWEEN is inclusive on both ends. If order_date is a timestamp rather than a date, '2025-12-31' means midnight at the start of December 31, so BETWEEN '2025-01-01' AND '2025-12-31' silently drops almost the whole last day.

-- Bug: misses everything after 2025-12-31 00:00:00:
SELECT * FROM orders
WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31';

-- Correct: half-open range:
SELECT * FROM orders
WHERE order_date >= '2025-01-01'
AND order_date < '2026-01-01';

The half-open range (>= start, < next start) is correct for DATE, timestamp and DATETIME2 columns alike, so it keeps working if someone changes the column type later. Writing '2025-12-31 23:59:59.999' instead is fragile: SQL Server's DATETIME rounds it up to the next day.

What does ORDER BY guarantee, and why add a tiebreaker?

Средний

ORDER BY sorts by the listed expressions; rows that tie on all of them may come back in any order, and that order can change between runs, indexes or parallel plans. SQL does not guarantee stable sorts.

-- Ties on total are ordered arbitrarily:
SELECT order_id, total FROM orders ORDER BY total DESC;

-- Total order, deterministic pagination and deduplication:
SELECT order_id, total FROM orders ORDER BY total DESC, order_id;

If a query relies on row order for paging, ranking or deduplication, always add a unique tiebreaker column. The only ordering that exists is the one a final ORDER BY specifies; a SELECT without ORDER BY has no order at all, even if it always looks sorted.

How does a CASE expression work, and where can it be used?

Easy

CASE returns a value from the first matching condition, with an optional ELSE default (NULL if omitted). It is an expression, so it goes anywhere an expression is allowed: the SELECT list, WHERE, ORDER BY, GROUP BY and aggregates.

SELECT order_id,
CASE
WHEN total >= 500 THEN 'large'
WHEN total >= 100 THEN 'medium'
ELSE 'small'
END AS size_bucket
FROM orders;

Conditions are tested in order and the first match wins, which is why the 500 check comes before the 100 check. All branches must return compatible types: mixing a number and a string makes SQL Server try to convert the string and fail at runtime. CASE inside SUM or COUNT is conditional aggregation, which has its own question.

SQL basics interview FAQ

What SQL dialect are these answers written in?

Standard SQL where it exists. When a question needs one dialect, such as date truncation or generate_series, the example is PostgreSQL and the answer says so, along with the SQL Server, MySQL and SQLite spelling where it differs.

What schema do the worked answers use?

One small shop schema: customers, orders, order_items and products, plus an employees table with a manager_id for self joins. It is printed at the top of the page so every answer makes sense in context.

What difficulty are the basics questions?

They run from easy warm-ups such as NULL handling to medium questions about the logical order of query evaluation and reliable pagination.

Can I practice these instead of reading them?

Yes. Press Hide answers, next to the question list, and this page becomes a quiz: each answer stays hidden until you reveal it, and a counter tracks how many you have opened. The difficulty buttons narrow the list to easy, medium or hard questions. For a shuffled deck across every topic, use the Practice mode link at the top of the page.

Other topics

// from study notes to daily tool

Now write some SQL against a real database

SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your schema, a formatter, guardrails for risky queries, and every engine in one app.