← Interview prep

SQL interview questions

Queries, joins, window functions, and database design.

501 questions · Page 3 of 26

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

Page 3 of 26

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

41.sql-0041Easyfresher

Is an empty string the same as NULL?

No, in standard SQL and in SQLite, PostgreSQL, MySQL and SQL Server. An empty string is a known value of length zero; NULL means no value. Oracle is the well-known exception: it stores an empty VARCHAR2 as NULL. Pick one meaning for 'no value' in each column and enforce it.

Full answer

An empty string '' is a real value. It has a length of zero and it equals itself. NULL is the absence of a value:

sql
CREATE TABLE feedback (id INTEGER PRIMARY KEY, note TEXT);
INSERT INTO feedback (note) VALUES ('Great tea'), (''), (NULL), (NULL);
sql
SELECT '' IS NULL AS empty_is_null, LENGTH('') AS empty_len, LENGTH(NULL) AS null_len;
empty_is_nullempty_lennull_len
00NULL

They behave differently almost everywhere: WHERE note = '' does not find NULLs, COUNT(note) counts empty strings but not NULLs, and a unique constraint rejects a second '' but allows many NULLs.

sql
SELECT COUNT(*)                                    AS rows_total,
       COUNT(note)                                 AS non_null_notes,
       SUM(CASE WHEN note = '' THEN 1 ELSE 0 END)  AS empty_notes,
       SUM(CASE WHEN note IS NULL THEN 1 ELSE 0 END) AS null_notes
FROM feedback;
rows_totalnon_null_notesempty_notesnull_notes
4212

Oracle is the exception. It treats an empty string in a VARCHAR2 as NULL, so '' IS NULL is true there. That comes from Oracle documentation and was not run here. Code moved from Oracle to PostgreSQL often breaks on exactly this point.

Having both in one column is a data-quality problem. Searches for "missing note" have to check two things, and reports count them differently. Decide on one meaning. Usually NULL means "not provided", and empty input is converted on the way in with NULLIF(TRIM(x), ''). A CHECK constraint such as CHECK (note <> '') stops empty strings coming back.

sql
CREATE TABLE feedback (id INTEGER PRIMARY KEY, note TEXT);
INSERT INTO feedback (note) VALUES ('Great tea'), (''), (NULL), (NULL);

SELECT '' IS NULL AS empty_is_null, LENGTH('') AS empty_len, LENGTH(NULL) AS null_len;

SELECT COUNT(*)                                    AS rows_total,
       COUNT(note)                                 AS non_null_notes,
       SUM(CASE WHEN note = '' THEN 1 ELSE 0 END)  AS empty_notes,
       SUM(CASE WHEN note IS NULL THEN 1 ELSE 0 END) AS null_notes
FROM feedback;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • '' is a value of length zero; NULL is no value
  • COUNT, =, and UNIQUE treat them differently
  • Oracle stores '' in VARCHAR2 as NULL
  • Normalise to one representation and enforce it

Common mistakes

  • Searching for missing values with = '' and missing NULL rows
  • Assuming Oracle behaviour on PostgreSQL or the reverse

Follow-ups

  • How would you clean a column that mixes '', spaces and NULL?
  • Should a form field left blank be stored as '' or NULL?

Tips

  • Mention Oracle; it is the reason this question is asked
42.sql-0042Easyfresher

A report filters WHERE dept_id <> 2 to exclude Sales. Why does an employee with no department disappear too?

For an employee with a NULL dept_id, dept_id <> 2 is UNKNOWN, not TRUE, so WHERE drops the row. If people with no department should stay, write WHERE dept_id <> 2 OR dept_id IS NULL, or use dept_id IS DISTINCT FROM 2.

Full answer

"Everyone except Sales" sounds like it should include people with no department. SQL disagrees:

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, dept_id FROM employees WHERE dept_id <> 2 ORDER BY name;
namedept_id
Asha1
Diego3
Mei1
Omar3
Ravi1

Lena is missing. Her dept_id is NULL, and NULL <> 2 is UNKNOWN. WHERE only keeps TRUE rows.

If the business meaning is "everyone not known to be in Sales", include the NULL case on purpose:

sql
SELECT name, dept_id FROM employees WHERE dept_id <> 2 OR dept_id IS NULL ORDER BY name;
namedept_id
Asha1
Diego3
LenaNULL
Mei1
Omar3
Ravi1

The null-safe operator says the same thing in one condition:

sql
SELECT name, dept_id FROM employees WHERE dept_id IS DISTINCT FROM 2 ORDER BY name;
namedept_id
Asha1
Diego3
LenaNULL
Mei1
Omar3
Ravi1

This is the mirror image of the NOT IN trap. Any time a filter uses <>, NOT LIKE or NOT IN on a nullable column, ask whether rows with NULL should be in or out, and make the query say it. Silent exclusion is how headcount reports end up with numbers that do not add up.

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, dept_id FROM employees WHERE dept_id <> 2 ORDER BY name;

SELECT name, dept_id FROM employees WHERE dept_id <> 2 OR dept_id IS NULL ORDER BY name;

SELECT name, dept_id FROM employees WHERE dept_id IS DISTINCT FROM 2 ORDER BY name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • col <> value drops rows where col is NULL
  • Add OR col IS NULL when NULL rows should stay
  • IS DISTINCT FROM is the one-condition version
  • Check every negative filter on a nullable column

Common mistakes

  • Assuming 'not equal to X' includes unknowns
  • Reconciling counts and finding they do not add up to the table total

Follow-ups

  • Does NOT LIKE behave the same way with NULL?
  • How would you write the filter on an engine without IS DISTINCT FROM?

Tips

  • State the business question first: should unknowns be included?
43.sql-0043Mediummid

What does 3 IN (1, 2, NULL) return? What about 1 IN (1, 2, NULL) and 3 NOT IN (1, 2, NULL)?

1 IN (1, 2, NULL) is TRUE because a match was found. 3 IN (1, 2, NULL) is UNKNOWN (shown as NULL), because 3 might equal the unknown value. 3 NOT IN (1, 2, NULL) is also UNKNOWN, so a WHERE clause using it keeps no rows.

Full answer

x IN (a, b, c) is shorthand for x = a OR x = b OR x = c. With a NULL in the list, one of the comparisons is always UNKNOWN, and the OR rules decide the result:

  • If some other comparison is TRUE, then TRUE OR UNKNOWN is TRUE.
  • If every other comparison is FALSE, then FALSE OR UNKNOWN is UNKNOWN.

NOT IN is the negation: x <> a AND x <> b AND x <> c. One UNKNOWN in an AND chain with no FALSE makes the whole result UNKNOWN.

sql
CREATE TABLE vals (v INTEGER);
INSERT INTO vals VALUES (1), (3);
sql
SELECT 1 IN (1, 2, NULL)     AS one_in,
       3 IN (1, 2, NULL)     AS three_in,
       3 NOT IN (1, 2, NULL) AS three_not_in;
one_inthree_inthree_not_in
1NULLNULL

Applied to a small table, row by row:

sql
SELECT v,
       v IN (1, 2, NULL)     AS in_result,
       v NOT IN (1, 2, NULL) AS not_in_result
FROM vals
ORDER BY v;
vin_resultnot_in_result
110
3NULLNULL

For v = 1, IN is true and NOT IN is false. For v = 3, both are UNKNOWN. In a WHERE clause UNKNOWN behaves like FALSE, so WHERE v NOT IN (1, 2, NULL) would return nothing, not even 3, which is clearly not 1 or 2. This is the same mechanism behind the NOT IN subquery trap, shown here with a literal list so the logic is easier to see.

sql
CREATE TABLE vals (v INTEGER);
INSERT INTO vals VALUES (1), (3);

