SELECT TOP command in SQL Server

In SQL Server, the SELECT TOP command is used to retrieve records from one or more tables in SQL Server and limit the number of return records based on a fixed value or percentage.

In SQL Server, the SELECT TOP command is used to retrieve records from one or more tables in SQL Server and limit the number of return records based on a fixed value or percentage.

Syntax SELECT TOP command

 SELECT TOP (giatri_dau) [PERCENT] [WIT H TIES] 
bieu_thuc
FROM bang
[WHERE dieu_kien]
[ORDER BY bieu_thuc [ ASC | DESC ]];

Variable name or variable value

TOP (giatri_dau)

Returns results based on giatri_dau. For example, TOP (10) will insert the first 10 rows from the result set.

PERCENT

Option. If specified, the first rows are based on the percentage of giatri_dau of the result set. For example, TOP (10) PERCENT will insert 10% of the first value in the result set.

WITH TIES

Option. If this clause is used, rows with the same value as the last row in the result set will be returned. This may result in a situation where the number of rows returned is more than making TOP allow.

bieu_thuc

The column or calculated value should be retrieved

state

Table wants to get records from there. Must have at least 1 table in the FROM clause.

WHERE dieu_kien

Option. Conditions must be met for the record to be selected.

ORDER BY bieu_thuc

Option. Use to order results. ASC in ascending order, DESC in descending order.

For example - use the keyword TOP

 SELECT TO P(5) 
nhanvien_id, ho, ten
FROM nhanvien
WHERE ho = 'Anderson'
ORDER BY nh anvien_id;

The example above will retrieve the first 5 records on the table when the last name is Anderson. If the other records also have the family name of Anderson, they are not returned in the SELECT statement.

The above example can be edited a bit by adding the WITH TIES clause

 SELECT TOP (5 ) WITH TIES 
nhanvien_id, ho, ten
FROM nhanvien
WHERE ho = 'Anderson'
ORDER BY nhanv ien_id;

This example will return the same rows as the last row in the result set.

For example - use the keyword TOP PERCENT

 SELEC T TOP(10) PERCENT 
nhanvien_id, ho, ten
FROM nhanvien
WHERE ho = 'Anderson'
ORDER B Y nhanvien_id;

This example will return the first 10% result set recorded in the employee table among the employees whose last name is Anderson. The remaining 90% will not be returned.

 SELECT TO P(10) PERCENT WITH TIES 
nhanvien_id, ho, ten
FROM nhanvien
WHERE ho = 'Anderson'
ORDER BY nha dentist_id;

With WITH TIES, the returned result will have the same rows as the last row in the result set. The result set will then be more than 10%.

Previous article: HAVING clause in SQL Server

The following article: SELECT INTO command in SQL Server

4.5 ★ | 2 Vote