SQL SELECT DISTINCT

What is the SELECT DISTINCT Statement?

The SELECT DISTINCT statement is used to retrieve unique values from a column in a table. It filters out duplicate values and returns only distinct records.

The basic syntax for the SELECT DISTINCT statement is:

SELECT DISTINCT column1, column2, ...
FROM table_name;

Here, only distinct (unique) values for the specified columns will be returned.

Example: Products Table

Consider the following Products table:

ProductID ProductName Category Price
1 Laptop Electronics $1000
2 Mouse Electronics $20
3 Chair Furniture $150
4 Laptop Electronics $950
5 Desk Furniture $200

Using SELECT DISTINCT

To get a list of unique product categories from the Products table, you can use the following SQL query:

SELECT DISTINCT Category
FROM Products;

This query returns the distinct categories in the Products table, like Electronics and Furniture.

Selecting Multiple Distinct Columns

You can also select distinct values from multiple columns. For example, to get a list of unique product names and their categories, use the following query:

SELECT DISTINCT ProductName, Category
FROM Products;

This query will return unique combinations of product names and categories.

Example Output

The following would be the result of the query:

ProductName Category
Laptop Electronics
Mouse Electronics
Chair Furniture
Desk Furniture