Home » SQL

SQL Query to access first N records from a table

Here, we will learn how to access first and last N records from a table with an example of SQL Query that will return first and last N records from a table.
Submitted by Preeti Jain, on March 21, 2018

Basically we have three clauses in SQL,

  1. TOP - It works in SQL Server or MS-Access.
  2. LIMIT - It works in MySQL.
  3. ROWNUM - It works in ORACLE.

Here we have a table named emp,

    Id	Full_name
    1	Preeti jain
    2	Rahul jain
    3	Tanya jain
    4	Ayesha jain

Finding first (Top) N records

1) SQL Query to find first 2 records in MySQL

mysql> select * from emp limit 2;

Output:

    Id	Full_name
    1	Preeti jain
    2	Rahul jain

2) SQL Query to find first 3 records in MySQL

mysql> select * from emp limit 3;

Output:

    Id	Full_name
    1	Preeti jain
    2	Rahul jain
    3	Tanya jain

Finding last N records

1) SQL Query to find last record from a table in MySQL

mysql> select * from emp order by id desc limit 1;

Output:

    Id	Full_name
    4	Ayesha jain

2) SQL Query to last 3 records in MySQL

mysql> select * from emp order by id desc limit 3;

Output:

    Id	Full_name
    4	Ayesha jain
    3	Tanya jain
    2	Rahul jain


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.