Explain ‘SQL SELECT DISTINCT’ with an Example

The SQL SELECT DISTINCT statement is used to retrieve unique or distinct values from a specified column or a combination of columns in a table. It eliminates duplicate rows in the result set, returning only unique values. Here’s an explanation of the SQL SELECT DISTINCT statement with an example:

Syntax:

SELECT DISTINCT column1, column2, ...
FROM table_name
WHERE condition;

Example:
Consider a table called “Orders” with the following columns: “OrderID,” “CustomerID,” and “ProductID.” Let’s say we want to retrieve the distinct customer IDs from the “Orders” table.

SELECT DISTINCT CustomerID
FROM Orders;

In this example, the SELECT DISTINCT statement retrieves unique values from the “CustomerID” column of the “Orders” table. The result set will contain only distinct customer IDs, eliminating any duplicate entries.

The DISTINCT keyword is applied to the specified column (or columns) in the SELECT statement, instructing the database to consider only unique values for that column. It ensures that each value appears only once in the result set, regardless of the number of occurrences in the original table.

It’s important to note that the SELECT DISTINCT statement can be combined with other clauses like WHERE to apply conditions for further filtering of data. For instance, you can add a WHERE clause to retrieve distinct customer IDs only for orders placed after a specific date.

Overall, the SELECT DISTINCT statement is useful when you want to retrieve unique values from a column or a combination of columns in a table. It allows you to eliminate duplicates and focus on the distinct values present in the data.

Run Code In Live & Test

Leave a Reply

Your email address will not be published. Required fields are marked *