DISTINCT Clause - ( SQL Server Clauses )
In SQL, the DISTINCT
clause is used to return only distinct (unique) values from a query. It removes duplicate rows from the query results.
Syntax
The basic syntax for DISTINCT
clause is as follows:
SELECT DISTINCT column1, column2, ...
FROM table_name
WHERE condition;
DISTINCT
keyword is used to remove the duplicates.column1, column2, ...
are the columns to be retrieved.table_name
is the table name from which the data is to be retrieved.WHERE
is an optional clause to filter the results.
Example
Let's take an example of a students
table:
id | name | age | course |
---|---|---|---|
1 | Alice | 20 | Science |
2 | Bob | 19 | Arts |
3 | Charlie | 21 | Science |
4 | David | 19 | Commerce |
5 | Eve | 20 | Arts |
SELECT DISTINCT course FROM students;
The query above returns the unique values from the course
column:
course |
---|
Science |
Arts |
Commerce |
Output
The output of the query is a table containing distinct values of the selected columns.
Explanation
The DISTINCT
clause is used to filter out the duplicate values from the query result. The SELECT
statement selects the specified columns from the specified table, and the DISTINCT
clause ensures that only unique values are returned for the specified columns.
Use
Use the DISTINCT
clause when you want to remove duplicates or retrieve only the unique values from a query.
Important Points
- The
DISTINCT
keyword is used to remove duplicate rows from the query results. - The
DISTINCT
keyword is used in conjunction with theSELECT
statement to select the specified columns from the specified table. - The
DISTINCT
clause is used when you want to get unique values for the specified columns.
Summary
In this page, we discussed DISTINCT
clause in SQL Server Clauses. We covered the syntax, example, output, explanation, use, important points, and summary of DISTINCT
clause. The DISTINCT
clause is used to select only unique values from a table or set of tables when running a query. It is useful in situations where you need to eliminate duplicates from the result set.