By default, SQL will return all the rows of data as a result of a query. However, there may be certain circumstances where it is desired to truncate the results to a set number of rows. This could be either for taking a quick look at some sample data, or for looking at a set amount of data for performing analytics (e.g. the top 10 records by a given metric). The
LIMIT clause serves this purpose.
LIMIT clause comes at the very end of a
SELECT statement, and is followed by the number of rows to which to truncate the query result. For example, to see only 10 rows from the
employees table, we can add to our regular “select star” query:
SELECT * FROM employees LIMIT 10;
The above is a very frequently-executed type of query to quickly inspect a table and see at a glance what types of data it contains.
SELECT <columns> FROM <table> WHERE <predicate> ORDER BY <column> LIMIT <row count>;
If there are other clauses in the query, the
LIMIT clause still comes at the very end:
It is a best practice to always include a
LIMIT clause when working with large tables (or tables of unknown size) when possible, in order to reduce query runtime and limit memory usage.
Learn SQL Today
Get hands-on experience writing code with interactive tutorials in our free online learning platform.
- Free and fun
- Designed for beginners
- No downloads or setup required