Tuesday, December 17, 2024

SQL SELECT DISTINCT Statement

 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:

SELECT DISTINCT column1, column2, ... FROM table_name;
  • column1, column2, etc., are the columns you want to retrieve unique values for.
  • table_name is 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:

SELECT DISTINCT column_name FROM table_name;

For example:

SELECT DISTINCT city FROM customers;

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.

SELECT DISTINCT column1, column2 FROM table_name;

For example:

SELECT DISTINCT first_name, last_name FROM employees;

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.

SELECT DISTINCT city FROM customers WHERE country = 'USA';

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:

SELECT COUNT(DISTINCT city) FROM customers;

This will return the number of distinct cities.

Important Notes:

  • DISTINCT affects the entire result set, so it considers the uniqueness of the entire row (or combination of columns) in the result.
  • Using DISTINCT can impact query performance, especially on large datasets, since the database has to perform additional work to eliminate duplicates.

No comments:

Post a Comment