SQL SELECT TOP Clause

Here’s a clear and practical guide to the SQL SELECT TOP clause, including differences across database engines.


βœ… Basic Usage (SQL Server / MS Access)

SELECT TOP 10 *
FROM employees;

This returns the first 10 rows based on the default ordering (or a specified ORDER BY).


πŸ”₯ SELECT TOP with ORDER BY

Always combine with ORDER BY to ensure predictable results:

SELECT TOP 5 name, salary
FROM employees
ORDER BY salary DESC;

πŸ”§ SELECT TOP with PERCENT

Returns a percentage of rows:

SELECT TOP 20 PERCENT *
FROM products
ORDER BY created_at DESC;

⚠ Other Databases Don’t Use TOP

Different SQL engines use different syntax:


PostgreSQL / MySQL / SQLite β€” Use LIMIT

SELECT *
FROM employees
ORDER BY id
LIMIT 10;

Oracle β€” Use FETCH FIRST

SELECT *
FROM employees
ORDER BY id
FETCH FIRST 10 ROWS ONLY;

πŸ” Best Practices

βœ” Always pair TOP/LIMIT with an ORDER BY
βœ” Avoid using TOP without specifying sorting (non-deterministic)
βœ” For pagination, use OFFSET + LIMIT (PostgreSQL/MySQL/SQLite) or OFFSET with FETCH (SQL Server/Oracle)

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *