Day 69 – SQL SELECT DISTINCT Keyword
SQL SELECT DISTINCT keyword is used to retrieve unique or distinct values from a table. The SELECT DISTINCT statement is useful when you want to eliminate duplicate rows from the result set returned by a SELECT statement.
The basic syntax for using the SELECT DISTINCT keyword is as follows:
SELECT DISTINCT column1, column2, ... FROM table_name WHERE condition;
column2, … are the names of the columns whose unique values will be retrieved, and
table_name is the name of the table from which the values will be retrieved. The
WHERE clause is optional and can be used to filter the rows that will be included in the result set.
For example, to retrieve the unique values from a column named “City” in a table named “Customers”, the SQL statement would be:
SELECT DISTINCT City FROM Customers;
This would retrieve all unique values from the “City” column in the “Customers” table.
Alternatively, to retrieve the unique values from two columns named “City” and “Country” in a table named “Customers”, the SQL statement would be:
SELECT DISTINCT City, Country FROM Customers WHERE Country = 'USA';
This would retrieve all unique combinations of values from the “City” and “Country” columns in the “Customers” table, but only for customers who live in the United States.
It’s important to note that the SELECT DISTINCT statement may be slower than a regular SELECT statement because it requires the database to compare and eliminate duplicate rows. Therefore, it’s recommended to use the SELECT DISTINCT statement only when necessary and to use appropriate indexing and query optimization techniques to improve performance.