SQL Queries, Joins and Window Functions Interview Questions

261 multiple-choice tech interview questions on SQL Queries, Joins and Window Functions: SELECT, joins, GROUP BY and HAVING, subqueries and CTEs, window functions. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 240 key terms with the flashcards first, then test yourself.

Take the practice test · Flashcards · All study tools

What it covers

  1. 2.1 SELECT basics, filtering and sorting
  2. 2.2 NULLs, expressions and conditional logic
  3. 2.3 Joins
  4. 2.4 Aggregation and grouping
  5. 2.5 Subqueries, set operations and CTEs
  6. 2.6 Window functions
  7. 2.7 Modifying data: INSERT, UPDATE, DELETE and MERGE
  8. 2.8 Dates, strings, JSON and dialect differences
  9. 2.9 SQL interview problems and query patterns

Key terms

2.1 SELECT basics, filtering and sorting

Three-valued logic
SQL conditions can be TRUE, FALSE or UNKNOWN; comparisons with NULL are UNKNOWN
BETWEEN
Inclusive range test: `x BETWEEN a AND b` means `x >= a AND x <= b`
Half-open range
A range with an inclusive start and exclusive end, like `>= start AND < end`
Operator precedence (AND/OR)
AND is evaluated before OR unless parentheses say otherwise
IN list
A predicate testing whether a value equals any item in a list
LIKE wildcards
In LIKE patterns `%` matches any run of characters and `_` exactly one
ESCAPE clause
Names a character that makes the next LIKE wildcard match literally
ILIKE
PostgreSQL's case-insensitive version of LIKE
NULLS FIRST / NULLS LAST
ORDER BY options that place NULLs before or after other values
Unordered result
A result without ORDER BY, whose row order is unspecified
Positional ORDER BY
Sorting by a select-list position number instead of a column name
Sort direction
ASC or DESC applies to the single ORDER BY key it follows
Deterministic ordering
An ORDER BY whose keys are unique, so row order can't vary
FETCH FIRST
Standard SQL row-limiting clause, like `FETCH FIRST 10 ROWS ONLY`
WITH TIES
Row-limit option that also returns rows tied with the last kept row
Quoted identifier
A name in double quotes, allowing reserved words, spaces or exact case
Identifier case folding
Unquoted names are folded to one case (lowercase in PostgreSQL)
Escaped quote
Two single quotes inside a string literal represent one
LIMIT 0
A query returning no rows, used to read result column metadata
ISO 8601 date literal
The `YYYY-MM-DD` format, as in `DATE '2026-03-04'`
DUAL
Oracle's one-row dummy table for selecting expressions
Custom sort order
Sorting by a CASE expression or rank column instead of raw values
Regex match
Pattern matching with regular expressions, like `~` in PostgreSQL
View column binding
Views store their column list at creation, so `*` doesn't pick up new columns
De Morgan's laws
NOT (A OR B) = NOT A AND NOT B; NOT (A AND B) = NOT A OR NOT B

2.2 NULLs, expressions and conditional logic

UNKNOWN
The third truth value, produced by comparisons involving NULL
IS DISTINCT FROM
Null-safe inequality: always TRUE or FALSE, never UNKNOWN
Null-safe equal (<=>)
MySQL operator that treats two NULLs as equal
NULL propagation
Most expressions return NULL when any input is NULL
CONCAT
String function joining values, treating NULL arguments as empty
Empty string vs NULL
Most databases treat '' as a known empty value; Oracle treats it as NULL
NULLIF
Returns NULL if two arguments are equal, else the first
ISNULL (SQL Server)
Two-argument NULL replacement that returns the first argument's type
CASE ELSE
The default branch of CASE; without it, unmatched rows return NULL
CASE evaluation order
CASE checks WHEN branches in order and returns the first match
Integer division
Dividing two integers truncates the fractional part in many databases
DECIMAL / NUMERIC
Exact fixed-point numeric types with set precision and scale
Three-valued AND/OR
FALSE AND anything is FALSE; TRUE OR anything is TRUE, even with NULL
NOT UNKNOWN
Negating UNKNOWN yields UNKNOWN, so the row is still filtered
GREATEST / LEAST
Functions returning the largest or smallest of their arguments
Implicit conversion
The database silently converts types to compare them
N prefix
Marks an nvarchar (Unicode) literal in SQL Server
IIF
SQL Server shorthand for `CASE WHEN cond THEN a ELSE b END`
IN with NULL
A list containing NULL can make IN return UNKNOWN instead of FALSE
UNIQUE and NULL
Whether NULLs count as duplicates varies; SQL Server allows one
TRIM
Removes leading and trailing spaces (or given characters)
CASE result type
All CASE branches must resolve to one compatible type
Division by zero
Error in most databases, NULL in MySQL SELECTs
Modulo
Remainder after division, `%` or MOD()
CEILING / FLOOR
Round up to the next integer, or down to the previous one
IS NULL
The predicate for testing NULL, since `= NULL` is never TRUE

