sql_distinct
SQL SELECT DISTINCT: Retrieving Unique Values
Section titled “SQL SELECT DISTINCT: Retrieving Unique Values”The SELECT DISTINCT statement is used to return only unique (different) values for one or more specified columns. It automatically filters out duplicate rows from your result set.
The Power of SELECT DISTINCT
Section titled “The Power of SELECT DISTINCT”In a table, a column (or a combination of columns) might contain many duplicate values. Sometimes, you only need a list of the unique values present. For example, you might want to find all unique countries where your customers are located, or all unique product categories you offer.
The DISTINCT keyword, when added to a SELECT statement, instructs the database to eliminate these duplicate rows before returning the results.
SQL SELECT DISTINCT Syntax
Section titled “SQL SELECT DISTINCT Syntax”SELECT DISTINCT column1, column2, ...FROM table_nameWHERE condition; -- Optional: to filter rows before finding distinct valuesWhen DISTINCT is applied to multiple columns, a row is considered a duplicate only if all selected columns have identical values to another row.
Demonstration Database: Northwind
Section titled “Demonstration Database: Northwind”We’ll continue using the Northwind sample database.
Here’s a selection from the “Customers” table:
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK
5Berglunds snabbköpChristina BerglundBerguvsvägen 8LuleåS-958 22SwedenSELECT DISTINCT Example: Listing Unique Cities
Section titled “SELECT DISTINCT Example: Listing Unique Cities”The following SQL statement selects only the unique values from the “City” column in the “Customers” table:
SELECT DISTINCT CityFROM CustomersORDER BY City; -- Optional: to sort the unique cities alphabeticallyPractical Application: This is useful for populating dropdown lists in user interfaces, understanding the geographical distribution of customers without redundancy, or identifying all unique product types sold.
Performance Note: Using DISTINCT can have performance implications, especially on large tables without appropriate indexes, as the database needs to sort or hash the data to identify duplicates. Use it judiciously.