DISTINCT clause in SQL Server
The DISTINCT clause is used to remove duplicates in the result set.
In SQL Server (Transact-SQL), the DISTINCT clause is used to remove duplicates in the result set. The DISTINCT clause can only be used in the SELECT statement.
DISTINCT clause syntax
SELECT DISTRINCT 'biểu thức'
FROM 'bảng'
[WHERE 'điều kiện'];
Variable name or variable value
'expression'
The column or calculated value you want to retrieve
'table'
Table used to retrieve records. Must have at least 1 table in the FROM clause.
WHERE 'condition'
Option. Conditions that the record must meet to be selected.
Note
- When the DISTINCT clause has only one expression, the query returns unique values for that expression.
- When the DISTINCT clause has more than 1 expression, the query returns the unique combination of expressions.
In SQL Server, the DISTINCT clause does not ignore the NULL value. So when using this clause in the command, the returned result will have a unique NULL value.
Example - 1 expression
The simplest example with the DISTINCT clause in SQL Server has only one expression.
SELECT DISTINCT ho
FROM nhanvien
WHERE nhanvien_id >= 50;
This example will return all employee surname values from the table with the table number greater than or equal to 50.
For example - multiple expressions
SELECT DISTINCT ten, ho
FROM nhanvien
WHERE nhanvien_id >= 50
ORDER BY ho;
In this example, the returned result will be the combination of the first and last name from the table when the value is greater than or equal to 50. The result is sorted in ascending order of the employee.
In this case, DISTINCT applies to each information field behind the DISTINCT keyword, so it will create different name combinations - they are different.
Previous article: Combine AND and OR conditions in SQL Server
Next article: IN conditions in SQL Server
Discover more
MS SQL Server SQL Server DISTINCT mssqlShare by
David PacYou should read it
- DELETE TOP command in SQL Server
- WHERE clause in SQL Server
- Instructions for deleting duplicate contacts on Android
- GROUP BY clause in SQL Server
- FUNCTION (Function) in SQL Server
- The Quiet Details That Make a Sports Betting Platform Feel Reliable
- Instructions on creating toy set images with ChatGPT AI
- How are AI agents changing the journalism industry?
- Introduction to SQL Server Reporting Services
- Instructions for creating and editing reports in SQL Server Reporting Services
- SQL Server setup is always available