HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

FizzBuzz in SQL--no loops

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sqlloopsfizzbuzz

Problem

MS SQL Server, no loops. ;)

WITH Numbers AS (
    SELECT 1 as Number
    UNION ALL
    SELECT Number+1 FROM Numbers WHERE Number < 100
)
SELECT CASE
    WHEN Number % 15 = 0 THEN 'FizzBuzz'
    WHEN Number % 5 = 0 THEN 'Buzz'
    WHEN Number % 3 = 0 THEN 'Fizz'
    ELSE CAST(Number as varchar)
END AS FizzBuzz
FROM Numbers;


Execution time ~5ms.

With performance being the most important concern, could this be made better?

Solution

Recursive CTEs in SQL Server execute involving a temp table. This is probably why this tiny amount of work even takes a measurable amount of time. This should take <= 1ms.

Use a numbers table. Or, use one of the many tricks to materialize a sequence of numbers without table access such as:

SELECT Num
FROM (VALUES (1), (2), ...) x(Num)


Using Number % 15 = 0 instead of Number % 3 = 0 AND Number % 5 = 0 is less clear. It requires mathematical insight to convince anyone that this is even correct. Code should be obviously correct.

The default length of varchar is unclear. (Can you tell from memory?!) Better use nvarchar(400). By default, use Unicode characters in order to just never have certain bugs and problems.

These issues aside this query is simple. Anyone can very quickly understand it and conclude that it is correct. That's good code.

Code Snippets

SELECT Num
FROM (VALUES (1), (2), ...) x(Num)

Context

StackExchange Code Review Q#56875, answer score: 10

Revisions (0)

No revisions yet.