Example 1
Return the top 3 scores but include all players tied at the boundary
Without WITH TIES, FETCH FIRST 3 ROWS ONLY (or TOP 3) would return Alice (95), Bob (90), and Carol (90) — leaving Eve off even though she also scored 90. With WITH TIES, the engine compares each candidate row's ORDER BY value against the last kept row. The third kept row is Carol at score 90. Eve also has score 90, so she ties on the ORDER BY key and is included, giving four rows total. Dave's score of 85 is lower, so he is excluded. The secondary ORDER BY player ASC ensures a deterministic order within the tied group: Bob, Carol, Eve appear alphabetically. SQL Server places WITH TIES after TOP n in the select list, while PostgreSQL appends WITH TIES to the FETCH FIRST n ROWS clause at the end of the query.
CREATE TABLE scores (player VARCHAR(20), score INT);
INSERT INTO
scores
VALUES
('Alice', 95),
('Bob', 90),
('Carol', 90),
('Dave', 85),
('Eve', 90);SELECT
TOP 3
WITH
TIES player,
score
FROM
scores
ORDER BY
score DESC,
player ASC;| player | score |
|---|---|
| Alice | 95 |
| Bob | 90 |
| Carol | 90 |
| Eve | 90 |
CREATE TABLE scores (player VARCHAR(20), score INT);
INSERT INTO
scores
VALUES
('Alice', 95),
('Bob', 90),
('Carol', 90),
('Dave', 85),
('Eve', 90);SELECT
player,
score
FROM
scores
ORDER BY
score DESC,
player ASC
FETCH FIRST
3 ROWS
WITH
TIES;| player | score |
|---|---|
| Alice | 95 |
| Bob | 90 |
| Carol | 90 |
| Eve | 90 |
SQL Server uses TOP n WITH TIES in the select list. PostgreSQL uses FETCH FIRST n ROWS WITH TIES at the end of the query. MySQL, MariaDB, and SQLite have no direct equivalent.