Example 1
Return the three earliest events from an event log
The table has five events. With ORDER BY id, they are ranked 1 through 5. Only the first three rows are returned. Logout (4) and delete (5) are discarded. Without an ORDER BY, the engine would return any three rows and the result would change between runs.
CREATE TABLE events (id INT, name VARCHAR(50));
INSERT INTO
events
VALUES
(1, 'signup'),
(2, 'login'),
(3, 'purchase'),
(4, 'logout'),
(5, 'delete');SELECT
id,
name
FROM
events
ORDER BY
id
LIMIT
3;| id | name |
|---|---|
| 1 | signup |
| 2 | login |
| 3 | purchase |
CREATE TABLE events (id INT, name VARCHAR(50));
INSERT INTO
events
VALUES
(1, 'signup'),
(2, 'login'),
(3, 'purchase'),
(4, 'logout'),
(5, 'delete');SELECT
TOP 3 id,
name
FROM
events
ORDER BY
id;| id | name |
|---|---|
| 1 | signup |
| 2 | login |
| 3 | purchase |
SQL Server uses SELECT TOP n before the column list. All other engines append LIMIT n after ORDER BY. The result is identical.