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

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.