Your First Queries · Lesson 8 of 64

SQL DISTINCT and Reading Error Messages

What you will learn

  • How to list different values only, with DISTINCT
  • How DISTINCT works on several columns at once
  • How to read the four most common error messages
  • A short routine for fixing a query that does not run

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. DISTINCT: each value once

Many rows share the same value in a column. SELECT DISTINCT returns each different value only once:

SELECT DISTINCT country FROM customers ORDER BY country LIMIT 8;
country
----------
Bangladesh
Brazil
Canada
Egypt
Ghana
India
Japan
Kenya
(8 rows)
SELECT DISTINCT risk_level FROM customers ORDER BY risk_level LIMIT 8;
risk_level
----------
high
low
normal
(3 rows)
SELECT DISTINCT enrolled_year FROM students ORDER BY enrolled_year LIMIT 8;
enrolled_year
-------------
         2023
         2024
         2025
         2026
(4 rows)

Without DISTINCT the same query would return one row for every row of the table. DISTINCT is the quickest way to ask "which values occur in this column?".

2. How many different values?

COUNT(DISTINCT column) counts the different values. Compare it with the count of all rows:

SELECT COUNT(*) AS all_rows, COUNT(DISTINCT country) AS different_values FROM customers;
all_rows  different_values
--------  ----------------
     420                16
(1 row)
SELECT COUNT(*) AS all_rows, COUNT(DISTINCT risk_level) AS different_values FROM customers;
all_rows  different_values
--------  ----------------
     300                 3
(1 row)
SELECT COUNT(*) AS all_rows, COUNT(DISTINCT enrolled_year) AS different_values FROM students;
all_rows  different_values
--------  ----------------
     360                 4
(1 row)

(COUNT is covered properly in chapter 3.) If the two numbers are close, the column is nearly unique; if the second is tiny, the column holds a few repeated values.

3. DISTINCT on several columns

With two or more columns, DISTINCT removes rows that are identical in all of them. It looks at the combination:

SELECT DISTINCT country, city FROM customers ORDER BY country, city LIMIT 8;
country     city
----------  ------------
Bangladesh  Dhaka
Brazil      Porto Alegre
Brazil      porto alegre
Canada      Toronto
Canada      toronto
Egypt       Cairo
Egypt       cairo
Ghana       Accra
(8 rows)
SELECT DISTINCT risk_level, city FROM customers ORDER BY risk_level, city LIMIT 8;
risk_level  city
----------  ------
high        Austin
high        Cairo
high        Dhaka
high        Hanoi
high        Lagos
high        Leeds
high        Lima
high        Lisbon
(8 rows)
SELECT DISTINCT enrolled_year, guardian_name FROM students ORDER BY enrolled_year, guardian_name LIMIT 8;
enrolled_year  guardian_name
-------------  -------------
         2023  NULL
         2023  Aisha Reyes
         2023  Amir Nguyen
         2023  Ana Ito
         2023  Ana Nguyen
         2023  Arjun Sato
         2023  Bela Kumar
         2023  Chloe Lopez
(8 rows)

A country can appear several times here, because it is the pair that must be different. DISTINCT always applies to the whole row of the result, not to the first column only.

4. NULL counts as a value for DISTINCT

For DISTINCT, all missing values (NULL) count as one value, so you see at most one NULL row:

SELECT DISTINCT phone IS NULL AS has_no_phone FROM customers;
has_no_phone
------------
           0
           1
(2 rows)
SELECT DISTINCT risk_level, risk_level IS NULL AS missing FROM customers ORDER BY risk_level;
risk_level  missing
----------  -------
high              0
low               0
normal            0
(3 rows)
SELECT DISTINCT guardian_name IS NULL AS has_no_guardian FROM students;
has_no_guardian
---------------
              0
              1
(2 rows)

(x IS NULL is true or false for each row, so DISTINCT shows at most the values 0 and 1; chapter 2 explains IS NULL.)

