sqlgocode-readability

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


Solution

  • 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....