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 |
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.