Selecting unique values from a column
To identify unique entries in a column, use the DISTINCT
clause like this:
This command lists each distinct value in column_name
, removing duplicates like a pro.
For a more practical scenario, if you have a transaction log and need to know the unique dates on which sales took place:
Not only does this command pull unique dates, but it also organizes them in descending order because sometimes we all like to go back in time.
SQL tactics and performance tricks
Sorting unique values
Sorting the unique values can be accomplished by adding an ORDER BY
after the DISTINCT
clause:
Use ASC
for ascending or DESC
for descending order.
GROUP BY
or DISTINCT
Remember that DISTINCT
is your friendly neighbourhood uniquer, but if you're also aggregating data, GROUP BY
should be your hero:
This statement shows distinct values and counts occurrences because who doesn't like good data insights.
Making use of aliases
For more readability especially in intricate queries, AS
can be your best friend to create aliases:
With aliases, your value's purpose becomes clear as a summer day.
Efficiency is key
- Check the table/column names. We all make mistakes.
- Specify column names instead of wildcards (
SELECT *
) to optimize the performance. - Test your queries. Make sure they behave like well-trained pets.
- Refer to official documentation for advanced performance tips.
Keeping your data in check
Matching data types
Ensure columns chosen for DISTINCT
are compatible with it. Mismatched types can lead to wonky results.
Case sensitivity
SQL is usually case-insensitive. Ensure your database appreciates the difference between Flower
and flower
.
Dealing with NULL
DISTINCT
treats NULL as a separate value. If NULLs are in your column, they will stand out in results.
Using subqueries
DISTINCT
can be used in subqueries to make your larger query clean:
This returns rows with unique values only.
Was this article helpful?