SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL GROUP BY SQL Having SQL In SQL INSERT INTO SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL TOP, LIMIT and FETCH FIRST

Limiting rows is useful when you only need a small result set: the newest orders, the most expensive products, or the first page of a search result.

Syntax

Different database systems use different keywords for this task.

-- SQL Server
SELECT TOP 10 column_name
FROM table_name;
-- MySQL, PostgreSQL and SQLite
SELECT column_name
FROM table_name
LIMIT 10;
-- Standard-style syntax supported by several databases
SELECT column_name
FROM table_name
FETCH FIRST 10 ROWS ONLY;

Example

Get the five most expensive products:

SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 5;

Use ORDER BY when the order matters. Without it, the database can return any matching rows, which is technically valid and not very helpful.

Common mistakes

Related topics

Review SQL ORDER BY, SQL SELECT and the SQL Formatter.