SELECT 1 IN (1, 2, NULL)     AS one_in,
       3 IN (1, 2, NULL)     AS three_in,
       3 NOT IN (1, 2, NULL) AS three_not_in;

SELECT v,
       v IN (1, 2, NULL)     AS in_result,
       v NOT IN (1, 2, NULL) AS not_in_result
FROM vals
ORDER BY v;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • IN expands to OR of equality checks; NOT IN to AND of inequality checks
  • A NULL in the list makes non-matches UNKNOWN
  • IN still returns TRUE when a real match exists
  • NOT IN with a NULL in the list never returns TRUE

Common mistakes

  • Building an IN list from user input that may contain NULL
  • Reading UNKNOWN as FALSE when the result is used inside NOT

Follow-ups

  • What does NOT (3 IN (1, 2, NULL)) return?
  • How do you write the same filter so NULLs in the list are ignored?

Tips

  • Expand the IN into ORs out loud; it makes the answer easy to defend
44.sql-0044Mediummid

A table has CHECK (marks BETWEEN 0 AND 100). Why is a NULL mark still accepted?

A CHECK constraint rejects a row only when its condition is FALSE. For a NULL mark the condition is UNKNOWN, and UNKNOWN passes. This is the opposite of WHERE, which keeps only TRUE. Add NOT NULL if a value is required.

Full answer

WHERE and CHECK treat UNKNOWN in opposite ways:

  • WHERE keeps a row only if the condition is TRUE.
  • CHECK rejects a row only if the condition is FALSE.

So a CHECK constraint lets UNKNOWN through, and any comparison involving NULL is UNKNOWN.

sql
CREATE TABLE results (student TEXT, marks INTEGER CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results VALUES ('Ana', 88), ('Ben', NULL);
SELECT student, marks FROM results ORDER BY student;
studentmarks
Ana88
BenNULL

The NULL mark was accepted, while 120 is rejected:

sql
INSERT INTO results VALUES ('Chen', 120);  -- error on purpose
text
Error: CHECK constraint failed: marks BETWEEN 0 AND 100

This is the intended design: CHECK validates values that exist, and NOT NULL is the separate tool that says a value must exist. Combine them when both rules apply:

sql
CREATE TABLE results2 (student TEXT, marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results2 VALUES ('Ana', 88);
SELECT COUNT(*) AS accepted FROM results2;
accepted
1
sql
INSERT INTO results2 VALUES ('Ben', NULL);  -- error on purpose
text
Error: NOT NULL constraint failed: results2.marks

The same reasoning applies to multi-column checks such as CHECK (end_date > start_date). A row with no end date passes, which is often correct (the course has not ended yet), but it should be a decision, not an accident.

sql
CREATE TABLE results (student TEXT, marks INTEGER CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results VALUES ('Ana', 88), ('Ben', NULL);
SELECT student, marks FROM results ORDER BY student;

-- error on purpose
INSERT INTO results VALUES ('Chen', 120);

CREATE TABLE results2 (student TEXT, marks INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100));
INSERT INTO results2 VALUES ('Ana', 88);
SELECT COUNT(*) AS accepted FROM results2;

-- error on purpose
INSERT INTO results2 VALUES ('Ben', NULL);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CHECK fails only on FALSE; UNKNOWN passes
  • WHERE keeps only TRUE; the two are opposites
  • Add NOT NULL when a value must be present
  • Multi-column checks also pass when any column is NULL

Common mistakes

  • Relying on CHECK to require a value
  • Writing CHECK (col IS NOT NULL AND ...) everywhere instead of declaring NOT NULL

Follow-ups

  • How would you require end_date to be after start_date only when it is present?
  • Does a FOREIGN KEY accept NULL?

Tips

  • State the WHERE versus CHECK contrast in one sentence
45.sql-0045Mediummid

Should a column allow NULL? How do you decide when designing a table?

Make a column NOT NULL unless a missing value is a real, expected state with a clear meaning. NULL then means one thing, such as 'not known yet' or 'not applicable'. If a column would mean several different things when empty, or every query has to remember to handle it, a default value or a separate table is usually better.

Full answer

Every nullable column adds work for every query that touches it: three-valued logic in filters, special handling in averages and joins, and more cases in application code. So the default should be NOT NULL, and NULL should be allowed on purpose.

Questions to ask for each column:

  1. Can a valid row exist without this value? An order cannot exist without an order date. A batch of students can exist before its end date is known.
  2. If the value is missing, what does that mean? If the answer is "not known yet", NULL fits. If it could mean either "unknown" or "not applicable", the column needs a clearer design.
  3. Is there a natural default? A status column can default to 'planned'. A counter can default to 0. Then NOT NULL DEFAULT is better than NULL.
  4. Is the value really optional data about a different thing? A user's optional company details may belong in a separate table that has a row only when the details exist.

A small table that follows these rules:

sql
CREATE TABLE batches (
  id          INTEGER PRIMARY KEY,
  course      TEXT    NOT NULL,
  start_date  TEXT    NOT NULL,
  end_date    TEXT,                                   -- NULL means still running
  status      TEXT    NOT NULL DEFAULT 'planned',
  seats_taken INTEGER NOT NULL DEFAULT 0 CHECK (seats_taken >= 0),
  CHECK (end_date IS NULL OR end_date >= start_date)
);
SELECT name, "notnull" AS not_null, dflt_value FROM pragma_table_info('batches') ORDER BY cid;
namenot_nulldflt_value
id0NULL
course1NULL
start_date1NULL
end_date0NULL
status1'planned'
seats_taken10

Inserting a row with only the required fields shows the defaults and the deliberate NULL:

sql
INSERT INTO batches (course, start_date) VALUES ('SQL Basics', '2026-04-01');
SELECT id, course, start_date, end_date, status, seats_taken FROM batches;
idcoursestart_dateend_datestatusseats_taken
1SQL Basics2026-04-01NULLplanned0

end_date stays NULL on purpose and means "still running". status and seats_taken get real defaults rather than NULLs that every query would have to translate.

sql
CREATE TABLE batches (
  id          INTEGER PRIMARY KEY,
  course      TEXT    NOT NULL,
  start_date  TEXT    NOT NULL,
  end_date    TEXT,                                   -- NULL means still running
  status      TEXT    NOT NULL DEFAULT 'planned',
  seats_taken INTEGER NOT NULL DEFAULT 0 CHECK (seats_taken >= 0),
  CHECK (end_date IS NULL OR end_date >= start_date)
);
SELECT name, "notnull" AS not_null, dflt_value FROM pragma_table_info('batches') ORDER BY cid;

INSERT INTO batches (course, start_date) VALUES ('SQL Basics', '2026-04-01');
SELECT id, course, start_date, end_date, status, seats_taken FROM batches;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Default to NOT NULL; allow NULL deliberately
  • NULL should have one clear meaning per column
  • Prefer NOT NULL DEFAULT when a natural default exists
  • Optional groups of attributes may belong in a separate table

Common mistakes

  • Leaving every column nullable because the ORM does by default
  • Using NULL to mean both 'unknown' and 'not applicable' in one column

Follow-ups

  • How do you add NOT NULL to a column that already has NULLs?
  • What is the cost of many nullable columns for queries?

Tips

  • Walk through two or three columns of a concrete table instead of answering in the abstract
46.sql-0046Hardsenior

Write a query that returns the larger of two nullable columns per row. What do SQLite's max(a, b) and PostgreSQL's GREATEST(a, b) do with NULL?

SQLite's two-argument max(a, b) returns NULL if any argument is NULL. PostgreSQL's GREATEST(a, b) ignores NULLs and returns NULL only when all arguments are NULL. MySQL's GREATEST returns NULL if any argument is NULL. For portable results, use CASE with explicit NULL checks.

Full answer

Each student sat a test twice, and the report shows the better score. Some students missed one sitting.

On SQLite, the scalar (multi-argument) form of max is used:

sql
CREATE TABLE attempts (student TEXT, first_try INTEGER, second_try INTEGER);
INSERT INTO attempts VALUES ('Ana',70,85),('Ben',90,NULL),('Chen',NULL,60),('Dara',NULL,NULL);
sql
SELECT student, first_try, second_try, max(first_try, second_try) AS best
FROM attempts ORDER BY student;
studentfirst_trysecond_trybest
Ana708585
Ben90NULLNULL
ChenNULL60NULL
DaraNULLNULLNULL

Ben missed the retest and Chen missed the first test. SQLite's max(a, b) returns NULL as soon as any argument is NULL, so both lost their score.

PostgreSQL's GREATEST skips NULLs:

sql
SELECT student, GREATEST(first_try, second_try) AS best
FROM attempts ORDER BY student;
studentbest
Ana85
Ben90
Chen60
DaraNULL

MySQL's GREATEST behaves like SQLite here and returns NULL when any argument is NULL; that comes from MySQL documentation and was not run here.

A version that gives the PostgreSQL behaviour on any engine:

sql
SELECT student,
       CASE
         WHEN first_try  IS NULL THEN second_try
         WHEN second_try IS NULL THEN first_try
         WHEN first_try >= second_try THEN first_try
         ELSE second_try
       END AS best
FROM attempts ORDER BY student;
studentbest
Ana85
Ben90
Chen60
DaraNULL

The CASE checks NULL first, then compares. It returns NULL only when both scores are missing, which is the honest answer for Dara. Using COALESCE(first_try, 0) would also produce numbers, but it would turn "both missing" into a score of 0, which is a different statement.

sql
CREATE TABLE attempts (student TEXT, first_try INTEGER, second_try INTEGER);
INSERT INTO attempts VALUES ('Ana',70,85),('Ben',90,NULL),('Chen',NULL,60),('Dara',NULL,NULL);

SELECT student, first_try, second_try, max(first_try, second_try) AS best
FROM attempts ORDER BY student;

SELECT student,
       CASE
         WHEN first_try  IS NULL THEN second_try
         WHEN second_try IS NULL THEN first_try
         WHEN first_try >= second_try THEN first_try
         ELSE second_try
       END AS best
FROM attempts ORDER BY student;

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

Key points

  • SQLite max(a, b) and MySQL GREATEST return NULL if any argument is NULL
  • PostgreSQL GREATEST ignores NULLs
  • A CASE with explicit IS NULL checks is portable
  • COALESCE with 0 changes 'unknown' into 'zero'

Common mistakes

  • Assuming GREATEST behaves the same on PostgreSQL and MySQL
  • Using COALESCE(x, 0) where 0 is a meaningful value

Follow-ups

  • How does this differ from the aggregate MAX(col)?
  • How would you take the best of three nullable attempts?

Tips

  • Mention that aggregate MAX ignores NULLs while scalar max may not
47.sql-0047Easyfresher

In SQLite, how are TRUE and FALSE represented, and what does WHERE do with a numeric column used as a condition?

SQLite has no separate boolean type. TRUE and FALSE are aliases for 1 and 0, comparisons return 1, 0 or NULL, and WHERE treats any non-zero number as true. PostgreSQL has a real boolean type and rejects WHERE on an integer column without a comparison.

Full answer

SQLite stores booleans as integers. The keywords TRUE and FALSE (accepted since 3.23) are just 1 and 0:

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, is_active INTEGER);
INSERT INTO users VALUES (1,'Ana',1),(2,'Ben',0),(3,'Chen',2),(4,'Dara',NULL);
sql
SELECT TRUE AS t, FALSE AS f, 5 > 3 AS cmp, typeof(TRUE) AS stored_as;
tfcmpstored_as
101integer

A comparison like 5 > 3 returns 1. Any non-zero numeric value counts as true in WHERE, so a column of 0s and 1s can be used directly:

sql
SELECT id, name, is_active FROM users WHERE is_active ORDER BY id;
idnameis_active
1Ana1
3Chen2

The row with is_active = 2 is also returned, since 2 is non-zero, and the NULL row is not. SQLite does not stop you storing 2 or -1 in a "boolean" column. Add CHECK (is_active IN (0, 1)) if only 0 and 1 make sense.

PostgreSQL has a true boolean type. Using an integer column as a condition is an error:

sql
SELECT id FROM users WHERE is_active;  -- error on purpose
text
Error: argument of WHERE must be type boolean, not type integer

In PostgreSQL you would declare is_active boolean, write WHERE is_active, and get true or false back. When code moves from SQLite to PostgreSQL, columns declared BOOLEAN in SQLite but filled with 0 and 1 usually need a migration step.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, is_active INTEGER);
INSERT INTO users VALUES (1,'Ana',1),(2,'Ben',0),(3,'Chen',2),(4,'Dara',NULL);

SELECT TRUE AS t, FALSE AS f, 5 > 3 AS cmp, typeof(TRUE) AS stored_as;

SELECT id, name, is_active FROM users WHERE is_active ORDER BY id;

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

Key points

  • SQLite has no boolean storage class; TRUE is 1 and FALSE is 0
  • Non-zero numbers are true in WHERE
  • Use CHECK (col IN (0, 1)) to keep a flag clean
  • PostgreSQL has a real boolean type and is stricter

Common mistakes

  • Storing values other than 0 and 1 in a flag column
  • Assuming WHERE int_column works on PostgreSQL

Follow-ups

  • How would you count active and inactive users in one query?
  • What does SUM(is_active) give you in SQLite?

Tips

  • Contrast with PostgreSQL in one line
48.sql-0048Easyfresher

How do INNER JOIN and LEFT JOIN results differ? Show it with students and their enrolments.

An INNER JOIN returns only rows that have a match on both sides. A LEFT JOIN returns every row from the left table, and fills the right-side columns with NULL when there is no match. So a student with no enrolments disappears from an inner join but appears once, with NULLs, in a left join.

Full answer

A join combines rows from two tables using a condition, usually "this key equals that key".

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);

With an INNER JOIN, a student appears only if at least one enrolment matches. Dara has none, so she is not in the result:

sql
SELECT s.name, e.course_id, e.marks
FROM students s
INNER JOIN enrolments e ON e.student_id = s.id
ORDER BY s.name, e.course_id;
namecourse_idmarks
Asha1088
Asha2092
Ben1075
Ben30NULL
Chen1064
Chen2071
Chen3080
Eli2055

With a LEFT JOIN, every student appears. Dara's row has NULL in the enrolment columns because nothing matched:

sql
SELECT s.name, e.course_id, e.marks
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
ORDER BY s.name, e.course_id;
namecourse_idmarks
Asha1088
Asha2092
Ben1075
Ben30NULL
Chen1064
Chen2071
Chen3080
DaraNULLNULL
Eli2055

Read the table names as a sentence: "students LEFT JOIN enrolments" means "all students, plus their enrolments if any". The table written first is the one whose rows are all kept.

Notice that Ben's Statistics row also shows marks NULL, but for a different reason: the enrolment exists and the mark is missing. To tell the two cases apart, test a column that can never be NULL in a real match, such as the right table's key: e.course_id IS NULL means "no enrolment at all".

A practical rule: use INNER JOIN when the related row must exist for the result to make sense, and LEFT JOIN when the left rows must all be listed, such as "every student with their marks, if any".

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 s.name, e.course_id, e.marks
FROM students s
INNER JOIN enrolments e ON e.student_id = s.id
ORDER BY s.name, e.course_id;

SELECT s.name, e.course_id, e.marks
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
ORDER BY s.name, e.course_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INNER JOIN keeps only matched rows
  • LEFT JOIN keeps every left row, with NULLs where nothing matched
  • The table written first is the preserved side in a LEFT JOIN
  • Check the right table's key to detect 'no match' rather than a nullable column

