Friday 16 December 2011

MySQL Limit Clause

You can restrict the number of rows a query returns by using the limit clause at the end. It is followed by 2 numbers, which are separated by a comma. The first number tells the query which row to start at (the table's first row is numbered zero). The second number tells the query how many rows to return. You can see what I mean in the examples below:  

mysql> create table andrews_table
    -> (col1 varchar(10));
Query OK, 0 rows affected (0.00 sec)
 
mysql> insert into andrews_table values ('Brian');
Query OK, 1 row affected (0.00 sec)
 
mysql> insert into andrews_table values ('Joe');
Query OK, 1 row affected (0.00 sec)
 
mysql> insert into andrews_table values ('Fred');
Query OK, 1 row affected (0.00 sec)
 
mysql> insert into andrews_table values ('Andrew');
Query OK, 1 row affected (0.00 sec)
 
mysql> select col1 from andrews_table limit 0,2;
+-------+
| col1  |
+-------+
| Brian |
| Joe   |
+-------+
2 rows in set (0.00 sec)
 
mysql> select col1 from andrews_table limit 2,2;
+--------+
| col1   |
+--------+
| Fred   |
| Andrew |
+--------+
2 rows in set (0.00 sec)
 
mysql> select col1 from andrews_table limit 1,3;
+--------+
| col1   |
+--------+
| Joe    |
| Fred   |
| Andrew |
+--------+
3 rows in set (0.00 sec)
 
mysql>

No comments: