π TOP β Get Only the First Few Rows in SQL
π§ Quick Syntax
SELECT TOP number column1, column2
FROM table_name
ORDER BY column_name DESC;
This tells SQL:
βGive me just the first few rows from the sorted results β like a highlight reel.β
Note: TOP
works in SQL Server. For MySQL or PostgreSQL, use LIMIT
(weβll cover that too).
π§Ύ Hereβs the Table Youβre Working With
Imagine youβve got an orders
table like this:
order_id | customer_name | total_amount |
---|---|---|
1 | Brill Venn | 15.99 |
2 | Larka Tove | 45.00 |
3 | Brill Venn | 15.99 |
4 | Milo Kresh | 72.50 |
5 | Vesh Luro | 10.00 |
6 | Tola Jinn | 29.99 |
β Suppose You Want to See the Top 3 Highest Orders
SELECT TOP 3 customer_name, total_amount
FROM orders
ORDER BY total_amount DESC;
π‘ Output:
Milo Kresh 72.50
Larka Tove 45.00
Tola Jinn 29.99
Here you sorted the orders from highest to lowest, and TOP 3
gave you the first three rows. Great for dashboards, leaderboards, or best-of lists.
β Suppose You Want the 2 Smallest Orders
SELECT TOP 2 customer_name, total_amount
FROM orders
ORDER BY total_amount ASC;
π‘ Output:
Vesh Luro 10.00
Brill Venn 15.99
This one sorted the data from smallest to largest and gave you the two cheapest orders. Same logic, just in reverse.
π§ Recap β What You Learned
TOP
limits how many rows your query returns- Combine with
ORDER BY
to choose what βtopβ really means - Great for bestsellers, highest spenders, top viewed items, and more
- Works in SQL Server β for MySQL/PostgreSQL use
LIMIT
instead