TOP: Exploring the TOP Keyword in SQL: Limiting Result Sets Effectively

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


In any database-related project, managing and manipulating the result sets effectively is one of the most crucial aspects. SQL, as a database management language, provides several keywords and functions to handle such operations, one among them is the ‘TOP’ keyword.

What is the TOP keyword in SQL?

The TOP keyword in SQL is used to limit the number of rows returned by a query. This comes in particularly handy when dealing with voluminous datasets and you’re not interested in all the returns a query could give but a certain number of top rows based, generally on certain conditions.

How to use the TOP keyword

TOP keyword is quite straightforward to use. It is used right after the SELECT statement and immediately followed by the numbers of rows you want to return. Look at the syntax below:

In the above SQL statement replace “number|percent” with the number of records that you want to retrieve, and “column_name(s)” with the columns you want to select from the specified “table_name”. The WHERE clause is optional, if you want to filter records based on certain conditions you can use it.

An example of the SQL TOP keyword

Suppose we have a table named ‘Orders’ and we want to fetch the first 3 orders from the table, here is how we can use TOP:

An example with TOP and WHERE

You can also use the TOP keyword simultaneously with the WHERE clause to filter your result:

Conclusion

The TOP keyword in SQL serves as a nifty tool when working with large databases by allowing us to limit the data that our queries return. As we have seen from the examples, it is quite simple to use and can be combined with other SQL keywords for better data filtering and manipulation.

Leave a Comment