SELECT TOP in SQL by Practical Examples – Analytics Planets

Overview: In this tutorial you will learn and understand SELECT TOP query in SQL with practical examples.

SELECT TOP

The command SELECT TOP in SQL allows you to extract or display the number of rows to returned result in SQL query. You can give the number of rows count, which you want to display in result Like top 10 rows, top 100 rows etc…

Why we need Select Top Command?

The SELECT TOP clause is useful on large tables with thousands of records. This command mostly used to get the result when user need to see specific top related results based on WHERE condition or without where condition. Therefore, the result set is limited to the first N number of ordered rows.

The SELECT TOP clause is useful on large tables. If you would like to see few result from millions of records and you will run simple SELECT query then it will take long time to run and sometime it will stop your SQL query window. So its better to use SELECT TOP command to see few results.

Below shows the syntax of the SELECT TOP clause with the SELECT statement:

Syntax:

SELECT TOP (number) 
      column_name(s)
FROM 
      table_name
WHERE 
      condition;

Lets take example to see the result with SELECT TOP command

Example #1: SELECT TOP 5 rows in SQL

SELECT TOP 5 
     * 
FROM 
   Customers_Tbl;

In this example SELECT TOP query is  extracting top 5 first rows items with all columns in the table, As we have not selected any specific columns only we put “*” mark which means all columns

Result:

Select Top in SQL

Example #2: SELECT TOP using WHERE clause

SELECT TOP in SQL can be performed on Where clause as well to show the result for TOP rows with condition on specific columns,

In below example WHERE clause on column [Province]= ‘Ontario’ extract only whose rows which is equal to ‘Ontario’

SELECT TOP 5 
      * 
FROM 
     Customers_Tbl
WHERE
     Province= 'Ontario';

Result:

Select Top in SQL

Example #3: SELECT TOP in SQL using Order BY Clause

One more clause we recommend to use with SELECT TOP in SQL is ORDER BY clause which make your rows sorted by specific columns

SELECT TOP 10
       Customer ID, Customer Name, Province, region 
FROM
      Customers_Tbl
ORDER BY 
      Customer ID DESC;

Above example extract the TOP 10 mentioned columns sorted by [Customer ID] in descending order.

Hope in this tutorial, you have learned how to use the SELECT TOP in SQL statement to limit the number of rows or percentage of rows returned by a query.