In SQL, the SELECT DISTINCT
statement is used to retrieve unique values from a specified column or combination of columns in a table. It filters out duplicate values and returns only distinct (unique) values.
Here's the basic syntax of the SELECT DISTINCT
statement:
SELECT DISTINCT column1, column2, ...
FROM table_name;
In this syntax:
column1, column2, ...
: Columns you want to retrieve distinct values from.table_name
: The name of the table from which you want to retrieve data.Example:
Let's say we have a table named students
with a column class_name
that contains duplicate entries, and we want to retrieve a list of unique class names:
SELECT DISTINCT class_name
FROM students;
This query will return only the distinct (unique) values from the class_name
column of the students
table, eliminating any duplicate values.
You can also use SELECT DISTINCT
with multiple columns to retrieve unique combinations of values. For example, if we have a table named sales
with columns product_id
and customer_id
, and we want to retrieve unique combinations of product_id
and customer_id
:
SELECT DISTINCT product_id, customer_id
FROM sales;
This query will return only the distinct combinations of product_id
and customer_id
from the sales
table.
The SELECT DISTINCT
statement is useful for data analysis and reporting when you want to identify unique values or combinations of values within a dataset. It's important to note that using SELECT DISTINCT
may impact query performance, especially on large tables, as it requires sorting and eliminating duplicates from the result set.