Common mistakes

  • Using INNER JOIN for a report that must list every student
  • Confusing a NULL from 'no match' with a NULL stored in the right table

Follow-ups

  • How do you find students who have no enrolments?
  • What happens if you add WHERE e.marks > 50 to the LEFT JOIN?

Tips

  • Name one row that appears in one result but not the other; it proves you read the data
49.sql-0049Easyfresher

Explain INNER, LEFT, RIGHT, FULL OUTER and CROSS JOIN using two small tables.

INNER keeps matches only. LEFT keeps all left rows, RIGHT keeps all right rows, and FULL OUTER keeps all rows from both sides, with NULLs where there is no partner. CROSS JOIN pairs every left row with every right row and has no join condition. SQLite has supported RIGHT and FULL OUTER JOIN since 3.39.

Full answer

Two tiny tables make the differences easy to see. left_t has keys 1, 2, 3 and right_t has keys 2, 3, 4:

sql
CREATE TABLE left_t (k INTEGER, l TEXT);
CREATE TABLE right_t (k INTEGER, r TEXT);
INSERT INTO left_t VALUES (1,'L1'),(2,'L2'),(3,'L3');
INSERT INTO right_t VALUES (2,'R2'),(3,'R3'),(4,'R4');

INNER JOIN: only keys present in both.

sql
SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l INNER JOIN right_t r ON r.k = l.k ORDER BY l.k;
lklrkr
2L22R2
3L33R3

LEFT JOIN: all left rows; key 1 has no partner.

sql
SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l LEFT JOIN right_t r ON r.k = l.k ORDER BY l.k;
lklrkr
1L1NULLNULL
2L22R2
3L33R3

RIGHT JOIN: all right rows; key 4 has no partner. Any RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the tables, and many teams do that so every query reads the same way.

sql
SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l RIGHT JOIN right_t r ON r.k = l.k ORDER BY r.k;
lklrkr
2L22R2
3L33R3
NULLNULL4R4

FULL OUTER JOIN: every row from both sides, matched where possible.

sql
SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l FULL OUTER JOIN right_t r ON r.k = l.k ORDER BY COALESCE(l.k, r.k);
lklrkr
1L1NULLNULL
2L22R2
3L33R3
NULLNULL4R4

CROSS JOIN: every combination, 3 x 3 = 9 rows. There is no ON clause.

sql
SELECT l.l, r.r FROM left_t l CROSS JOIN right_t r ORDER BY l.l, r.r;
lr
L1R2
L1R3
L1R4
L2R2
L2R3
L2R4
L3R2
L3R3
L3R4

SQLite added RIGHT and FULL OUTER JOIN in version 3.39 (2022). On older SQLite, and on MySQL, which still lacks FULL OUTER JOIN, the usual workaround is a LEFT JOIN combined with the unmatched rows of the reverse join using UNION ALL.

sql
CREATE TABLE left_t (k INTEGER, l TEXT);
CREATE TABLE right_t (k INTEGER, r TEXT);
INSERT INTO left_t VALUES (1,'L1'),(2,'L2'),(3,'L3');
INSERT INTO right_t VALUES (2,'R2'),(3,'R3'),(4,'R4');

SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l INNER JOIN right_t r ON r.k = l.k ORDER BY l.k;

SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l LEFT JOIN right_t r ON r.k = l.k ORDER BY l.k;

SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l RIGHT JOIN right_t r ON r.k = l.k ORDER BY r.k;

SELECT l.k AS lk, l.l, r.k AS rk, r.r FROM left_t l FULL OUTER JOIN right_t r ON r.k = l.k ORDER BY COALESCE(l.k, r.k);

SELECT l.l, r.r FROM left_t l CROSS JOIN right_t r ORDER BY l.l, r.r;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • INNER: matches only
  • LEFT or RIGHT: keep every row of one side
  • FULL OUTER: keep every row of both sides
  • CROSS: every combination, no condition
  • SQLite 3.39+ has RIGHT and FULL; MySQL has no FULL OUTER JOIN

Common mistakes

  • Drawing joins as Venn diagrams and then being surprised by duplicate rows from repeated keys
  • Forgetting that CROSS JOIN row counts multiply

Follow-ups

  • How would you emulate FULL OUTER JOIN on MySQL?
  • When is a CROSS JOIN actually useful?

Tips

  • Use tiny tables with an overlap; it explains every type at once
50.sql-0050Mediummid

A LEFT JOIN report of every student and their Databases mark drops students who never took Databases. The filter is in the WHERE clause. Why, and how do you fix it?

WHERE runs after the join. For students without a Databases enrolment, the right-side columns are NULL, so a WHERE condition on them is UNKNOWN and the rows are removed, which turns the LEFT JOIN into an inner join. Move the condition on the right table into the ON clause so it limits which rows can match, not which left rows survive.

Full answer

The goal is a list of all students with their Databases mark, blank if they never took it.

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);

The first attempt puts the course filter in WHERE:

sql
SELECT s.name, e.marks AS databases_mark
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE e.course_id = 10
ORDER BY s.name;
namedatabases_mark
Asha88
Ben75
Chen64

Dara and Eli are missing. Here is what happened, step by step:

  1. The LEFT JOIN produced every enrolment for every student, plus a NULL row for Dara.
  2. WHERE then kept only rows with course_id = 10. Eli's only row has course_id = 20, and Dara's has NULL. Both fail, so both students vanish.

The fix is to make the course part of the matching rule:

sql
SELECT s.name, e.marks AS databases_mark
FROM students s
LEFT JOIN enrolments e
       ON e.student_id = s.id
      AND e.course_id  = 10
ORDER BY s.name;
namedatabases_mark
Asha88
Ben75
Chen64
DaraNULL
EliNULL

Now the join looks only for Databases enrolments. Students without one still appear, with NULL marks.

The rule to remember: in a LEFT JOIN, conditions on the right table belong in ON if you want to keep every left row. Conditions on the left table usually belong in WHERE. A condition such as WHERE e.course_id IS NULL is the exception that is meant to be in WHERE, because it deliberately keeps only the unmatched rows.

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 s.name, e.marks AS databases_mark
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE e.course_id = 10
ORDER BY s.name;

SELECT s.name, e.marks AS databases_mark
FROM students s
LEFT JOIN enrolments e
       ON e.student_id = s.id
      AND e.course_id  = 10
ORDER BY s.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • WHERE is applied after the join
  • A WHERE condition on right-side columns removes the NULL rows a LEFT JOIN added
  • Put right-table filters in ON to keep all left rows
  • WHERE right.key IS NULL is the intended anti-join exception

Common mistakes

  • Filtering the right table in WHERE and silently getting an inner join
  • Moving left-table filters into ON, which does not remove left rows

Follow-ups

  • What happens if you put a condition on the left table into the ON clause of a LEFT JOIN?
  • How would you list students who did not take Databases?

Tips

  • Walk through the rows before and after WHERE; it makes the cause obvious
51.sql-0051Hardsenior

In a LEFT JOIN, what happens if you put a condition on the left table in the ON clause, for example ON e.student_id = s.id AND s.city = 'Pune'?

Left rows are never removed by the ON clause of a LEFT JOIN. A false left-side condition only means those rows find no match, so they appear with NULLs on the right. Students outside Pune are still listed, just without enrolments. To restrict the left table, the condition must go in WHERE.

Full answer

This is the mirror image of the more common WHERE-versus-ON bug, and it confuses people who expect the condition to filter.

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 s.name, s.city, e.course_id
FROM students s
LEFT JOIN enrolments e
       ON e.student_id = s.id
      AND s.city = 'Pune'
