This SQL tutorial explains how to use the SQL DISTINCT clause with syntax and examples.
The SQL DISTINCT clause is used to remove duplicates from the result set of a SELECT statement.
The syntax for the SQL DISTINCT clause is:
SELECT DISTINCT expressions
Parameters or Arguments
- The columns or calculations that you wish to retrieve.
- The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
- WHERE conditions
- Optional. The conditions that must be met for the records to be selected.
- When only one expression is provided in the DISTINCT clause, the query will return the unique values for that expression.
- When more than one expression is provided in the DISTINCT clause, the query will retrieve unique combinations for the expressions listed.
- In SQL, the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL statement, your result set will include NULL as a distinct value.
Example - With Single field
Let's look at the simplest SQL DISTINCT query example. We can use the SQL DISTINCT clause to return a single field that removes the duplicates from the result set.
SELECT DISTINCT city
This SQL DISTINCT example would return all unique city values from the suppliers table.
Example - With Multiple fields
Let's look at how you might use the SQL DISTINCT clause to remove duplicates from more than one field in your SQL SELECT statement.
SELECT DISTINCT city, state
This SQL DISTINCT clause example would return each unique city and state combination. In this case, the DISTINCT applies to each field listed after the DISTINCT keyword.