Distinct

In SQL, the DISTINCT keyword is used to retrieve unique values from a table or a result set. It is often used in conjunction with the SELECT statement to filter out duplicate rows.

Syntax

The syntax for using DISTINCT is as follows:

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

In this syntax, the column names refer to the columns that you want to retrieve unique values from. The table name refers to the table that contains the data you want to query.

When you use DISTINCT, SQL returns only one instance of each unique value in the specified columns. If there are multiple instances of a value in the specified columns, only one instance will be returned.

Example

For example, consider the following table called “customers”:

customer_id customer_name city
1 John Smith New York
2 Jane Doe Chicago
3 John Smith Los Angeles
4 Sarah Johnson Miami
5 Jane Doe San Francisco

If you want to retrieve a list of unique customer names from this table, you could use the following SQL query:

SELECT DISTINCT customer_name
FROM customers;

The result of this query would be:

customer_name
John Smith
Jane Doe
Sarah Johnson

Note that the city column was not included in the query, so it does not appear in the result set. Also, even though there were multiple instances of John Smith and Jane Doe in the table, each customer name appears only once in the result set.

In summary, the DISTINCT keyword is a useful tool for retrieving unique values from a table or result set. By using DISTINCT in conjunction with the SELECT statement, you can easily filter out duplicate rows and focus on the unique values that are important for your analysis.