DISTINCT Keyword

The DISTINCT keyword retrieves unique values or records from a table, eliminating duplicates. It is applied with the SELECT statement to obtain unique values of one or more columns. Consider a sales table with customer ID, name, product, and price. To find the unique products in the sales table, we can use the DISTINCT keyword.

Syntax:

SELECT DISTINCT column(s) FROM table_name

DISTINCT vs GROUP BY in SQL

SQL (Structured Query Language) is used to manage and manipulate the data in relational databases. It can be used for tasks such as database querying, data editing, database and table creation and deletion, and granting user permissions.

We can use the DISTINCT keyword and GROUP BY clause when we want to obtain the unique records of a table in SQL. Even though their purpose is the same, they are used in various ways and they also function differently.

Similar Reads

DISTINCT Keyword

The DISTINCT keyword retrieves unique values or records from a table, eliminating duplicates. It is applied with the SELECT statement to obtain unique values of one or more columns. Consider a sales table with customer ID, name, product, and price. To find the unique products in the sales table, we can use the DISTINCT keyword....

GROUP BY

The GROUP BY clause groups similar or identical values in a table and is used with aggregate functions like AVG(), SUM(), MAX(), MIN(), COUNT(), etc. It is employed with the SELECT statement and is positioned after the WHERE clause. Unlike DISTINCT, GROUP BY doesn’t directly remove duplicate records; instead, it groups similar values into sets and applies aggregate functions....

Examples of DISTINCT and GROUP BY in SQL

Let’s take a closer look at the functionality and use cases of GROUP BY and DISTINCT using a simple example in MySQL....

DISTINCT vs GROUP BY in SQL

Feature DISTINCT GROUP BY Used for Unique values from a single column Grouped data (by one or more columns) along with aggregate function calculation. Syntax SELECT DISTINCT column1 FROM table_name; (multiple columns can be added) SELECT column1 aggregate_function(column_name) FROM table_name GROUP BY column1; (multiple columns can be added) Goal Removes duplicate rows from the result Groups rows based on specified columns, and use aggregate functions Columns in SELECT Include only the column(s) for which uniqueness is desired Include columns specified in group by clause as well as columns for which aggregate functions are applied...

Conclusion

In conclusion, DISTINCT and GROUP BY in SQL, though serving the common purpose of obtaining unique records, are applied differently. DISTINCT is suitable for obtaining unique values from one or more columns, while GROUP BY is employed for grouping data based on one or more columns along with aggregate function calculations. Understanding when to use each is crucial for crafting efficient and effective SQL queries....