SQL (Structured Query Language) is a programming language used to manage and manipulate relational databases. One of the most commonly used SQL commands is SELECT, which is used to retrieve data from a database. The SELECT statement can be used to retrieve all the data from a table or a specific subset of data based on certain conditions. However, sometimes we may want to retrieve only unique values from a column or a combination of columns. This is where the SELECT DISTINCT command comes in handy.
The SELECT DISTINCT command is used to retrieve only unique values from a column or a combination of columns in a table. It eliminates duplicate rows from the result set and returns only distinct values. The syntax for using SELECT DISTINCT is as follows:
SELECT DISTINCT column1, column2, ... FROM table_name;
Here, column1, column2, ... are the names of the columns from which you want to retrieve distinct values, and table_name is the name of the table from which you want to retrieve the data.
For example, let's say we have a table named "employees" with columns "id", "name", "department", and "salary". If we want to retrieve only the distinct department names from the table, we can use the following SQL query:
SELECT DISTINCT department FROM employees;
This will return a list of all the unique department names from the "employees" table.
Let's take a look at some more examples of using SELECT DISTINCT:
Retrieve all the unique values from a single column:
SELECT DISTINCT column1 FROM table_name;
Retrieve all the unique values from multiple columns:
SELECT DISTINCT column1, column2 FROM table_name;
Retrieve all the unique values from a combination of columns:
SELECT DISTINCT CONCAT(column1, '-', column2) FROM table_name;
This will concatenate the values of column1 and column2 with a hyphen (-) and return only the distinct combinations.
Retrieve all the unique values from a column based on a condition:
SELECT DISTINCT column1 FROM table_name WHERE condition;
Here, the WHERE clause is used to specify the condition based on which the distinct values will be retrieved.
SELECT DISTINCT is a powerful SQL command that allows you to retrieve only unique values from a table or a combination of columns. It can be used to eliminate duplicate rows from the result set and return only the distinct values. By using the examples provided in this tutorial, you can easily use SELECT DISTINCT in your own SQL queries to retrieve the data you need.