AdBlock Detected!
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.
SQL DISTINCT |
|
SQL > SQL Commands >
Distinct
In SQL, the DISTINCT keyword is used in the SELECT statement to retrieve unique values from a database table. Any value that has a duplicate will only show up once.
Key Takeaway: Use SELECT DISTINCT when you want a list of unique values and don't need aggregation. It removes duplicate rows so each unique combination of selected columns appears only once.
Syntax"table_name" is the name of the table where data is stored, and "column_name" is the name of the column containing the data to be retrieved. ExamplesThe examples will use the following table: Table Store_Information
Example 1: Use DISTINCT on one columnTo select all distinct stores in Table Store_Information, we key in, Result:
Example 2: Use DISTINCT on multiple columnsWe can apply DISTINCT to multiple columns. If we want to get a list showing all unique combinations of stores and transaction dates, we would type in the following, Result:
ExercisesFor these exercises, assume we have a table called Users with the following data: Table Users
1. Which of the following SQL statement is valid?
2. What's the result of the following query?
3. What's the result of the following query?
Frequently Asked QuestionsDoes DISTINCT apply to all columns or just one?DISTINCT applies to all columns listed after it in the SELECT clause. It returns rows where the combination of ALL selected columns is unique — not just the first column. Is SELECT DISTINCT slower than SELECT?Yes, typically. DISTINCT requires the database to sort or hash all rows to identify duplicates, which adds overhead. For large tables, consider whether GROUP BY might be more efficient. Can I use DISTINCT with aggregate functions?Yes. For example, What is the difference between DISTINCT and UNIQUE?In SQL queries, DISTINCT is used in SELECT to filter duplicate rows. UNIQUE is a constraint used when creating a table to ensure a column does not contain duplicate values. |
Our website is made possible by displaying ads to our visitors. Please supporting us by whitelisting our website.