MySQL — Distinct
Basic DISTINCT
SELECT DISTINCT category FROM products;
DISTINCT Multiple Columns
SELECT DISTINCT category, brand FROM products;
DISTINCT Examples
-- Unique categories
SELECT DISTINCT category FROM products;
-- Unique countries
SELECT DISTINCT country FROM users;
-- Count unique values
SELECT COUNT(DISTINCT category) as category_count
FROM products;
-- Unique combinations
SELECT DISTINCT category, brand
FROM products;
-- Unique with condition
SELECT DISTINCT country
FROM users
WHERE is_active = TRUE;
COUNT with DISTINCT
-- Number of unique categories
SELECT COUNT(DISTINCT category) as unique_categories
FROM products;
-- Number of unique customers
SELECT COUNT(DISTINCT user_id) as unique_customers
FROM orders;
Mini Practice
Write MySQL code that:
- Gets distinct values
- Gets distinct combinations
- Counts unique values
- Uses DISTINCT with conditions
Up Next
Next: Learn about Aggregate Functions.
Related Topics
Frequently Asked Questions about Distinct
What is Distinct in MySQL?
Distinct is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Distinct?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Distinct.
Why is Distinct important in MySQL?
Distinct is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.