FizzBuzz in PostgreSQL

95 views Asked by At

You need to write a query that outputs a sequence of digits from 1 to 1000.

If the number is a multiple of three, then Fizz is output instead of a number. If it is a multiple of five, then Buzz, and if both three and five, then FizzBuzz.

My pseudocode:

SELECT
   CASE
     WHEN (BETWEEN 1 AND 1000)% 3 = 0 THEN "Fizz",
     WHEN (BETWEEN 1 AND 1000)% 5 = 0 THEN "Buzz",
     WHEN (BETWEEN 1 AND 1000)% 5 = 0 AND WHEN (BETWEEN 1 AND 1000)% 3 = 0 THEN "FizzBuzz",
   END
2

There are 2 answers

0
Trung Duong On BEST ANSWER

You could try this query

SELECT
   n,
   CASE
     WHEN MOD(n,15) = 0 THEN 'FizzBuzz'
     WHEN MOD(n,3) = 0 THEN 'Fizz'
     WHEN MOD(n,5) = 0 THEN 'Buzz' 
     ELSE ''
   END
FROM generate_series(1,1000) n

See demo here

0
Zegarek On

Plain case statement:

select case when num%15=0 then 'FizzBuzz' 
            when num%3 =0 then 'Fizz'
            when num%5 =0 then 'Buzz'
            else num::text
       end
from generate_series(1,1000,1) AS gen(num);

Array of options, cases cast to indices:

select (ARRAY[num::text,'Fizz','Buzz','FizzBuzz'])[ 1 +(num%3=0)::int +2*(num%5=0)::int]
from generate_series(1,1000,1) AS gen(num);

A combination of coalesce() with an array, keeps a static array without constructing it or prepending to it:

select coalesce( ('{Fizz,Buzz,FizzBuzz}'::text[])[ (num%3=0)::int +2*(num%5=0)::int ] 
                , num::text)
from generate_series(1,1000,1) AS gen(num);

coalesce() of self-nullifying values:

select coalesce(case when num%15=0 then 'FizzBuzz' end,
                case when num%3 =0 then 'Fizz'     end,
                case when num%5 =0 then 'Buzz'     end,
                num::text)
from generate_series(1,1000,1) AS gen(num);

NATURAL LEFT JOIN+SRF:

select coalesce( f||b, f, b, a.num::text)
from    generate_series(1,1000,1)                AS a(num) natural left join 
(select generate_series(3,1000,3) num, 'Fizz' f) AS f      natural left join 
(select generate_series(5,1000,5) num, 'Buzz' b) AS b

demo