SQL offers a DISTINCT command to provide a convenient way for us to select only one element without duplication.
Let's learn by an example:
SELECT DISTINCT p1.email FROM Person p1, Person p2
WHERE p1.email = p2.email AND p1.id <> p2.id
SELECT defines you want to show in the output.
DISTINCT enables you to select only one element without duplication.
p1.email means you want to show the p1's email in the output.
FROM means retrieving data from Person table and assigns it to p1 and p2 respectively.
WHERE filters your target data by condition.
p1.email = p2.email is the first condition, which is used to filter out the candidates that share the same email address.
AND states the second necessary condition p1.id <> p2.id.
It ensures that p1 and p2 would not be the same person.
In this way, we will find the output to be:
+---------+
| Email |
+---------+
| h@p.com |
+---------+
Congratulations on completing this tutorial!
Don't hesitate to continue exploring SQL and experimenting with different scenarios.
See you in SQL (4)!
© 2023 Harmony Pang. All rights reserved.
Comentários