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

Select The First N Rows From A Result

Retrieve a fixed number of rows from the top of a sorted result set using `LIMIT`, `TOP`, or `FETCH FIRST`.

Docker-validated Not currently validation-green

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.

MySQL MariaDB PostgreSQL SQLite
Engine-specific syntax
Setup
CREATE TABLE events (id INT, name VARCHAR(50));

INSERT INTO
  events
VALUES
  (1, 'signup'),
  (2, 'login'),
  (3, 'purchase'),
  (4, 'logout'),
  (5, 'delete');
SQL
SELECT
  id,
  name
FROM
  events
ORDER BY
  id
LIMIT
  3;
idname
1signup
2login
3purchase
SQL Server
Engine-specific syntax
Setup
CREATE TABLE events (id INT, name VARCHAR(50));

INSERT INTO
  events
VALUES
  (1, 'signup'),
  (2, 'login'),
  (3, 'purchase'),
  (4, 'logout'),
  (5, 'delete');
SQL
SELECT
  TOP 3 id,
  name
FROM
  events
ORDER BY
  id;
idname
1signup
2login
3purchase

SQL Server uses SELECT TOP n before the column list. All other engines append LIMIT n after ORDER BY. The result is identical.

Where this command helps.

  • showing the most recent or highest-ranked items in a UI
  • sampling a few rows from a large table for inspection

What the command is doing.

Each database engine offers a way to cap the number of rows returned. MySQL, MariaDB, PostgreSQL, and SQLite use LIMIT n at the end of the query. SQL Server uses SELECT TOP n at the start of the select list. All standards-compliant engines also support the ISO syntax FETCH FIRST n ROWS ONLY, though support varies. Always pair a row limit with ORDER BY — without it, the 'first' rows are chosen arbitrarily and results are non-deterministic across runs.