Database.Beginner.How to Fetch the Top N Records in SQL ?

It depends a little on the SQL dialect (MySQL, PostgreSQL, SQL Server, etc.), but the general idea is:


1. Using LIMIT (MySQL, PostgreSQL, SQLite)

SELECT * FROM table_name
ORDER BY column_name
LIMIT N;

Example — get top 5 employees with highest salary:

SELECT * FROM Employees
ORDER BY salary DESC
LIMIT 5;

ORDER BY salary DESC — sort by salary, highest first.

LIMIT 5 — return only the first 5 rows.

2. Using TOP (SQL Server)

SELECT TOP N * FROM table_name
ORDER BY column_name DESC;

Example — top 3 customers by total purchases:

SELECT TOP 3 * FROM Customers
ORDER BY total_purchases DESC;

3. Using FETCH FIRST N ROWS ONLY (Standard SQL, Oracle, DB2, PostgreSQL 13+)

SELECT * FROM table_name
ORDER BY column_name
FETCH FIRST N ROWS ONLY;

Example — top 10 students by score:

SELECT * FROM Students
ORDER BY score DESC
FETCH FIRST 10 ROWS ONLY;

Very standard SQL way.

Supported by Oracle (12c+), DB2, PostgreSQL 13+.

Why Use ORDER BY with LIMIT / TOP?

Because:

  • LIMIT N without ORDER BY just returns random N rows depending on how the DB scans the table.
  • ORDER BY makes it meaningful — like top salaries, earliest dates, highest scores.

Bonus: Skip First N Rows (Pagination)

You can also skip rows — useful for pagination:

✅ In MySQL/PostgreSQL:

SELECT * FROM Employees
ORDER BY salary DESC
LIMIT 5 OFFSET 10;   -- Skip first 10, fetch next 5

✅ In SQL Server (2012+):

SELECT * FROM Employees
ORDER BY salary DESC
OFFSET 10 ROWS
FETCH NEXT 5 ROWS ONLY;

In Short

DatabaseTop N Syntax
MySQL, PostgreSQL, SQLiteLIMIT N
SQL ServerTOP N
Oracle, DB2, PostgreSQL 13+FETCH FIRST N ROWS ONLY

✅ Always use ORDER BY to get meaningful Top N results.


Example

📝 Top 5 best-selling products:

SELECT product_name, SUM(quantity) AS total_sold
FROM Sales
GROUP BY product_name
ORDER BY total_sold DESC
LIMIT 5;
This entry was posted in Без рубрики. Bookmark the permalink.