SQL | SELECT TOP Clause


SELECT TOP clause is used to fetch limited number of rows from a database. This clause is very useful while dealing with large databases.

  • Basic Syntax:
    SELECT TOP value column1,column2 FROM table_name;
    value: number of rows to return from top
    column1 , column2: fields in the table
    table_name: name of table
    
  • Syntax using Percent
    SELECT TOP value PERCENT column1,column2 FROM table_name;
    value: percentage of number of rows to return from top
    column1 , column2: fields in the table
    table_name: name of table
    

table1

Queries



        • To fetch first two data set from Student table.
          SELECT TOP 2 * FROM Student; 
          

          Output:

          ROLL_NO NAME ADDRESS PHONE Age
          1 Ram Delhi XXXXXXXXXX 18
          2 RAMESH GURGAON XXXXXXXXXX 18

 

      • To fetch 50 percent of the total records from Student table.
        SELECT TOP 50 PERCENT * FROM Student; 
        

        Output:

        ROLL_NO NAME ADDRESS PHONE Age
        1 Ram Delhi XXXXXXXXXX 18
        2 RAMESH GURGAON XXXXXXXXXX 18
        3 SUJIT ROHTAK XXXXXXXXXX 20

NOTE: To get the same functionality on MySQL and Oracle databases there is a bit of difference in the basic syntax;

        Equivalent Syntaxes are as follows:

      • For MySQL databases:
        SELECT column1,column2 FROM table_name LIMIT value;
        column1 , column2: fields int the table
        table_name: name of table
        value: number of rows to return from top
        
      • For Oracle databases:
        SELECT column1,column2 FROM table_name WHERE ROWNUM <= value;
        column1 , column2: fields int the table
        table_name: name of table
        value: number of rows to return from top
        

This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.