sqlcmd.net validated sql reference
beginner pagination MySQL MariaDB SQL Server PostgreSQL SQLite

Use LIMIT Or TOP With ORDER BY For Stable Results

A row limit without an explicit sort can return different rows over time or across engines.

Docker-validated Not currently validation-green

Take the two newest rows in a deterministic order

The query returns Bravo and Charlie because they are the two newest posts by published_at. The ORDER BY makes the limit meaningful and repeatable. Without that ordering, the database would be free to return any two rows.

MySQL MariaDB PostgreSQL SQLite
Engine-specific syntax
Setup
CREATE TABLE posts (
  id INT,
  title VARCHAR(50),
  published_at VARCHAR(19)
);

INSERT INTO
  posts (id, title, published_at)
VALUES
  (1, 'Alpha', '2026-04-01 09:00:00'),
  (2, 'Bravo', '2026-04-03 09:00:00'),
  (3, 'Charlie', '2026-04-02 09:00:00');
SQL
SELECT
  id,
  title
FROM
  posts
ORDER BY
  published_at DESC,
  id DESC
LIMIT
  2;
idtitle
2Bravo
3Charlie
SQL Server
Engine-specific syntax
Setup
CREATE TABLE posts (
  id INT,
  title VARCHAR(50),
  published_at VARCHAR(19)
);

INSERT INTO
  posts (id, title, published_at)
VALUES
  (1, 'Alpha', '2026-04-01 09:00:00'),
  (2, 'Bravo', '2026-04-03 09:00:00'),
  (3, 'Charlie', '2026-04-02 09:00:00');
SQL
SELECT
  TOP 2 id,
  title
FROM
  posts
ORDER BY
  published_at DESC,
  id DESC;
idtitle
2Bravo
3Charlie

The result is the same across engines, but SQL Server uses `TOP` instead of `LIMIT`.

Where this command helps.

  • getting a stable top-N result for dashboards or tests
  • avoiding misleading samples from unordered row limits

What the command is doing.

A common sampling mistake is treating LIMIT or TOP as if it automatically means 'first rows in a meaningful order.' It does not. Without ORDER BY, the database can return whichever rows are cheapest to read. If you want the newest rows, largest values, or any stable subset, you must define the order explicitly.