SQL Tutorial for Beginners: SQL SELECT LIMIT, TOP, FETCH FIRST

In this SQL tutorial for beginners, you will learn about SQL SELECT LIMIT, TOP, FETCH FIRST with the help of examples.

The LIMIT keyword in SQL allows you to specify the number of records to return in a query. We can use the LIMIT keyword with MySQL, PostgreSQL, and SQLite.

Example

SELECT first_name, age
FROM Customers
LIMIT 2;

Here, the SQL command selects the first 2 rows from the table.


SQL LIMIT With OFFSET Clause

The OFFSET keyword is used with LIMIT to specify the starting rows from where to select the data. For example,

-- LIMIT 2 selects two results
-- OFFSET 3 excludes the first three results

SELECT first_name, last_name
FROM Customers
LIMIT 2 OFFSET 3;

Here, the SQL command selects 2 rows starting from the fourth row. OFFSET 3 means the first 3 rows are excluded.

How to use SQL LIMIT Clause with OFFSET

Example: SQL LIMIT Clause with OFFSET

Note: The LIMIT clause is not supported in all Database Management Systems (DBMS). Different DBMS use different keywords to select a fixed number of rows. For example,

KeywordDatabase System
TOPSQL Server, MS Access
LIMITMySQL, PostgreSQL, SQLite
FETCH FIRSTOracle

SQL TOP Clause

The TOP keyword is used in place of LIMIT with the following database systems:

  • SQL Server
    • MS Access
SELECT TOP 2 first_name, last_name
FROM Customers;

Here, the SQL command selects first_name and last_name of the first 2 rows.

We can also use * with TOP to select all columns.

SELECT TOP 2 *
FROM Customers;

Here, the SQL command selects the first 2 rows from the table.

How to use SQL TOP Clause

Example: SQL TOP Clause


SQL FETCH FIRST Clause

The FETCH FIRST n ROWS ONLY clause is used with the Oracle database system.

Let's look at an example.

SELECT *
FROM Customers
FETCH FIRST 2 ROWS ONLY;

Here, the SQL command selects the first 2 rows from the table.

#sql 

SQL Tutorial for Beginners: SQL SELECT LIMIT, TOP, FETCH FIRST
1.90 GEEK