0

I have the following query:

SELECT (COUNT(DISTINCT CASE WHEN houses.level = 'top' THEN users.id END)::float / NULLIF(COUNT(DISTINCT users.id)::float, 0)) 
FROM users
LEFT JOIN houses ON houses.user_id = users.id

And instead of a ratio, I want to return a percentage, so I changed it to:

SELECT (COUNT(DISTINCT CASE WHEN houses.level = 'top' THEN users.id END)::float / NULLIF(COUNT(DISTINCT users.id)::float, 0)) * 100
FROM users
LEFT JOIN houses ON houses.user_id = users.id

However, if the denominator (NULLIF(COUNT(DISTINCT users.id)::float, 0)) returns null, it means I will be multiplying NULL * 100. How can I just return NULL without multiplying if the denominator is 0 (and therefore null because of the NULLIF).

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

2 Answers2

2

It's ok to multiply an INT with NULL. The result will still be NULL.

Try it yourself:

SELECT NULL * 100
Nobita
  • 23,519
  • 11
  • 58
  • 87
0

If you want NULL to represent 0%, use COALESCE:

SELECT COALESCE((COUNT(DISTINCT CASE WHEN houses.level = 'top' THEN users.id END)::float / NULLIF(COUNT(DISTINCT users.id)::float, 0)) * 100, 0) ...

COALESCE returns the first non-null thing it encounters, working from left to right

Otherwise, go for what Nobita recommends ; let null be null

Caius Jard
  • 72,509
  • 5
  • 49
  • 80