SQL > Advanced SQL > Limit

By default, all results that satisfy the conditions specified in the SQL statement are returned. However, this may not always be what we want, as sometimes we only want to retrieve a subset of records. In MySQL, this is accomplished using the LIMIT keyword. The syntax for LIMIT is as follows:

[SQL Statement 1]
LIMIT [N];

where [N] is the number of records to be returned. Please note that the ORDER BY clause is usually included in the SQL statement. Without the ORDER BY clause, the results we get would be dependent on what the database default is.

For example, we may wish to show the two highest sales amounts in Table Store_Information

Table Store_Information

Store_NameSalesTxn_Date
Los Angeles1500Jan-05-1999
San Diego250Jan-07-1999
San Francisco300Jan-08-1999
Boston700Jan-08-1999

we key in,

SELECT Store_Name, Sales, Txn_Date
FROM Store_Information
ORDER BY Sales DESC
LIMIT 2;

Result:

Store_NameSalesTxn_Date
Los Angeles1500Jan-05-1999
Boston700Jan-08-1999

The SQL Server equivalent to LIMIT is TOP, which is covered next.

Next: SQL TOP




Copyright © 2014   1keydata.com   All Rights Reserved.     Privacy Policy     About   Contact