2.3 Joins

INNER JOIN
Returns only rows that match in both tables
LEFT OUTER JOIN
Returns every left-table row, with NULLs where the right table has no match
Anti-join
Rows in one table with no match in another, written with NOT EXISTS or LEFT JOIN ... IS NULL
ON vs WHERE in outer joins
ON decides which right rows match; WHERE filters afterwards and can drop NULL-padded rows
RIGHT JOIN
Keeps every row of the right table, NULL-padding unmatched left rows
USING clause
Join shorthand for equality on same-named columns, merging them into one output column
NATURAL JOIN
Joins on all columns with matching names in both tables
Comma join
Old-style join listing tables with commas and conditions in WHERE
Non-equi join
A join whose condition uses ranges or inequalities rather than equality
Composite join
Joining on every column of a multi-column key
Outer join nullified
A later inner join or WHERE filter that removes NULL-padded rows, undoing a LEFT JOIN
Join cardinality
How many rows a join yields per row: one-to-one, one-to-many or many-to-many
NULL join keys
Equality joins never match NULLs, so those rows drop from inner joins
Ambiguous column
Error when a column name exists in more than one joined table
Reconciliation join
A full outer join filtered to unmatched rows, showing differences between two tables
FULL JOIN emulation
Combining LEFT and RIGHT joins with UNION where FULL OUTER JOIN is missing
Calendar table
A table with one row per date, used to fill gaps in reports
Junction table join
Joining two tables through the table that links them in a many-to-many relationship
Pairs self-join
Self-join with `a.id < b.id` to get each unordered pair once
CROSS JOIN
Pairs every row of one table with every row of another
LEFT JOIN row count
A left join returns at least one row per left row, more when matches repeat
Always-true join
A join condition that every pair satisfies, giving a cross join
Equi-join
A join that matches rows using equality conditions
COUNT after LEFT JOIN
Counting a right-table column gives 0 for unmatched rows; COUNT(*) gives 1
JOIN keyword defaults
Plain JOIN is an inner join; OUTER is optional in LEFT/RIGHT/FULL

2.4 Aggregation and grouping

SUM of no rows
Aggregates other than COUNT return NULL when there are no input rows
AVG and NULL
AVG divides the sum of non-NULL values by their count
AVG result type
Some databases return AVG in the input's integer type
COUNT(DISTINCT)
Counts unique non-NULL values in a column
Conditional aggregation
Aggregating a CASE expression to count or sum only matching rows
FILTER clause
Standard syntax that limits which rows an aggregate sees
GROUP BY NULLs
All NULL keys fall into a single group
ROLLUP
GROUP BY extension adding hierarchical subtotals and a grand total
CUBE
GROUP BY extension producing subtotals for all combinations of the listed columns
GROUPING SETS
Lists the exact groupings to compute in one query
GROUPING()
Function returning 1 when a column was rolled up in a subtotal row
Functional dependency in GROUP BY
Grouping by a primary key lets you select other columns of that table
STRING_AGG
Aggregate that concatenates values with a separator
HAVING without GROUP BY
Filters the single group formed by the whole input
Aggregate in WHERE
Not allowed, since WHERE runs before aggregation
Collation
Rules for comparing and sorting text, including case and accent sensitivity
Grouping by period
Grouping on a truncated date to aggregate by day, month or year
MIN / MAX
Aggregates returning the smallest or largest value of any ordered type
COUNT(*) vs COUNT(1)
Equivalent row counts; neither reads all columns
PERCENTILE_CONT
Ordered-set aggregate that interpolates a percentile, like the median
BOOL_AND / EVERY
Aggregate that is TRUE when all values are TRUE
Average of averages
Averaging group averages ignores group sizes
GROUP BY alias
Using a SELECT alias in GROUP BY; allowed in some dialects, not SQL Server
SUM(DISTINCT)
Sums only distinct values, dropping repeats
ANY_VALUE
Aggregate returning an arbitrary value from each group
Empty grouping
A scalar aggregate returns one row; GROUP BY over no rows returns none

