FizzBuzz in SQL

less than 1 minute read

The expected output is:

 x  β”‚  value
════β•ͺ══════════
 1  β”‚ 1
 2  β”‚ 2
 3  β”‚ fizz
 4  β”‚ 4
 5  β”‚ buzz
 6  β”‚ fizz
 7  β”‚ 7
 8  β”‚ 8
 9  β”‚ fizz
 10 β”‚ buzz
 11 β”‚ 11
 12 β”‚ fizz
 13 β”‚ 13
 14 β”‚ 14
 15 β”‚ fizzbuzz
 16 β”‚ 16
 17 β”‚ 17
 18 β”‚ fizz
 19 β”‚ 19
 20 β”‚ buzz
 21 β”‚ fizz
 22 β”‚ 22
 23 β”‚ 23
 24 β”‚ fizz
 25 β”‚ buzz
 26 β”‚ 26
 27 β”‚ fizz
 28 β”‚ 28
 29 β”‚ 29
 30 β”‚ fizzbuzz

And the sql is:

select
    x::varchar,
    case
      when (x % 15 = 0) then
        'fizzbuzz'
      when (x % 3 = 0) then
        'fizz'
      when (x % 5 = 0) then
        'buzz'
      else
        x::varchar
    end as "value"
  from generate_series(1, 50) t(x)
;

Categories:

Updated: