tags:

views:

168

answers:

5

There is a query like SELECT * FROM clients ORDER BY id. I want to select only first 10 elements. How can I do this?

P.S. I'm using MySQL.

+10  A: 
SELECT * FROM clients ORDER BY id LIMIT 10;
Luke Bayes
Should be noted that the ORDER BY defaults to ASC, where DESC is also an option, but must be explicitly stated - `ORDER BY id DESC`
Jonathan Sampson
+2  A: 

SELECT * FROM clients ORDER BY id Limit 10

Jebli
That's for SQL Server. MySQL and Postgres use LIMIT.
Arthur Reutenauer
I have edited the answer.Sorry
Jebli
+4  A: 

Here's all you can do with a SELECT (taken from here):

SELECT
    [ALL | DISTINCT | DISTINCTROW ]
      [HIGH_PRIORITY]
      [STRAIGHT_JOIN]
      [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
      [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
    select_expr [, select_expr ...]
    [FROM table_references
    [WHERE where_condition]
    [GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]
    [HAVING where_condition]
    [ORDER BY {col_name | expr | position}
      [ASC | DESC], ...]
    [LIMIT {[offset,] row_count | row_count OFFSET offset}]
    [PROCEDURE procedure_name(argument_list)]
    [INTO OUTFILE 'file_name' export_options
      | INTO DUMPFILE 'file_name'
      | INTO var_name [, var_name]]
    [FOR UPDATE | LOCK IN SHARE MODE]]

So the statement you are looking for is:

SELECT * FROM clients ORDER BY id LIMIT 10
tangens
+1  A: 

Note that OFFSET is very helpful to paginate:

LIMIT 10 OFFSET 11

for the second page of 10.

David W
A: 

The MySQL way is to use

SELECT * FROM clients ORDER BY id LIMIT 10;

which is MySQL-specific. For a longtime there was no counterpart in other databases but the SQL:2008 standard introduces an additional syntax:

SELECT * FROM clients FETCH FIRST 10 ROWS ONLY;

And

SELECT * FROM clients OFFSET 1 FETCH NEXT 10 ROWS ONLY;

But the problem is, that this syntax isn't supported by MySQL and most other databases, yet. In case you care about portability you should follow the development there.

Please mind that you should always ORDER BY clauses else the result might be random on different calls.

johannes