In this lesson, you will learn how to filter out redundant, repeating information to extract only the unique values from your data.
Why Do We Need Unique Data?
Imagine you are looking at a list of customers who have placed orders. In a busy database, the same customer name might appear hundreds of times because they’ve made hundreds of purchases. If you want to create a simple mailing list of every customer who has ever ordered, you don't need the same name listed 100 times—you just need to see each unique name once.
When we query data, the database often returns every matching row, which can lead to a messy, repetitive result set. SQL provides a specific keyword to "clean up" these results and return only distinct values.
Using the DISTINCT Keyword
To remove duplicates from your query results, you place the DISTINCT keyword immediately after SELECT.
Think of DISTINCT as a filter that tells the database: "Look at the entire row I've requested, and if I’ve already seen this exact combination of values, ignore it."
Take a look at this example:
SELECT DISTINCT customer_name
FROM orders;
In this query, even if "Alice Smith" appears in the orders table a thousand times, the result will show "Alice Smith" only once. If you include multiple columns, such as SELECT DISTINCT city, state, the database will return every unique pair of city and state. It will only hide a row if both the city and the state match a previous row exactly.
A Quick Note on Performance
Because the database has to sort through your results to identify and remove duplicates, using DISTINCT can take a little bit of extra processing power on very large tables. Always use it thoughtfully when you truly only need to see the unique values within your dataset.
By mastering this simple keyword, you can quickly turn bloated, repetitive tables into clean, concise reports that tell you exactly who or what exists in your database without the clutter.
Key Takeaway: Use the DISTINCT keyword immediately after SELECT to strip away redundant rows and return only unique values from your database.