ORDER BY s.name, e.course_id;
namecitycourse_id
AshaPune10
AshaPune20
BenLeedsNULL
ChenPune10
ChenPune20
ChenPune30
DaraNULLNULL
EliLeedsNULL

Every student is still there. Ben, Dara and Eli are not from Pune, so for them the ON condition is false for every enrolment. A LEFT JOIN promises to return each left row at least once, so they come back with NULLs, as if they had no enrolments. That is misleading: Ben and Eli do have enrolments.

If the intent was "Pune students with their enrolments", the city filter belongs in WHERE:

sql
SELECT s.name, s.city, e.course_id
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE s.city = 'Pune'
ORDER BY s.name, e.course_id;
namecitycourse_id
AshaPune10
AshaPune20
ChenPune10
ChenPune20
ChenPune30

For an INNER JOIN the placement does not change the result, because a failed condition removes the row either way. The difference exists only for outer joins, which is why it is worth checking every outer join for conditions in the wrong clause.

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 s.name, s.city, e.course_id
FROM students s
LEFT JOIN enrolments e
       ON e.student_id = s.id
      AND s.city = 'Pune'
ORDER BY s.name, e.course_id;

SELECT s.name, s.city, e.course_id
FROM students s
LEFT JOIN enrolments e ON e.student_id = s.id
WHERE s.city = 'Pune'
ORDER BY s.name, e.course_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ON in a LEFT JOIN controls matching, never removal of left rows
  • A false left-side condition in ON produces NULL-filled rows
  • Filters on the preserved table belong in WHERE
  • For INNER JOIN, ON and WHERE placement give the same result

Common mistakes

  • Putting a left-table filter in ON and getting rows that look like 'no enrolments'
  • Assuming ON and WHERE are interchangeable for outer joins

Follow-ups

  • Write the query for 'all students, with only their Pune-campus enrolments'.
  • Does the optimizer treat ON and WHERE differently for inner joins?

Tips

  • Point at Ben: he has enrolments, but the result shows none
52.sql-0052Mediummid

Write a query to find employees who earn more than their own manager.

Join the employees table to itself: one copy for the employee (e) and one for the manager (m), matched on e.manager_id = m.id. Then compare e.salary > m.salary. Employees with no manager drop out of the inner join, which is correct here because they have no manager to compare against.

Full answer

A self join treats one table as two. Each copy gets its own alias, and the join condition links a row to another row in the same 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');

The data already has an interesting case. Sara reports to Tom, and Omar reports to Diego. Let's see who out-earns their manager:

sql
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.name;
employeesalarymanagermanager_salary

(0 rows)

Nobody does, with the original salaries. Give Omar a raise and run it again:

sql
UPDATE employees SET salary = 60000 WHERE name = 'Omar';
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.name;
employeesalarymanagermanager_salary
Omar60000Diego55000

How the query works:

  • employees e is "the person", employees m is "their manager".
  • ON m.id = e.manager_id pairs each person with the row of their manager.
  • WHERE e.salary > m.salary keeps the pairs where the person earns more.

Asha has no manager, so the inner join finds no partner for her and she is excluded, which is what the question wants. Lena's salary is NULL, so her comparison is UNKNOWN and she is excluded too. If the question were "employees with no manager or earning more than their manager", you would switch to a LEFT JOIN and add OR m.id IS NULL.

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, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.name;

UPDATE employees SET salary = 60000 WHERE name = 'Omar';
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A self join uses two aliases for the same table
  • Join on employee.manager_id = manager.id
  • Inner join drops people without a manager
  • NULL salaries make the comparison UNKNOWN and drop the row

Common mistakes

  • Using one alias and comparing a row with itself
  • Reversing the join condition and comparing managers with their reports the wrong way round

Follow-ups

  • How would you list each manager with the number of direct reports?
  • How would you find the full chain of managers above an employee?

Tips

  • Say which alias plays which role before writing the condition
53.sql-0053Mediummid

List every pair of students who live in the same city, with each pair shown only once.

Self join students on a.city = b.city and add a.id < b.id. The inequality removes pairs of a student with themselves and keeps only one of the two orderings (Asha-Chen but not Chen-Asha). Students with a NULL city never pair, because NULL = NULL is not true.

Full answer

A self join on city alone produces too much:

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 a.name AS a, b.name AS b, a.city
FROM students a
JOIN students b ON a.city = b.city
ORDER BY a.city, a.name, b.name;
abcity
BenBenLeeds
BenEliLeeds
EliBenLeeds
EliEliLeeds
AshaAshaPune
AshaChenPune
ChenAshaPune
ChenChenPune

Each student is paired with themselves, and each real pair appears twice in both orders. Using a.id <> b.id would remove the self-pairs but keep both orders. Using a.id < b.id keeps exactly one ordering of each pair:

sql
SELECT a.name AS a, b.name AS b, a.city
FROM students a
JOIN students b ON a.city = b.city AND a.id < b.id
ORDER BY a.city, a.name;
abcity
BenEliLeeds
AshaChenPune

Dara has a NULL city, so a.city = b.city is never true for her, and she pairs with nobody. That is usually right: an unknown city should not count as the same city.

This pattern, a self join with < on the key, is the general tool for "all unique pairs" problems: roommates, matches between teams, or duplicate candidates that need a human check. For n rows in one group it produces n(n-1)/2 pairs, so on a large group it grows quickly.

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 a.name AS a, b.name AS b, a.city
FROM students a
JOIN students b ON a.city = b.city
ORDER BY a.city, a.name, b.name;

SELECT a.name AS a, b.name AS b, a.city
FROM students a
JOIN students b ON a.city = b.city AND a.id < b.id
ORDER BY a.city, a.name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Self join on the shared attribute
  • a.id < b.id removes self-pairs and mirrored duplicates
  • NULL values never pair with =
  • Pair count grows as n(n-1)/2 per group

Common mistakes

  • Using <> and getting every pair twice
  • Forgetting the inequality and pairing rows with themselves

Follow-ups

  • How would you count the pairs per city without listing them?
  • How would you find pairs of students who share at least two courses?

Tips

  • Show the row count before and after adding a.id < b.id
54.sql-0054Easyfresher

When is a CROSS JOIN useful? Give a practical example.

A CROSS JOIN returns every combination of rows from two tables. It is useful when you deliberately need all combinations, such as every size with every colour for a product catalogue, or every student with every course to build an attendance grid that a LEFT JOIN then fills in. Without that intent, it is usually a bug.

Full answer

A CROSS JOIN has no condition. Every row on the left is paired with every row on the right, so 3 sizes and 2 colours give 6 rows:

sql
WITH sizes(size) AS (VALUES ('S'), ('M'), ('L')),
     colours(colour) AS (VALUES ('Red'), ('Blue'))
SELECT size, colour
FROM sizes CROSS JOIN colours
ORDER BY size, colour;
sizecolour
LBlue
LRed
MBlue
MRed
SBlue
SRed

The more interesting use is as a scaffold. Suppose a report must show every student against every course, with the mark if it exists and a blank otherwise. Start from all combinations, then LEFT JOIN the real data onto 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);
sql
SELECT s.name, c.title, e.marks
FROM students s
CROSS JOIN courses c
LEFT JOIN enrolments e ON e.student_id = s.id AND e.course_id = c.id
WHERE s.id IN (1, 4)
ORDER BY s.name, c.title;
nametitlemarks
AshaAlgorithms92
AshaDatabases88
AshaEthicsNULL
AshaStatisticsNULL
DaraAlgorithmsNULL
DaraDatabasesNULL
DaraEthicsNULL
DaraStatisticsNULL

