The SELECT TOP in SQL is used t retrieve a specific number or percetage of rows from a result set. It is particularly useful when you want to limit the amount of data returned by a query.
SQL Select Top Syntax
SELECT TOP (number) column1, column2, ... FROM table_name ORDER BY column1;
SQL Select Top Example
SQL Select Top Selecting Top 5 Records Example
This query retrieves the first 5 records from the Patients table, ordered by patient_id in ascending order. This means it will return the details of 5 patients with the smallest patient_id values.
SELECT TOP 5 * FROM Patients ORDER BY patient_id;
SQL Select Top Selecting Top 10 Most Recent Appointments Example
This query retrieves the top 10 most recent appointments from the Appointments table by sorting the records in descending order based on the appointment_date.
SELECT TOP 10 * FROM Appointments ORDER BY appointment_date DESC;
SQL Select Top Selecting a Percentage of Rows Example
This query retrieves the top 20 percent of records from the Patients table, ordered by patient_id.
SELECT TOP 20 PERCENT * FROM Patients ORDER BY patient_id;