The DISTINCT keyword in SQL is used to return only unique (different) values in a result set. This can be applied to a single column or multiple columns to eliminate duplicates.
To select unique values from a column, use the following syntax:
SELECT DISTINCT column1 FROM table_name;
For example: SELECT DISTINCT country FROM Customers; will return a list of unique countries from the Customers table.
You can also use DISTINCT with more than one column. This will return unique combinations of values from the specified columns.
SELECT DISTINCT city, country FROM Customers;
This example will return unique combinations of city and country from the Customers table.
The DISTINCT keyword is particularly useful when you want to eliminate duplicate records in your result set.
SELECT DISTINCT city FROM Customers;
This query will only return the unique city values from the Customers table, eliminating any repeated city entries.
Using DISTINCT can be resource-intensive, especially if your table contains a large number of records. Always consider the performance impact when using DISTINCT with large datasets.
If possible, try to optimize your query or reduce the number of rows returned by other means, like using WHERE clauses or indexing columns.
Be mindful of using DISTINCT in large tables. Sometimes, eliminating duplicates in the database itself (e.g., during data entry or validation) may be a better solution.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!