The CROSS JOIN produces 5 x 4 = 20 student-course combinations (the WHERE keeps two students so the output stays short), and the LEFT JOIN fills in marks where an enrolment exists. Dara gets a full row of blanks, which is exactly what an attendance grid needs to show. The same technique fills gaps in time series: cross join every store with every date in a calendar table, then left join the sales.

The danger is size. Two tables of 10,000 rows each give 100,000,000 combinations. An accidental cross join, often from an old-style comma join with a missing WHERE condition, is a classic way to overload a database.

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);

WITH sizes(size) AS (VALUES ('S'), ('M'), ('L')),
     colours(colour) AS (VALUES ('Red'), ('Blue'))
SELECT size, colour
FROM sizes CROSS JOIN colours
ORDER BY size, colour;

SELECT s.name, c.title, e.marks
FROM students s
CROSS JOIN courses c
LEFT JOIN enrolments e ON e.student_id = s.id AND e.course_id = c.id
WHERE s.id IN (1, 4)
ORDER BY s.name, c.title;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • CROSS JOIN returns every combination: rows multiply
  • Useful for building complete grids, then LEFT JOIN the facts
  • Calendar x entity is the standard gap-filling pattern
  • An accidental cross join can explode the row count

Common mistakes

  • Writing FROM a, b and forgetting the join condition
  • Cross joining two large tables without a filter

Follow-ups

  • How would you produce a row for every day in March even when there were no sales?
  • How can you spot an accidental cross join in a query plan?

Tips

  • Give the scaffold-then-LEFT JOIN example; it shows a real reason to use it
55.sql-0055Hardsenior

Revenue per customer looks too high after joining orders to both order items and payments. What is going on?

Joining a parent to two independent child tables multiplies rows: an order with 2 items and 2 payments becomes 4 joined rows, so every item and every payment is counted twice. Aggregate each child table separately (in subqueries or CTEs) down to one row per order, then join the results.

Full answer

This bug is often called fan-out, and it produces numbers that look plausible.

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);

CREATE TABLE payments (order_id INTEGER, amount INTEGER);
INSERT INTO payments VALUES (101, 8), (101, 5), (102, 30);

Order 101 has two items and was paid in two instalments. Joining both child tables in one go:

sql
SELECT o.id,
       SUM(i.qty * i.unit_price) AS items_total,
       SUM(p.amount)             AS paid
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN payments    p ON p.order_id = o.id
GROUP BY o.id
ORDER BY o.id;
iditems_totalpaid
1012626
1023030

The true item total for order 101 is 2 x 4 + 5 x 1 = 13, and the true amount paid is 13. The query reports 26 for both. Each of the 2 item rows matched each of the 2 payment rows, giving 4 rows, and SUM added every value twice. Order 102 has one item and one payment, so it is correct, which is why the bug can hide in small test data.

Count the joined rows to see it:

sql
SELECT o.id, COUNT(*) AS joined_rows
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN payments    p ON p.order_id = o.id
GROUP BY o.id
ORDER BY o.id;
idjoined_rows
1014
1021

The fix is to reduce each child table to one row per order before joining:

sql
WITH items AS (
  SELECT order_id, SUM(qty * unit_price) AS items_total
  FROM order_items GROUP BY order_id
), paid AS (
  SELECT order_id, SUM(amount) AS paid
  FROM payments GROUP BY order_id
)
SELECT o.id, i.items_total, p.paid
FROM orders o
JOIN items i ON i.order_id = o.id
JOIN paid  p ON p.order_id = o.id
ORDER BY o.id;
iditems_totalpaid
1011313
1023030

Rules of thumb: when you join a table to two or more one-to-many children and then aggregate, pre-aggregate the children. SUM(DISTINCT ...) is not a fix, because two different items can have the same value and would be merged.

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);

CREATE TABLE payments (order_id INTEGER, amount INTEGER);
INSERT INTO payments VALUES (101, 8), (101, 5), (102, 30);

SELECT o.id,
       SUM(i.qty * i.unit_price) AS items_total,
       SUM(p.amount)             AS paid
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN payments    p ON p.order_id = o.id
GROUP BY o.id
ORDER BY o.id;

SELECT o.id, COUNT(*) AS joined_rows
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN payments    p ON p.order_id = o.id
GROUP BY o.id
ORDER BY o.id;

WITH items AS (
  SELECT order_id, SUM(qty * unit_price) AS items_total
  FROM order_items GROUP BY order_id
), paid AS (
  SELECT order_id, SUM(amount) AS paid
  FROM payments GROUP BY order_id
)
SELECT o.id, i.items_total, p.paid
FROM orders o
JOIN items i ON i.order_id = o.id
JOIN paid  p ON p.order_id = o.id
ORDER BY o.id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Joining two independent child tables multiplies rows
  • Sums and counts are inflated by the multiplication
  • Pre-aggregate each child to one row per parent, then join
  • SUM(DISTINCT) is not a safe fix

Common mistakes

  • Testing with orders that have one item and one payment, where the bug cannot appear
  • Reaching for DISTINCT to hide the duplication

Follow-ups

  • How would you detect fan-out in an existing report?
  • Does the same problem happen with COUNT(*)?

Tips

  • Show the row count per order; it makes the multiplication visible
56.sql-0056Mediummid

How do you reconcile two lists, such as students registered in the portal and students on the exam sheet, to find who is missing from each?

A FULL OUTER JOIN on the shared key keeps rows from both lists. Rows with NULL on the right are only in the first list, rows with NULL on the left are only in the second, and rows with both sides are in both. On engines without FULL OUTER JOIN, combine a LEFT JOIN with the unmatched rows of the reverse LEFT JOIN using UNION ALL.

Full answer

Reconciliation means comparing two sources and labelling each key as matched, only in A, or only in B.

