Logo

K-Learn

SQL TOP Clause

< Previous Next >

The TOP clause in SQL is used to limit the number of rows returned by a SELECT statement. It is commonly used with the SELECT statement to retrieve a specific number or percentage of rows from a table that matches certain criteria.

TOP Clause Syntax

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

For Example,

SELECT TOP 5 name, marks FROM exam 
JOIN student ON exam.student_id = student.id
ORDER BY marks DESC

OUTPUT

In this example,

In this example of the student table, if we want to retrieve only the top 5 students with the highest marks, we can use the following query: This query retrieves the names and marks of the top 5 students based on the marks they scored in the exams. The JOIN clause is used to join the exam table with the student table, and the ORDER BY clause is used to sort the rows in descending order of the marks column. Finally, the TOP clause is used to retrieve only the top 5 rows from the result set. It is important to note that the syntax of the TOP clause may differ slightly depending on the specific SQL database being used. For example, some databases may use the LIMIT clause instead of TOP.


< Previous Next >