5. Reading error messages

When a query is wrong, the database does not guess. It stops and says what it could not understand. The message names the problem; reading it is the skill. Run each of these and read the message.

A misspelt keyword. The message points at the word it could not understand:

SELEC name FROM sqlite_master;
OperationalError: near "SELEC": syntax error
SELEC name FROM sqlite_master;
OperationalError: near "SELEC": syntax error
SELEC name FROM sqlite_master;
OperationalError: near "SELEC": syntax error

near "SELEC": syntax error means: at or just before SELEC the statement stopped making sense. Fix the spelling of the keyword.

A table that does not exist:

SELECT * FROM customerss;
OperationalError: no such table: customerss
SELECT * FROM customerss;
OperationalError: no such table: customerss
SELECT * FROM studentss;
OperationalError: no such table: studentss

no such table names the table SQLite looked for. Check the list from lesson 1.1.

A column that does not exist (lesson 1.2):

SELECT country, nothing_here FROM customers;
OperationalError: no such column: nothing_here
SELECT risk_level, nothing_here FROM customers;
OperationalError: no such column: nothing_here
SELECT enrolled_year, nothing_here FROM students;
OperationalError: no such column: nothing_here

A statement that stops too early:

SELECT country FROM customers WHERE
OperationalError: incomplete input
SELECT risk_level FROM customers WHERE
OperationalError: incomplete input
SELECT enrolled_year FROM students WHERE
OperationalError: incomplete input

incomplete input says the statement ended while SQLite was still waiting for more: here the WHERE has no condition.

6. A routine for a query that will not run

  1. Read the message, especially the name inside it (SELEC, the table, the column).
  2. Check the spelling against the schema (lesson 1.1).
  3. Check punctuation: commas between columns and none before FROM; quotes closed; a semicolon at the end.
  4. Simplify. Remove parts until the query runs, then add them back one at a time.
  5. Run it again after every small change.

Worked example: fix a broken query

This query was written fast:

SELECT first_name last_name, FROM customers
Problem How you find it Fix
comma missing between the two columns without it SQL reads last_name as an alias of first_name add the comma
comma before FROM the error points at FROM (near "FROM": syntax error) remove the comma

After both fixes: SELECT first_name, last_name FROM customers;. Each fix came from reading what the message pointed at. The query is an illustration.

Common mistakes

  • Using DISTINCT to hide a mistake. If rows repeat when they should not, find out why instead of removing them.
  • Thinking DISTINCT works on the first column only. It works on the whole row of the result.
  • Ignoring the error message. The name inside it is usually the answer.
  • Changing many things at once when a query fails. Change one thing and run again.

Key takeaways

  • SELECT DISTINCT returns each different row once; with several columns it looks at the combination.
  • COUNT(DISTINCT column) counts different values.
  • For DISTINCT, all NULLs count as one value.
  • Read error messages: syntax error, no such table, no such column and incomplete input each point at the problem.
  • When a query fails: read, check the spelling, check the punctuation, simplify, run again.

Practice

1. Which query lists the different cities in a table customers?

Show answer

SELECT DISTINCT city FROM customers;

2. What does SELECT DISTINCT a, b FROM t remove?

Show answer

Rows where both a and b are the same as in another row. It looks at the pair, not at a alone.

3. What does the error no such table: custmers tell you?

Show answer

There is no table with that name; most likely it is misspelt. Check the real name with SELECT name FROM sqlite_master WHERE type = 'table';.

4. What does incomplete input mean?

Show answer

The statement ended while the database was still waiting for more, for example a WHERE with no condition.

5. A query returns nothing but an error pointing at near "FROM". Which mistake is likely?

Show answer

A comma right before FROM (an extra comma at the end of the column list), or a missing piece just before it.

6. Name the five steps of the routine for a query that will not run.

Show answer

Read the message, check the spelling, check the punctuation, simplify, run again.