2.5 Subqueries, set operations and CTEs

HAVING
Filters groups after GROUP BY aggregation
Correlated subquery
A subquery that references the outer query's columns
CTE
Common table expression: a named temporary result defined with WITH
WITH RECURSIVE
Keyword marking a CTE as recursive in PostgreSQL, MySQL and SQLite
Scalar subquery
A subquery returning one column and at most one row, used as a value
Empty scalar subquery
A scalar subquery with no rows yields NULL
NOT EXISTS
Anti-join predicate that is TRUE when the subquery returns no rows
Derived table
A subquery used in FROM as an inline table
INTERSECT
Set operation returning rows present in both query results
EXCEPT / MINUS
Set difference: rows in the first result that aren't in the second
UNION compatibility
Queries in a set operation need matching column counts and compatible types
ORDER BY with set operations
A final ORDER BY sorts the whole combined result
Set operations and NULL
Set operations treat NULLs as equal when comparing rows
Anchor member
The non-recursive starting query of a recursive CTE
CYCLE clause
Standard recursive CTE option that detects and stops at cycles
MAXRECURSION
SQL Server query hint limiting recursion depth, 100 by default
Chained CTEs
Several CTEs in one WITH, where later ones read earlier ones
ANY / SOME
Compares a value with each subquery row; TRUE if any comparison is
CTE scope
A CTE exists only within its own statement
Data-modifying CTE
A PostgreSQL CTE containing INSERT, UPDATE or DELETE with RETURNING
ALL
Compares a value with every subquery row; TRUE if all comparisons are, or no rows
Number series
A generated sequence of integers, from a recursive CTE or series function
Per-group comparison
Comparing each row with an aggregate of its own group
EXISTS select list
The select list inside EXISTS doesn't matter; only row presence does
Set operation precedence
INTERSECT is evaluated before UNION and EXCEPT
Row value comparison
Comparing tuples of columns, like `(a, b) IN (...)`
Outer reference capture
An unqualified column in a subquery silently binding to the outer query

2.6 Window functions

Window function
A function computed over a set of rows defined by OVER(), without collapsing the rows
PARTITION BY
Divides rows into groups for a window function, like GROUP BY without collapsing
ROW_NUMBER
Gives each row in a partition a unique sequential number
LEAD
Window function returning a value from a following row in the partition
LAG default
Third LAG/LEAD argument used when the offset row doesn't exist
RANGE vs ROWS
RANGE frames include all rows tied on the ORDER BY value; ROWS counts physical rows
Partition total
A window aggregate without ORDER BY covers the whole partition
OVER ()
An empty window spanning every row of the result
FIRST_VALUE
Window function returning the value from the first row of the frame
LAST_VALUE frame
LAST_VALUE needs a frame extended to the partition's end
NTH_VALUE
Window function returning the value from the nth row of the frame
CUME_DIST / PERCENT_RANK
Relative position of a row in its partition, from 0 to 1
WINDOW clause
Defines a named window specification reused by OVER
RANGE with interval
A frame defined by a value distance, like days, rather than a row count
ROW_NUMBER ties
Tied rows get arbitrary relative numbers unless ORDER BY is unique
Period-over-period change
Comparing a value with the previous period's using LAG
Window over aggregate
A window function applied to grouped results, like `SUM(COUNT(*)) OVER ()`
Distinct window aggregate
`COUNT(DISTINCT) OVER` isn't supported in several databases
EXCLUDE clause
Frame option leaving out the current row, its peers or ties
GROUPS frame
A frame measured in peer groups of tied ORDER BY values
Window ORDER BY
Orders rows within the window computation, not the final result
MySQL 8.0 windows
MySQL added window functions and CTEs in 8.0
Centered window
A frame that looks both before and after the current row
Resetting running total
Partitioning a running total so it starts over per group

