SQL SELECT DISTINCT |
SQL Sample Code - SQL SELECT DISTINCT |
| SELECT DISTINCT column_name(s) FROM table_name; |
See the SQL samples section below for an explanation.
What does the SQL SELECT DISTINCT Statement do? |
Columns of database tables often contain duplicate values. You may however only want to retrieve a list of unique or ‘distinct’ values from a column(s) rather than a list of all the values including the duplicates.
Adding the DISTINCT keyword to the SELECT statement allows you to retrieve each distinct or different values.
The result is stored in a result table.
Sample – SQL SELECT DISTINCT |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town |
| 1 | SQL Sample | 1 Sample St | Hamburg |
| 2 | SQL Code Land | 2 Code Rd | Hamburg |
| 3 | Sample Code World | 66 SQL St | Curry |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa |
In order to retrieve the distinct values from the ‘Town’ column from the table ‘tblCompany’ above.
Use the SELECT statement below:
| SELECT DISTINCT Town FROM tblCompany; |
Use the SELECT statement below:
The table of results will look like this:
| Town |
| Hamburg |
| Curry |
| Pisa |
Notes: The SQL standard allows the DISTINCT keyword for SUM(), AVG(), and COUNT(). Some database vendors also provide DISTINCT for Count(*)(all columns); it must be used for DISTINCT (column).
Related SQL Sample Code:
|
|