Full answer
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 DISTINCT dept_id FROM employees ORDER BY salary; -- error on purposetext
Error: for SELECT DISTINCT, ORDER BY expressions must appear in select listSQLite is lenient:
sql
SELECT DISTINCT dept_id FROM employees ORDER BY salary;| dept_id |
|---|
| NULL |
| 3 |
| 2 |
| 1 |
SQLite returned NULL, 3, 2, 1 here, but the order depends on which salary it picks for each group, which is not a documented rule, so the same query could order differently after a data change. To sort departments by a salary statistic, say which one: SELECT dept_id FROM employees GROUP BY dept_id ORDER BY MAX(salary) DESC.
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 DISTINCT dept_id FROM employees ORDER BY salary;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- DISTINCT plus ORDER BY needs the sort column in the SELECT list (PostgreSQL)
- Each distinct value can come from rows with different sort values
- SQLite accepts it with an undefined choice
- Use GROUP BY with an explicit aggregate for the sort
Common mistakes
- Sorting DISTINCT results by a hidden column
- Trusting SQLite's lenient result
Follow-ups
- How would you sort departments by average salary?
- What is DISTINCT ON in PostgreSQL?
Tips
- Name the aggregate you want to sort by