Posts Tagged Select

SQL – Select with limit rows and records Clause Example, Oracle MS SQL MySQL

Sunday, November 22nd, 2009

SQL select query is used to fetch records from database. limit clause is used to get limited rows from database table. Limit is implemented differently with different database Oracle, MS Sql, MySQL.

SQL select limit query example explains how to use select limit query in SQL.

Table class_name with all records

+---------+-------------+------------+------------+
| Roll_No | Name        | Class_Name | Year_Start |
+---------+-------------+------------+------------+
|       1 | Amit Mishra | B Science  |       2005 |
|       2 | Robot       | B.Tech     |       2005 |
|       3 | Rohan       | M.Tech     |       2005 |
|       4 | Vivek       | B.Tech     |       2009 |
|       5 | Chander     | B.Science  |       2009 |
|       6 | Deepak      | B.Science  |       2009 |
+---------+-------------+------------+------------+

In MySQL, limit keyword

select * from class_name limit 4;

Output

+---------+-------------+------------+------------+
| Roll_No | Name        | Class_Name | Year_Start |
+---------+-------------+------------+------------+
|       1 | Amit Mishra | B Science  |       2005 |
|       2 | Robot       | B.Tech     |       2005 |
|       3 | Rohan       | M.Tech     |       2005 |
|       4 | Vivek       | B.Tech     |       2009 |
+---------+-------------+------------+------------+

this SQL query in mysql return only top 4 rows from table.

select * from class_name limit 2, 4;

Output

+---------+---------+------------+------------+
| Roll_No | Name    | Class_Name | Year_Start |
+---------+---------+------------+------------+
|       3 | Rohan   | M.Tech     |       2005 |
|       4 | Vivek   | B.Tech     |       2009 |
|       5 | Chander | B.Science  |       2009 |
|       6 | Deepak  | B.Science  |       2009 |
+---------+---------+------------+------------+

this SQL query in mysql returns only rows start after top 2 and get only 4 rows.

In Oracle, limits rows by rownum keyword in SQL query

select * from class_name rownum <=4;

this Oracle SQL query returns only top 4 rows from table

In Microsoft SQL, limits rows by top keyword in SQL query

select top 4 column_names from class_name;

this Mircrosoft SQL query returns only top 4 rows from table

* indicates fetch all columns records from table.