Hello, coders! 💻
Today's quiz taken from a real world task is SQL related.
Database structure
There are two tables (very simplified for the sake of this quiz):
-
companies
with two columns:id
andname
-
users
with two columns:company_id
andis_pro
(boolean)
Task
write a query to find all companies that only have pro users (
is_pro=1
).
My take on this
Click to see my solution using MySQL
SELECT
c.name as company
FROM
users u
JOIN companies c ON
c.id = u.company_id
GROUP BY
c.id
HAVING
SUM(IF(is_pro, 0, 1)) = 0;
IF(is_pro, 0, 1)
means that I give 0 points to users that are pros (counter-intuitive but bear with me!). If all users are pros then the sum of points should be 0, right? That's what HAVING IF(is_pro, 0, 1)) = 0
does.
There you have it!
How would you have done it?
📝 Edit
As pointed out by @geraldew using SUM
to COUNT
is hacky and as such I'd better use COUNT
and CASE
:
SELECT
c.name as company,
COUNT(
CASE WHEN can_use_app = 1 THEN 'x'
END
) isPro,
COUNT(
CASE WHEN can_use_app = 0 OR can_use_app IS NULL THEN 'x'
END
) isNotPro
FROM
users u
JOIN companies c ON
c.id = u.company_id
GROUP BY
c.id
HAVING
isPro > 0 and isNotPro = 0;
Happy coding! ⌨️
I don't know which SQL dialects have such an IF function (none that I use do), so my question is: what happens when is_pro is null?