In SQL, the SELECT DISTINCT statement is used to retrieve unique values from a specified column or a set of columns in a table. When you use DISTINCT, duplicate rows are excluded from the result set, and only unique combinations of values are returned.
Basic Syntax:
column1,column2, etc., are the columns you want to retrieve unique values for.table_nameis the name of the table you're querying from.
Examples:
1. Get Unique Values from a Single Column:
If you want to get all unique values from a single column, use:
For example:
This query will return all unique cities from the customers table.
2. Get Unique Combinations of Multiple Columns:
If you specify multiple columns, the combination of values in those columns will be considered for uniqueness.
For example:
This query will return all unique combinations of first_name and last_name from the employees table.
3. Distinct with WHERE Clause:
You can combine DISTINCT with other SQL clauses like WHERE to filter the results.
This query will return unique cities from the customers table where the country is 'USA'.
4. Distinct with Aggregate Functions:
You can also use DISTINCT with aggregate functions like COUNT(), SUM(), etc. For example, to count the number of unique cities in the customers table:
This will return the number of distinct cities.
Important Notes:
DISTINCTaffects the entire result set, so it considers the uniqueness of the entire row (or combination of columns) in the result.- Using
DISTINCTcan impact query performance, especially on large datasets, since the database has to perform additional work to eliminate duplicates.
No comments:
Post a Comment