← Back to SQL, page 16

sql-0306 · Easy fresher

What does SELECT MAX(name) FROM employees return?

The alphabetically last name under the column's collation, here 'Tom'. MIN and MAX work on text, comparing strings, not on the length of the value. With SQLite's default binary collation, uppercase letters sort before lowercase ones, which can surprise.

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 MIN(name) AS first_name, MAX(name) AS last_name FROM employees;
first_namelast_name
AshaTom

MIN returns Asha and MAX returns Tom, by string comparison. For the longest name, sort by length(name) instead.

With mixed case, binary collation would put 'zoe' after 'Tom' but 'Zoe' before 'asha'. Use MAX(name COLLATE NOCASE) in SQLite, or a linguistic collation in PostgreSQL, when case should not matter.

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 MIN(name) AS first_name, MAX(name) AS last_name FROM employees;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • MIN and MAX compare text by collation
  • They do not measure string length
  • Binary collation is case-sensitive
  • Use NOCASE or a linguistic collation when needed

Common mistakes

  • Using MAX to find the longest string
  • Ignoring case effects on string MAX

Follow-ups

  • How would you return the longest name?
  • What do MIN and MAX return for dates stored as text?

Tips

  • Separate value order from length