← Back to PostgreSQL, page 2

postgresql-0026 · Easy fresher

Return the top three scores including ties with FETCH FIRST ... WITH TIES.

FETCH FIRST n ROWS WITH TIES (PostgreSQL 13+) returns the first n rows plus any further rows that tie with the last one on the ORDER BY keys. LIMIT n cuts off at exactly n rows, dropping tied rows arbitrarily. WITH TIES requires an ORDER BY.

Full answer

Setup for the example:

sql
CREATE TABLE results (student text, score int);
INSERT INTO results VALUES ('Asha', 95), ('Ben', 88), ('Chen', 91), ('Dev', 88), ('Esha', 70);
sql
SELECT student, score FROM results ORDER BY score DESC, student LIMIT 3;

PostgreSQL returns:

text
 student | score
---------+-------
 Asha    | 95
 Chen    | 91
 Ben     | 88
(3 rows)
sql
SELECT student, score FROM results ORDER BY score DESC FETCH FIRST 3 ROWS WITH TIES;

Result on PostgreSQL 17:

text
 student | score
---------+-------
 Asha    | 95
 Chen    | 91
 Ben     | 88
 Dev     | 88
(4 rows)
sql
SELECT student FROM results FETCH FIRST 3 ROWS WITH TIES;

Result:

text
ERROR:  WITH TIES cannot be specified without ORDER BY clause

LIMIT 3 returns Asha, Chen and Ben, leaving out Dev although he scored the same 88 as Ben; the student tie-breaker only makes the choice repeatable. WITH TIES returns four rows, because Dev ties with the third row. The order within the tied rows is not specified, since only score is in the ORDER BY. Without ORDER BY, WITH TIES is an error. A window function such as rank() <= 3 gives the same result on databases without WITH TIES.

sql
CREATE TABLE results (student text, score int);
INSERT INTO results VALUES ('Asha', 95), ('Ben', 88), ('Chen', 91), ('Dev', 88), ('Esha', 70);

SELECT student, score FROM results ORDER BY score DESC, student LIMIT 3;

SELECT student, score FROM results ORDER BY score DESC FETCH FIRST 3 ROWS WITH TIES;

SELECT student FROM results FETCH FIRST 3 ROWS WITH TIES;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • WITH TIES includes tied rows
  • LIMIT cuts off at exactly n
  • Requires ORDER BY
  • PostgreSQL 13+
  • rank() is the portable alternative

Common mistakes

  • Using LIMIT for 'top 3 including ties'
  • Forgetting ties when awarding prizes

Follow-ups

  • How would you get the top 3 per class?
  • How does OFFSET interact with WITH TIES?

Tips

  • Show the dropped tie