19
4
I found it quite hard to achieve a range of numbers as rows in MySQL
.
For example the range 1-5 is achieved by:
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5
will result in:
1 2 3 4 5
for 0-99 I can cross join two 0-9 tables:
CREATE TABLE nums as
SELECT 0 as num
UNION
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
UNION
SELECT 4
UNION
SELECT 5
UNION
SELECT 6
UNION
SELECT 7
UNION
SELECT 8
UNION
SELECT 9
;
Select n.num*10+nums.num v
From nums n cross join nums
I'm tired of writing all these UNION
s and looking for a way to shrink the code.
Any ideas how to golf it (for example 0-1,000,000 range) in MySQL or any SQL syntax ?
Extra points are given for:
- single statement
- no procedures
- no variables
- no DDL statements
- only DQL statements
2
Not sure if this belongs in meta, or in dba.stackexchange.com or maybe in the tips for Golfing in SQL thread.
– BradC – 2017-06-30T17:47:04.9608To close voters: This is an on-topic challenge; questions that aren't challenges that are related to golfing code are considered on-topic tips questions. – HyperNeutrino – 2017-06-30T17:54:15.930
3
I kinda like this answer from SO. Hackish at best, but you asked for a golfing solution after all.
– Arnauld – 2017-06-30T18:01:26.300@Arnauld that's amazing! – Dimgold – 2017-06-30T18:05:34.950
Large list of methods for creating a number table, although they're evaluated by speed, not by golfing ability. – BradC – 2017-06-30T18:28:51.613
2
If “any SQL” includes PostgreSQL, see
– manatwork – 2017-06-30T18:29:19.857generate_series()
. We have a couple of usage examples here.@manatwork Looks useful, I'd say add it as an answer. Mine are already platform specific. – BradC – 2017-06-30T18:49:03.277
See http://www.itprotoday.com/microsoft-sql-server/virtual-auxiliary-table-numbers (for SQL Server 2005 or later).
– Razvan Socol – 2018-03-24T07:42:00.483