Selecting unique values with DISTINCT #
A table often has repeated values in a column. The DISTINCT keyword removes duplicate rows from the result, keeping only unique values:
SELECT DISTINCT
column_name
FROM
table;
For example, our customers table has a gender column that only ever contains M or F. Instead of getting the value once per customer, DISTINCT gives us each unique value once:
SELECT DISTINCT
gender
FROM
customers;
DISTINCT applies to the whole row being selected, so if you select multiple columns, only rows where all selected columns match together are treated as duplicates.
Exercise #
We have already created a table products with the columns id, name, category, and price. Write a command that retrieves the distinct list of category values from products.
Tests #
- The result has a
categorycolumn. - The result contains each category value exactly once, with no duplicates.
Solution
SELECT DISTINCT
category
FROM
products;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity