SQL Query to access first N records from a table

Here, we will figure out how to get to first and keep going N records from a table with an example of SQL Query that will return first and keep going N records from a table.

Essentially we have three conditions in SQL,

  • TOP – It works in SQL Server or MS-Access.
  • Breaking point – It works in MySQL.
  • 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

Discovering first (Top) N records

1) SQL Query to discover initial 2 records in MySQL

mysql> select * from emp limit 2;

Output:

Id Full_name 1 Preeti jain 2 Rahul jain

2) SQL Query to discover initial 3 records in MySQL

mysql> select * from emp limit 3;

Output:

    Id	Full_name
    1	Preeti jain
    2	Rahul jain
    3	Tanya jain

Discovering keep going N records

1) SQL Query to discover 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

Leave a Comment

error: Alert: Content is protected!!