Hàm select top 1 from table trong sql năm 2024

CodeLearn is an online platform that helps users to learn, practice coding skills and join the online coding contests.

Links

Learning

Training

Fights

Information

About Us

Terms of Use

Help

Help

Discussion

Powered by CodeLearn © 2024. All Rights Reserved. rev 2/5/2024 5:31:56 PM

The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

Example

Select only the first 3 records of the Customers table:

SELECT TOP 3 * FROM Customers;

Try it Yourself »

Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses FETCH FIRST n ROWS ONLY and ROWNUM.

SQL Server / MS Access Syntax:

SELECT TOP number|percent columnname(s) FROM tablename WHERE condition;

MySQL Syntax:

SELECT columnname(s) FROM tablename WHERE condition LIMIT number;

Oracle 12 Syntax:

SELECT columnname(s) FROM tablename ORDER BY columnname(s) FETCH FIRST number ROWS ONLY;

Older Oracle Syntax:

SELECT columnname(s) FROM tablename WHERE ROWNUM <= number;

Older Oracle Syntax (with ORDER BY):

`SELECT TOP`0


Demo Database

Below is a selection from the Customers table used in the examples:

CustomerID CustomerName ContactName Address City PostalCode Country 1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany 2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico 3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico 4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK 5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden



LIMIT

The following SQL statement shows the equivalent example for MySQL:

Example

Select the first 3 records of the Customers table:

SELECT * FROM Customers LIMIT 3;

Try it Yourself »


FETCH FIRST

The following SQL statement shows the equivalent example for Oracle:

Example

Select the first 3 records of the Customers table:

SELECT * FROM Customers FETCH FIRST 3 ROWS ONLY;


SQL TOP PERCENT Example

The following SQL statement selects the first 50% of the records from the "Customers" table (for SQL Server/MS Access):

The following SQL statement shows the equivalent example for Oracle:

Example

SELECT * FROM Customers FETCH FIRST 50 PERCENT ROWS ONLY;


ADD a WHERE CLAUSE

The following SQL statement selects the first three records from the "Customers" table, where the country is "Germany" (for SQL Server/MS Access):

The following SQL statement shows the equivalent example for MySQL:

The following SQL statement shows the equivalent example for Oracle:

Example

SELECT * FROM Customers WHERE Country='Germany' FETCH FIRST 3 ROWS ONLY;


ADD the ORDER BY Keyword

Add the `SELECT TOP`1 keyword when you want to sort the result, and return the first 3 records of the sorted result.

Ở các bài trước, Kienit đã nói về các mệnh đề liên quan đến câu lệnh SELECT. Câu lệnh SELECT TOP trong SQL là nội dung tiếp theo mình sẽ đề cập trong bài viết này.

1/ Mô tả

Lệnh SELECT TOP trong SQL có nhiệm vụ lấy dữ liệu từ một hoặc nhiều bảng và sẽ trả về số lượng bản ghi được giới hạn bởi giá trị phần trăm cố định hoặc giá trị.

Nếu như bạn muốn lấy ra top n giá trị cao nhất hoặc thấp nhất trong bảng dữ liệu thì hãy dùng câu lệnh SQL này. SELECT TOP sẽ giúp bạn giới hạn số dòng trả về như bạn mong muốn.

2/ Cú pháp

SELECT TOP giatri_dau [PERCENT] [WITH TIES] bieu_thuc

FROM bang

[WHERE dieu_kien]

[ORDER BY bieu_thuc [ ASC | DESC ]]

Trong đó:

SELECT TOP (giatri_dau) có nghĩa là lấy 10 giá trị đầu trong một bảng hoặc nhiều bảng. Ví dụ TOP 10

PERCENT có nghĩa là lấy phần trăm số lượng dòng trong bảng. Ví dụ SELECT TOP 50 PERCENT

WITH TIES có nghĩa là sẽ trả về các dòng có giá trị phù hợp với dòng cuối cùng trong kết quả trả về. Tuy nhiên sẽ trả về nhiều hàng hơn so với biến TOP bạn dùng.

Trường hợp bạn dùng WITH TIES là khi bạn lấy ra n sản phẩm có giá trị nhưng vẫn có sản phẩm khác có giá trị bằng giá trị đã lấy thì bạn dùng biến này để tránh bỏ sót.

Lưu ý: Vì các giá trị ban đầu chưa được sắp xếp theo thứ tự tăng hoặc giảm dần nên khi sử dụng lệnh này bạn nên dùng với mệnh đề ORDER BY trong SQL.

Sau khi đã hiểu được ý nghĩa và cú pháp thì ở phần này mình sẽ đưa ra ví dụ sử dụng SELECT TOP trong SQL cơ bản.

Dùng từ khóa TOP

Ví dụ 1: Lấy 5 dòng dữ liệu đầu tiên trong bảng HoaDon

SELECT TOP(5) * FROM HoaDon

Ví dụ 2: Lấy 3 dòng đầu tiên trong bảng Customer có điều kiện cột Country là Germany

SELECT TOP(3) * FROM Customer WHERE Country = ‘Germany’

Dùng với từ khóa TOP PERCENT

Ví dụ 1: Lấy 1/2 dòng dữ liệu trong bảng Customer

SELECT TOP(50) PERCENT * FROM Customer

Ví dụ 2: Lấy 10% dòng của cột list_price trong bảng products

SELECT TOP(10) PERCENT list_price

FROM products

ORDER BY list_price DESC

Dùng với từ khóa TOP WITH TIES

Ví dụ:

SELECT TOP 1 WITH TIES list_price

FROM products

ORDER BY list_price DESC

Trường hợp dùng với từ khóa TOP WITH TIES rất ít. Trong ví dụ trên, nếu như ngoài 1 dòng có giá trị được lấy ra thì nếu trong nếu có dòng nào khác có giá trị bằng với dòng cuối cùng thì cũng sẽ được lấy ra. Như vậy sẽ giúp bạn không bỏ sót dữ liệu.

Bài viết trên đã chia sẻ các kiến thức cơ bảng về cách sử dụng SELECT TOP trong SQL. Hy vọng bài viết sẽ mang đến những thông tin hữu ích cho những bạn nào đang tìm hiểu về câu lệnh này.