Search code examples
postgresqlfizzbuzz

FizzBuzz in PostgreSQL


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

Solution

  • 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