2.7 Modifying data: INSERT, UPDATE, DELETE and MERGE

INSERT ... SELECT
Inserts the result rows of a query into a table
Multi-row VALUES
A single INSERT listing several row constructors
INSERT column list
Naming target columns so the insert doesn't depend on table column order
UPDATE without WHERE
An UPDATE with no filter changes every row in the table
UPDATE ... FROM
PostgreSQL and SQL Server syntax for updating with values from another table
Ambiguous update source
A target row matching several source rows in UPDATE ... FROM gets an arbitrary one
SET evaluation
Standard SQL computes all SET expressions from old values; MySQL applies them in order
TRUNCATE
Removes all rows from a table at once, without row-by-row deletes
Transactional TRUNCATE
Whether TRUNCATE can be rolled back depends on the database
DELETE ... USING
PostgreSQL syntax for deleting with conditions on another table
Delete duplicates
Removing all but one row per duplicate key, often keeping MIN(id)
OUTPUT clause
SQL Server clause returning affected rows' old or new values
SCOPE_IDENTITY
Returns the last identity value generated in the current scope
ON DUPLICATE KEY UPDATE
MySQL upsert syntax that updates when an insert hits a unique key
ON CONFLICT DO NOTHING
PostgreSQL insert option that skips rows violating a unique constraint
EXCLUDED
Pseudo-table holding the proposed row in ON CONFLICT DO UPDATE
PostgreSQL MERGE
MERGE arrived in PostgreSQL 15; 17 added RETURNING and NOT MATCHED BY SOURCE
NOT MATCHED BY SOURCE
MERGE branch for target rows absent from the source, often deleted
SELECT INTO
SQL Server syntax that creates a table from a query result
Correlated UPDATE
An UPDATE whose SET uses a subquery evaluated per target row
Safe ad hoc change
Wrapping manual changes in BEGIN, checking affected rows, then COMMIT or ROLLBACK
sql_safe_updates
MySQL setting rejecting UPDATE/DELETE that lack a key filter or LIMIT
DELETE TOP
SQL Server syntax limiting how many rows a DELETE affects
Statement-level trigger
A trigger that fires once per statement, however many rows change
NEW and OLD
Row variables in PostgreSQL row triggers holding the new and old row versions
IDENTITY_INSERT
SQL Server setting allowing explicit values in an identity column
setval
PostgreSQL function setting a sequence's current value
VALUES table constructor
Using VALUES as an inline table in FROM
REPLACE INTO
MySQL statement that deletes a conflicting row, then inserts

2.8 Dates, strings, JSON and dialect differences

