FizzBuzz – My Approach

I’m sure you’re aware of the classic FizzBuzz interview question. The issue has always been on a simple way of populating the 100 rows of data, I’ve seen approaches with temp tables, cursors and loops. I don’t like these types of approach as they cause unnecessary overhead.

Here’s my take on the problem;


SELECT
    CASE WHEN a % 5 = 0 AND a % 3 = 0 THEN 'FizzBuzz' 
         WHEN a % 3 = 0 THEN 'Fizz' 
         WHEN a % 5 = 0 THEN 'Buzz' 
         ELSE CONVERT(varchar,a) END
FROM (SELECT TOP 100 
      ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) a 
      FROM sys.all_objects) a

One thought to “FizzBuzz – My Approach”

  1. Here is my version

    SELECT number,ISNULL(NULLIF(CASE WHEN number % 3 = 0 THEN ‘Fizz’ ELSE ” END
    + CASE WHEN number % 5 = 0 THEN ‘Buzz’ ELSE ” END, ”), number)
    FROM master..spt_values WHERE type=’P’
    and number between 1 and 100

Leave a Reply