Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making SQL INSERT statement easier to read

I'm working on a program in Go, that makes heavy usage of MySQL. For sake of readability, is it possible to include the value of a column after each column name in an INSERT statement? Like:

INSERT INTO `table` (`column1` = 'value1', `column2` = 'value2'...);

instead of

INSERT INTO `table` (`column`, `column2`,...) VALUES('value1', 'value2'...);

so that it's easier to see which value is associated with which column, considering the SQL strings can often get fairly long

like image 591
eggbertx Avatar asked Sep 22 '13 02:09

eggbertx


2 Answers

No, you cannot use your proposed syntax (though it would be nice).

One way is to line up column names and values:

INSERT INTO `table` 
(`column`, `column2`,...) 
VALUES
('value1', 'value2'...);

Update in response to your comment "the statements contain variables from outside the string": if you parameterise your SQL statements then matching up column names to variables is easy to check if the parameters are named for their respective columns: @ColumnName.

This is actually how I do it in my TSQL scripts:

INSERT INTO `table` 
(
    `column`, 
    `column2`,
    ...
) 
VALUES
(
    'value1', 
    'value2',
    ...
);

(It's also common to put the commas at the start of the lines)

but to be honest, once you get enough columns it is easy to mix up the position of columns. And if they have the same type (and similar range of values) you might not notice straight away....

like image 155
Mitch Wheat Avatar answered Sep 28 '22 06:09

Mitch Wheat


Although this question is a bit older I will put that here for future researchers.

I'd suggest to use the SET syntax instead of the ugly VALUES list syntax.

INSERT INTO table
SET
column1 = 'value1',
column2 = 'value2';

IMHO this is the cleanest way in MySQL.

like image 41
Uwe Trotzek Avatar answered Sep 28 '22 05:09

Uwe Trotzek