This tutorial will explain how to use top from a SQL query and how to use them with the examples.
Top keyword is used to retrieve n number of records from the resultset.
This is the general statement to retrieve n number of records from a table
SELECT TOP (expression)
column1, column2, column3
FROM
tablename
ORDER BY
column1
Lets create a sample table and add some rows
CREATE TABLE SampleContacts (
FullName VARCHAR(50) NOT NULL,
Gender CHAR(1) NOT NULL,
Age INT NOT NULL
);
INSERT INTO SampleContacts
(FullName, Gender, Age)
VALUES
('Contact1', 'M', 26),
('Contact2', 'M', 29),
('Contact3', 'F', 27),
('Contact4', 'F', 28),
('Contact5', 'F', 25),
('Contact6', 'M', 24)
The following example lists 3 youngest contact records.
SELECT TOP 3
FullName, 'M', Age
FROM
SampleContacts
ORDER BY
Age ASC;
The following example lists half percent of the total contacts and youngest records.
SELECT TOP 50 PERCENT
FullName, 'M', Age
FROM
SampleContacts
ORDER BY
Age ASC;