Date difference
Subtracting dates (PostgreSQL) or DATEDIFF (SQL Server, MySQL)
DATEDIFF boundaries
SQL Server DATEDIFF counts unit boundaries crossed, not elapsed whole units
Month arithmetic
Adding months clamps to the end of shorter months
CURRENT_TIMESTAMP
Standard SQL function for the current date and time
clock_timestamp
PostgreSQL function returning the actual current time, changing during a statement
AT TIME ZONE
Operator converting between timestamptz and local wall-clock time in a zone
age()
PostgreSQL function returning the interval between dates in years, months and days
EOMONTH
SQL Server function returning the last day of a date's month
to_char
PostgreSQL and Oracle function formatting dates and numbers as text
TRY_CAST
SQL Server conversion that returns NULL instead of raising an error
SUBSTRING
Extracts part of a string by 1-based start position and length
CHAR_LENGTH
Counts characters, while LENGTH in MySQL counts bytes
CHARINDEX / POSITION
Functions returning a substring's 1-based position, or 0 if missing
String concatenation
Double pipes are standard; SQL Server uses a plus sign; CONCAT works almost everywhere
LPAD
Pads a string on the left to a given length
STRING_SPLIT
SQL Server table function splitting a string by a separator
-> and ->>
PostgreSQL JSON operators returning JSON or text
JSONB containment (@>)
Tests whether one JSONB value contains another
json vs jsonb
PostgreSQL's text-preserving and binary-parsed JSON types
JSON_VALUE / JSON_QUERY
SQL Server functions for extracting scalars versus objects or arrays
JSON_TABLE
Standard function projecting JSON into relational rows and columns
jsonb_array_elements
Set-returning function expanding a JSON array into rows
json_agg / FOR JSON
Aggregating rows into JSON arrays in PostgreSQL and SQL Server
SQL Server json type
Native binary JSON storage added in SQL Server 2025
LEFT / RIGHT
Return a given number of characters from the start or end of a string
REGEXP_REPLACE
Replaces regex matches in a string
Trailing space padding
SQL Server pads strings before comparing, so trailing spaces don't affect `=`
Unix epoch
Seconds since 1970-01-01 UTC, converted with to_timestamp or FROM_UNIXTIME
DATE_ADD
MySQL function adding an interval to a date

2.9 SQL interview problems and query patterns

Second-highest value
Classic interview query: the maximum below the overall maximum
Nth highest distinct
DENSE_RANK = N finds the Nth distinct value, ignoring ties
Gaps and islands
Finding runs of consecutive values, often with date minus ROW_NUMBER
Sequence gap
A missing value between consecutive numbers, found with LEAD or LAG
Sessionization
Grouping events into sessions by inactivity gaps with LAG and a running sum
PIVOT
Operator turning row values into columns with an aggregate
UNPIVOT
Turning columns into rows of name-value pairs
Interval overlap test
Two ranges overlap when each starts before the other ends
Both-products query
Grouping per customer and counting distinct matches to require all listed items
Relational division
Finding entities related to every item in a set
Cohort
A group of users sharing a starting period, like first-purchase month
Manager comparison
Self-join comparing each row with its parent row
Consecutive repeats
Comparing a row with earlier rows via LAG to detect runs
Active per day
Counting entities whose interval covers each date via a calendar join
Hierarchy path
A string or array built during recursion listing a row's ancestors
Funnel step
Matching an event to a later event by the same user within a time window
Running balance
A signed running sum of credits and debits
Table comparison
Using EXCEPT both ways to prove two results match
Time to next event
Gap between an event and the same entity's next one, from LEAD
Top group
Ordering groups by an aggregate and keeping the first, with ties
Mode
The most frequent value in a set
Query grain
What one output row represents, like one row per customer per month
Join debugging
Checking cardinality step by step to find the join that multiplies rows
Bucketing
Grouping values into fixed-width ranges with FLOOR or width_bucket
Churned customers
Entities present in an earlier period but absent in the current one
Aggregate of aggregates
Computing per-entity totals first, then aggregating those totals
Interval merging
Combining overlapping ranges into continuous blocks
Top percentile filter
Selecting rows above a relative rank cutoff with PERCENT_RANK or NTILE
Every-period check
Requiring activity in each period by counting distinct periods

