A few thoughts about creating and using tables for challenges:
1. SQL input can be taken via a pre-existing table
Code Golf Input/Output Methods:
SQLs may take input from a named table
Creating and populating this table with input values doesn't count toward your byte total, you can just assume it is already there.
This means your calculations can output via simple SELECT from the input table:
SELECT 2*SQRT(a)FROM t
2. If possible, don't actually create a table at all
Instead of (69 bytes):
CREATE TABLE t(b INT)
INSERT t VALUES(7),(14),(21),(99)
SELECT b FROM t
Just do (43 bytes):
SELECT b FROM(VALUES(7),(14),(21),(99))t(b)
3. If possible, create the table with a SELECT INTO
Instead of (39 bytes):
CREATE TABLE t(p INT)
INSERT t VALUES(2)
Do this (17 bytes):
SELECT 2 p INTO t
4: Consider mashing multiple columns together
Here are two variations that return the same output:
SELECT a,b FROM
(VALUES('W','Bob'),('X','Sam'),('Y','Darla'),('Z','Elizabeth'))t(a,b)
SELECT LEFT(a,1),SUBSTRING(a,2,99)FROM
(VALUES('WBob'),('XSam'),('YDarla'),('ZElizabeth'))t(a)
After some testing, the top version (multiple columns) seems shorter with 7 or fewer rows, the bottom version (due to the LEFT and SUBSTRING) is shorter with 8 or more rows. Your mileage may vary, depending on your exact data.
5: Use REPLACE and EXEC for very long sequences of text
In the vein of comfortablydrei's excellent answer, if you have 15 or more values, use REPLACE
on a symbol to get rid of the repeated '),('
separators between elements:
114 characters:
SELECT a FROM(VALUES('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H')
,('I'),('J'),('K'),('L'),('M'),('N'),('O'))t(a)
112 characters:
DECLARE @ CHAR(999)=REPLACE('SELECT a FROM(VALUES(''
A-B-C-D-E-F-G-H-I-J-K-L-M-N-O''))t(a)','-','''),(''')EXEC(@)
If you're already using dynamic SQL for other reasons (or have multiple replaces), then the threshold where this is worth it is much lower.
6: Use a SELECT with named columns instead of a bunch of variables
Inspired by jmlt's excellent answer here, re-use strings via a SELECT:
SELECT a+b+a+b+d+b+b+a+a+d+a+c+a+c+d+c+c+a+a
FROM(SELECT'Hare 'a,'Krishna 'b,'Rama 'c,'
'd)t
returns
Hare Krishna Hare Krishna
Krishna Krishna Hare Hare
Hare Rama Hare Rama
Rama Rama Hare Hare
(For MS SQL I changed the \t
to an in-line return, and changed CONCAT()
to +
to save bytes).
a tip - use a different language for golfing. Sql answers usually gets very few or no upvotes at all. – t-clausen.dk – 2019-04-07T16:17:41.953