SQL - gregorymorrison/euler1 GitHub Wiki

ANSI SQL is a database query language, not a general-purpose language. Even so, with a little cleverness we can bend it to our will, abusing it to do things that would make E. F. Codd sad. The following is Oracle SQL; with other DBMSes your mileage may vary:

-- Euler1 in SQL

WITH euler1 AS (
    select SUM(lvl) from (
	select LEVEL lvl from dual
	where MOD(LEVEL,3)=0 or MOD(LEVEL,5)=0
	connect by LEVEL < 1000))

select * from euler1;

I tried to keep to my Euler1 design as much as possible. User-defined runtime variables don't exist in pure ANSI SQL, although database tools often allow substitution variables to be passed in through the UI for compile-time binding.

SQL doesn't allow for user-defined functions, either - there is nothing like a call stack. No functions, no recursion - only one flat global state. So then what is euler1() here?  It looks like a separate function, but it's not; think of euler1() instead as a compile-time substitution. Oracle's WITH clause allows some flexibility to decompose your problem, with which we can simulate function calls. Notice that there's no parameter passing, though. Like I said - just one global state.

Cleverer people may be able to bastardize SQL further; I am not a clever man. For a real crime against SQLmanity, check out this neato pie chart (including legend) done entirely in SQL.

Simply execute the query to get your results, then apologize to Dr. Codd:

233168