Mastering Data Uniqueness: The DISTINCT Clause in SQL
Learn how to filter out duplicate records and retrieve unique values using SQL's DISTINCT clause.
What is the DISTINCT Clause?
The DISTINCT clause in SQL is used to remove duplicate rows from a query result, ensuring that only unique values are returned.
Basic Usage
The simplest way to use DISTINCT is with a single column.
-- Basic DISTINCT usage
SELECT DISTINCT country FROM customers;
Using DISTINCT with Multiple Columns
DISTINCT can also be applied to multiple columns, filtering out duplicate row combinations.
-- DISTINCT with multiple columns
SELECT DISTINCT country, city FROM customers;
DISTINCT vs. GROUP BY
In some cases, GROUP BY can achieve the same result as DISTINCT.
-- Using GROUP BY instead of DISTINCT
SELECT category FROM products GROUP BY category;
DISTINCT with Aggregate Functions
You can use DISTINCT inside aggregate functions like COUNT to count unique values.
-- Using DISTINCT with COUNT
SELECT COUNT(DISTINCT customer_id) AS unique_customers FROM orders;