SQL Select Distinct
The SQL SELECT DISTINCT (Different Values) statement is used to retrieve unique values from a specific column or set of columns in a database table. It eliminates duplicate rows and returns only distinct (different value) or unique value only.
Below is an explanation of SELECT DISTINCT with an example:
The syntax of the SELECT DISTINCT statement is as follows:
SELECT DISTINCT column1, column2, column3 FROM table_name WHERE condition;
SELECT DISTINCT: This combination of keywords indicates that you want to retrieve unique values from one or more columns.
column1,column2,column3: These are the names of the columns from which you want to retrieve unique values. You can specify one or more columns, separated by commas (,).
FROM: This keyword specifies the table from which you want to retrieve data.
table_name: This is the name of the table where the data is stored.
WHERE (optional): This clause allows you to filter the data based on specific conditions. It’s used to limit the selection of distinct values.
condition (optional): This is the condition that determines which rows are included in the result. It’s typically expressed using comparison operators
like =, <, >, <=, >=, and logical operators like AND, OR, and NOT.
Example of a SQL SELECT DISTINCT statement:
Suppose we have a table called products with the following data:
product_id product_name category
1 Laptop Electronic
2 Tablet Electronic
3 T-shirt Clothing
4 Laptop Electronic
5 Jeans Clothing
If you want to retrieve a list of distinct product categories from this table, you can use the SELECT DISTINCT statement like this:
SELECT DISTINCT category FROM products;
The result of this query would be:
category
Electronics
Clothing
In this example,
We specified the column category from which we want to retrieve distinct values.
We specified the products table from which we want to retrieve data.
The SELECT DISTINCT statement ensures that only unique values from the category column are returned, eliminating duplicates.
So, the SELECT DISTINCT statement is useful when you want to find unique values in a specific column, which can be particularly valuable for generating summary reports or getting a list of unique categories, as shown in this example.