sql
CREATE TABLE portal (roll INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE exam_sheet (roll INTEGER PRIMARY KEY, name TEXT);
INSERT INTO portal VALUES (1,'Asha'),(2,'Ben'),(3,'Chen');
INSERT INTO exam_sheet VALUES (3,'Chen'),(5,'Eli');
sql
SELECT COALESCE(p.roll, x.roll) AS roll,
       CASE WHEN x.roll IS NULL THEN 'portal only'
            WHEN p.roll IS NULL THEN 'exam sheet only'
            ELSE 'both' END AS status
FROM portal p
FULL OUTER JOIN exam_sheet x ON x.roll = p.roll
ORDER BY roll;
rollstatus
1portal only
2portal only
3both
5exam sheet only

The CASE expression labels each row by which side is NULL. Roll 3 is in both lists, roll 1 and 2 are only in the portal, and roll 5 is only on the exam sheet.

On MySQL, which has no FULL OUTER JOIN, or on SQLite before 3.39, the same result comes from two LEFT JOINs:

sql
SELECT p.roll, CASE WHEN x.roll IS NULL THEN 'portal only' ELSE 'both' END AS status
FROM portal p LEFT JOIN exam_sheet x ON x.roll = p.roll
UNION ALL
SELECT x.roll, 'exam sheet only'
FROM exam_sheet x LEFT JOIN portal p ON p.roll = x.roll
WHERE p.roll IS NULL
ORDER BY 1;
rollstatus
1portal only
2portal only
3both
5exam sheet only

The second half keeps only exam rows with no portal match, so matched rows are not repeated. UNION ALL is used instead of UNION because the two halves cannot overlap, and UNION would add an unnecessary duplicate-removal step.

Two details matter in real reconciliations. Normalise the key first (trim spaces, consistent case, same data type), or genuine matches will show up as "missing from both". And compare values as well as keys: p.name IS DISTINCT FROM x.name finds rows present in both lists whose details disagree.

sql
CREATE TABLE portal (roll INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE exam_sheet (roll INTEGER PRIMARY KEY, name TEXT);
INSERT INTO portal VALUES (1,'Asha'),(2,'Ben'),(3,'Chen');
INSERT INTO exam_sheet VALUES (3,'Chen'),(5,'Eli');

SELECT COALESCE(p.roll, x.roll) AS roll,
       CASE WHEN x.roll IS NULL THEN 'portal only'
            WHEN p.roll IS NULL THEN 'exam sheet only'
            ELSE 'both' END AS status
FROM portal p
FULL OUTER JOIN exam_sheet x ON x.roll = p.roll
ORDER BY roll;

SELECT p.roll, CASE WHEN x.roll IS NULL THEN 'portal only' ELSE 'both' END AS status
FROM portal p LEFT JOIN exam_sheet x ON x.roll = p.roll
UNION ALL
SELECT x.roll, 'exam sheet only'
FROM exam_sheet x LEFT JOIN portal p ON p.roll = x.roll
WHERE p.roll IS NULL
ORDER BY 1;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • FULL OUTER JOIN keeps every key from both sides
  • Which side is NULL tells you where the key is missing
  • LEFT JOIN UNION ALL anti-join emulates FULL OUTER JOIN
  • Normalise keys before comparing

Common mistakes

  • Using UNION instead of UNION ALL in the emulation and paying for a needless sort
  • Testing a nullable non-key column to decide which side is missing

Follow-ups

  • How would you also flag rows whose names differ between the two lists?
  • Why is UNION ALL safe in the emulation?

Tips

  • Show the label column; it turns the join into a readable report
57.sql-0057Mediummid

Write a query that assigns a grade to each mark using a grade-band table with min and max marks.

Join marks to the band table with a range condition instead of equality: ON e.marks BETWEEN g.min_mark AND g.max_mark. This is a non-equi join. Make sure the bands do not overlap or leave gaps, or a mark can match two grades or none; a LEFT JOIN exposes marks that fall into no band.

Full answer

Most joins compare keys with =. A non-equi join uses any other condition, such as a range. Grade bands are the classic case, because a mark belongs to the band whose range contains it.

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);

CREATE TABLE grade_bands (grade TEXT PRIMARY KEY, min_mark INTEGER, max_mark INTEGER);
INSERT INTO grade_bands VALUES ('A',85,100),('B',70,84),('C',50,69),('F',0,49);
sql
SELECT s.name, e.course_id, e.marks, g.grade
FROM enrolments e
JOIN students s ON s.id = e.student_id
LEFT JOIN grade_bands g ON e.marks BETWEEN g.min_mark AND g.max_mark
ORDER BY s.name, e.course_id;
namecourse_idmarksgrade
Asha1088A
Asha2092A
Ben1075B
Ben30NULLNULL
Chen1064C
Chen2071B
Chen3080B
Eli2055C

The LEFT JOIN keeps Ben's Statistics enrolment, whose mark is NULL; it matches no band and shows a NULL grade instead of disappearing.

Range joins depend on clean bands. If two bands overlapped (say B was 60 to 80 and A was 80 to 100), a mark of 80 would match both and the enrolment would appear twice. If bands had a gap, some marks would match nothing. A quick check for overlaps is itself a self join on the band table:

sql
SELECT a.grade, b.grade AS overlaps_with
FROM grade_bands a
JOIN grade_bands b
  ON a.grade < b.grade
 AND a.min_mark <= b.max_mark
 AND b.min_mark <= a.max_mark;
gradeoverlaps_with

(0 rows)

No rows means no overlaps. For an exclusive upper bound (common with decimal marks such as 79.5), store bands as half-open ranges and join with marks >= min_mark AND marks < next_min.

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);

CREATE TABLE grade_bands (grade TEXT PRIMARY KEY, min_mark INTEGER, max_mark INTEGER);
INSERT INTO grade_bands VALUES ('A',85,100),('B',70,84),('C',50,69),('F',0,49);

SELECT s.name, e.course_id, e.marks, g.grade
FROM enrolments e
JOIN students s ON s.id = e.student_id
LEFT JOIN grade_bands g ON e.marks BETWEEN g.min_mark AND g.max_mark
ORDER BY s.name, e.course_id;

SELECT a.grade, b.grade AS overlaps_with
FROM grade_bands a
JOIN grade_bands b
  ON a.grade < b.grade
 AND a.min_mark <= b.max_mark
 AND b.min_mark <= a.max_mark;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A non-equi join matches on a range or other condition
  • BETWEEN joins assign each value to its band
  • Overlapping bands duplicate rows; gaps drop them
  • A self join on the band table can check for overlaps

Common mistakes

  • Hard-coding grade logic in a long CASE that drifts from the official table
  • Using inclusive bounds with decimal values and leaving gaps such as 79.5

Follow-ups

  • How would you count students per grade?
  • How would you handle decimal marks without gaps?

Tips

  • Mention the overlap check; it shows you think about data quality
58.sql-0058Easyfresher

What does a join return when the key column is NULL on one or both sides?

A NULL key never matches anything, not even another NULL, because NULL = NULL is UNKNOWN. In an inner join those rows disappear; in a LEFT JOIN the left row stays with NULLs on the right. If two NULLs should match, which is rare, the condition must say so with IS NOT DISTINCT FROM.

Full answer

Join conditions are ordinary comparisons, so NULL follows the same three-valued logic as in WHERE.

sql
WITH a(k, v) AS (VALUES (1, 'a1'), (NULL, 'a-null')),
     b(k, w) AS (VALUES (1, 'b1'), (NULL, 'b-null'))
SELECT a.v, b.w FROM a JOIN b ON a.k = b.k ORDER BY a.v;
vw
a1b1

Only the key 1 rows matched. The NULL on the left did not match the NULL on the right.

A LEFT JOIN keeps the unmatched left rows, including the one with a NULL key:

sql
WITH a(k, v) AS (VALUES (1, 'a1'), (NULL, 'a-null')),
     b(k, w) AS (VALUES (1, 'b1'), (NULL, 'b-null'))
SELECT a.v, b.w FROM a LEFT JOIN b ON a.k = b.k ORDER BY a.v;
vw
a-nullNULL
a1b1

The orders table in the shop schema shows the business version. Guest order 106 has no customer, so it disappears from an inner join with customers:

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 COUNT(*) AS orders_in_inner_join,
       (SELECT COUNT(*) FROM orders) AS all_orders
FROM orders o
JOIN customers c ON c.id = o.customer_id;
orders_in_inner_joinall_orders
56

Five of six orders appear. A revenue report built on that inner join would quietly leave out guest orders. Starting from orders with a LEFT JOIN keeps them.

When NULL keys should match (for example, comparing two snapshots where "no region" in both counts as the same), use ON a.k IS NOT DISTINCT FROM b.k. Expect it to be slower on large tables, since it may not use an index the way = does.

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);

WITH a(k, v) AS (VALUES (1, 'a1'), (NULL, 'a-null')),
     b(k, w) AS (VALUES (1, 'b1'), (NULL, 'b-null'))
SELECT a.v, b.w FROM a JOIN b ON a.k = b.k ORDER BY a.v;

WITH a(k, v) AS (VALUES (1, 'a1'), (NULL, 'a-null')),
     b(k, w) AS (VALUES (1, 'b1'), (NULL, 'b-null'))
SELECT a.v, b.w FROM a LEFT JOIN b ON a.k = b.k ORDER BY a.v;

SELECT COUNT(*) AS orders_in_inner_join,
       (SELECT COUNT(*) FROM orders) AS all_orders
FROM orders o
JOIN customers c ON c.id = o.customer_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • NULL keys never match with =
  • Inner joins drop rows with NULL keys
  • LEFT JOIN keeps them with NULLs on the other side
  • IS NOT DISTINCT FROM makes NULLs match when that is truly wanted

Common mistakes

  • Losing guest or unassigned rows in an inner join report
  • Expecting NULL keys on both sides to join