Sample practice questions

  1. In what logical order does SQL process these clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY?

    1. SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
    2. FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY
    3. FROM, SELECT, WHERE, HAVING, GROUP BY, ORDER BY
    4. WHERE, FROM, SELECT, GROUP BY, ORDER BY, HAVING

    Answer: B. FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY This logical order explains why a column alias defined in SELECT can be used in ORDER BY but not in WHERE.

  2. What does `WHERE manager_id = NULL` return?

    1. Every row whose manager_id is NULL, as intended
    2. No rows; `= NULL` is UNKNOWN, so use `IS NULL`
    3. Every row in the table, since NULL matches anything
    4. A syntax error in every database engine

    Answer: B. No rows; `= NULL` is UNKNOWN, so use `IS NULL` Three-valued logic: NULL = NULL is UNKNOWN, and WHERE keeps only rows where the condition is TRUE.

  3. What does an INNER JOIN return?

    1. Only rows that have a match in both tables according to the join condition
    2. All rows from the left table, with NULLs where there is no match
    3. All rows from both tables, matched where possible
    4. Every combination of rows from the two tables

    Answer: A. Only rows that have a match in both tables according to the join condition Unmatched rows on either side are dropped by an inner join.

  4. What is the difference between WHERE and HAVING?

    1. HAVING filters rows before grouping; WHERE filters groups after
    2. HAVING can only be used in queries that have no GROUP BY
    3. They're interchangeable and always give the same result
    4. WHERE filters rows before grouping; HAVING filters groups after

    Answer: D. WHERE filters rows before grouping; HAVING filters groups after Use HAVING for conditions on aggregates, such as `HAVING COUNT(*) > 5`.

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

    1. UNION ALL removes duplicate rows; UNION keeps them all
    2. UNION removes duplicate rows; UNION ALL keeps them and is faster
    3. UNION combines only two tables; UNION ALL combines any number
    4. There's no difference between them in standard SQL

    Answer: B. UNION removes duplicate rows; UNION ALL keeps them and is faster Removing duplicates needs a sort or hash step, so prefer UNION ALL when duplicates are impossible or acceptable.

  6. How does a window function differ from GROUP BY aggregation?

    1. It can only appear in the WHERE clause of a query
    2. It always sorts the final result set of the query
    3. It removes duplicate rows from the result set
    4. It computes across related rows but keeps every input row

    Answer: D. It computes across related rows but keeps every input row `SUM(amount) OVER (PARTITION BY customer_id)` adds a per-customer total to every row.

  7. What does `INSERT INTO archive (id, name) SELECT id, name FROM users WHERE active = false` do?

    1. Copies every inactive user's id and name into archive in one statement
    2. Inserts one row, the first inactive user found
    3. Creates the archive table with the selected columns
    4. Moves inactive users into archive and deletes them from users

    Answer: A. Copies every inactive user's id and name into archive in one statement INSERT ... SELECT is the set-based way to copy rows.

  8. How do you get the number of days between two dates in PostgreSQL and in SQL Server?

    1. `DAYS(end_date, start_date)` in PostgreSQL; `end_date - start_date` in SQL Server
    2. `end_date - start_date` in PostgreSQL; `DATEDIFF(day, start_date, end_date)` in SQL Server
    3. `INTERVAL(end_date, start_date)` in PostgreSQL; `DAYDIFF()` in SQL Server
    4. `DATEDIFF(end_date, start_date)` in both, with the same argument order

    Answer: B. `end_date - start_date` in PostgreSQL; `DATEDIFF(day, start_date, end_date)` in SQL Server MySQL's `DATEDIFF(end, start)` takes two arguments and returns days.

  9. Which query returns the second-highest salary without window functions?

    1. `SELECT MIN(salary) FROM emp WHERE salary > (SELECT MIN(salary) FROM emp)`
    2. `SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp)`
    3. `SELECT MAX(salary) - 1 FROM emp` using the gap to the next value
    4. `SELECT salary FROM emp ORDER BY salary DESC` and read row 2 by hand

    Answer: B. `SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp)` It returns NULL when there's no second distinct salary, which interviewers like.

  10. Why does `SELECT price * 2 AS doubled FROM items WHERE doubled > 10` fail in most databases?

    1. Column aliases can only be used on aggregate functions
    2. Arithmetic like multiplication isn't allowed in SELECT
    3. WHERE runs before SELECT, so the alias doesn't exist yet
    4. WHERE can't compare a computed number with a literal

    Answer: C. WHERE runs before SELECT, so the alias doesn't exist yet Repeat the expression in WHERE, or wrap the query in a subquery or CTE and filter the outer query.

Practice all 261 questions

More Storage and Data