Follow-ups

  • How would you count orders with no customer?
  • Should foreign key columns allow NULL?

Tips

  • Tie it back to a report that silently loses rows
59.sql-0059Easyfresher

Both tables have the key 'Pen' twice. How many rows does the join return, and why?

A join pairs every matching row on the left with every matching row on the right. Two 'Pen' rows on each side give 2 x 2 = 4 joined rows for that key. This is expected behaviour, not a bug, but it explains many inflated counts when a lookup table that was assumed unique has duplicates.

Full answer

A join is not a lookup that stops at the first match. For each left row it returns one output row per matching right row.

sql
WITH prices(product, price) AS (VALUES ('Pen', 1), ('Pen', 2), ('Bag', 30)),
     stock(product, shelf)  AS (VALUES ('Pen', 'A1'), ('Pen', 'B4'), ('Bag', 'C2'))
SELECT p.product, p.price, s.shelf
FROM prices p JOIN stock s ON s.product = p.product
ORDER BY p.product, p.price, s.shelf;
productpriceshelf
Bag30C2
Pen1A1
Pen1B4
Pen2A1
Pen2B4

Count it: 2 Pen rows in the price list times 2 Pen rows in the stock table gives 4 rows for Pen, plus 1 x 1 for Bag.

A frequent real cause is a lookup table that someone assumed was unique. Here a price list accidentally holds two current prices for Pen, and every Pen sale is doubled when joined:

sql
CREATE TABLE price_list (product TEXT, price INTEGER);
INSERT INTO price_list VALUES ('Pen', 1), ('Pen', 1), ('Bag', 30);
CREATE TABLE sales (product TEXT, qty INTEGER);
INSERT INTO sales VALUES ('Pen', 10), ('Bag', 1);
SELECT SUM(s.qty * p.price) AS revenue
FROM sales s JOIN price_list p ON p.product = s.product;
revenue
50

The right answer is 10 x 1 + 1 x 30 = 40, but the duplicate Pen price row doubled the pen revenue. Finding the culprit:

sql
SELECT product, COUNT(*) AS copies
FROM price_list
GROUP BY product
HAVING COUNT(*) > 1;
productcopies
Pen2

The protection is a constraint, not a DISTINCT in the report: make the lookup key a PRIMARY KEY or UNIQUE so the duplicate can never be inserted. To find existing duplicates, group by the key and keep groups with COUNT(*) > 1.

sql
WITH prices(product, price) AS (VALUES ('Pen', 1), ('Pen', 2), ('Bag', 30)),
     stock(product, shelf)  AS (VALUES ('Pen', 'A1'), ('Pen', 'B4'), ('Bag', 'C2'))
SELECT p.product, p.price, s.shelf
FROM prices p JOIN stock s ON s.product = p.product
ORDER BY p.product, p.price, s.shelf;

CREATE TABLE price_list (product TEXT, price INTEGER);
INSERT INTO price_list VALUES ('Pen', 1), ('Pen', 1), ('Bag', 30);
CREATE TABLE sales (product TEXT, qty INTEGER);
INSERT INTO sales VALUES ('Pen', 10), ('Bag', 1);
SELECT SUM(s.qty * p.price) AS revenue
FROM sales s JOIN price_list p ON p.product = s.product;

SELECT product, COUNT(*) AS copies
FROM price_list
GROUP BY product
HAVING COUNT(*) > 1;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Each left row pairs with every matching right row
  • Duplicate keys on both sides multiply: m x n rows per key
  • Duplicate keys in a lookup table inflate totals
  • Enforce uniqueness with a constraint instead of DISTINCT

Common mistakes

  • Assuming a join returns one match per left row
  • Hiding duplicated rows with DISTINCT rather than fixing the data

Follow-ups

  • How do you find duplicate keys in the price list?
  • How would you pick only the latest price when several exist?

Tips

  • Say the m x n rule before showing the result
60.sql-0060Mediummid

How do JOIN ... USING, JOIN ... ON and NATURAL JOIN behave? Why do many teams avoid NATURAL JOIN?

ON takes any condition. USING (col) is shorthand for equality on columns with the same name in both tables, and it outputs that column once. NATURAL JOIN joins on every column name the two tables share, chosen automatically. That is risky: adding an unrelated column with a common name, such as created_at, silently changes the join condition.

Full answer

Three ways to say "match on the key":

sql
CREATE TABLE dept (dept_id INTEGER, dept_name TEXT);
CREATE TABLE staff (staff_name TEXT, dept_id INTEGER);
INSERT INTO dept VALUES (1,'Library'),(2,'Canteen');
INSERT INTO staff VALUES ('Ira',1),('Jon',2),('Kim',1);

ON is the general form. Any condition works, and both key columns stay available with their table prefixes:

sql
SELECT s.staff_name, d.dept_name
FROM staff s JOIN dept d ON d.dept_id = s.dept_id
ORDER BY s.staff_name;
staff_namedept_name
IraLibrary
JonCanteen
KimLibrary

USING (id) requires a column with the same name in both tables, compares them with =, and returns it once without a prefix. It reads nicely when keys share names, which these tables do not, so here is a tiny pair that does:

sql
SELECT dept_id, staff_name, dept_name
FROM staff JOIN dept USING (dept_id)
ORDER BY staff_name;
dept_idstaff_namedept_name
1IraLibrary
2JonCanteen
1KimLibrary

NATURAL JOIN goes further and joins on every column name the tables have in common:

sql
SELECT staff_name, dept_name FROM staff NATURAL JOIN dept ORDER BY staff_name;
staff_namedept_name
IraLibrary
JonCanteen
KimLibrary

It works today. Then someone adds an updated_on column to both tables for auditing:

sql
ALTER TABLE dept  ADD COLUMN updated_on TEXT DEFAULT '2026-01-01';
ALTER TABLE staff ADD COLUMN updated_on TEXT DEFAULT '2026-02-15';
SELECT staff_name, dept_name FROM staff NATURAL JOIN dept ORDER BY staff_name;
staff_namedept_name

(0 rows)

The same NATURAL JOIN now also requires updated_on to match, and the rows vanish without any error. The query text never changed. That is why style guides often ban NATURAL JOIN in application code. USING is generally considered safe, because the join columns are written down.

sql
CREATE TABLE dept (dept_id INTEGER, dept_name TEXT);
CREATE TABLE staff (staff_name TEXT, dept_id INTEGER);
INSERT INTO dept VALUES (1,'Library'),(2,'Canteen');
INSERT INTO staff VALUES ('Ira',1),('Jon',2),('Kim',1);

SELECT s.staff_name, d.dept_name
FROM staff s JOIN dept d ON d.dept_id = s.dept_id
ORDER BY s.staff_name;

SELECT dept_id, staff_name, dept_name
FROM staff JOIN dept USING (dept_id)
ORDER BY staff_name;

SELECT staff_name, dept_name FROM staff NATURAL JOIN dept ORDER BY staff_name;

ALTER TABLE dept  ADD COLUMN updated_on TEXT DEFAULT '2026-01-01';
ALTER TABLE staff ADD COLUMN updated_on TEXT DEFAULT '2026-02-15';
SELECT staff_name, dept_name FROM staff NATURAL JOIN dept ORDER BY staff_name;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • ON accepts any condition
  • USING (col) is equality on same-named columns, output once
  • NATURAL JOIN picks join columns automatically from shared names
  • A new common column name can silently change a NATURAL JOIN

Common mistakes

  • Using NATURAL JOIN in code that lives for years
  • Expecting USING to work when key columns have different names

Follow-ups

  • Can you mix USING with extra conditions?
  • How do you refer to the USING column in SELECT on PostgreSQL?

Tips

  • Tell the audit-column story; it is the concrete reason behind the rule