Question

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

Was it helpful?

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

OTHER TIPS

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.

When you use Golang database/sql package, the work connecting to the database is carry out by your chosen SQL driver such as http://github.com/ziutek/mymysql or https://github.com/Go-SQL-Driver/MySQL/.

When you use an SQL statement in function such as Query() or Exec(), almost all driver will pass your SQL statement as it is to the database engine. MySQL implements the standard SQL INSERT syntax, and does not support your proposed syntax. Thus you can not use your proposed syntax with existing Golang MySQL drivers and MySQL database.

Thus your solution if you want to use your syntax is to:

  • find an SQL database that supports your proposed non-standard syntax, and there is none that I'm aware.
  • or write your own Golang MySQL driver to parse and convert your proposed syntax to the standard INSERT syntax before sending it to MySQL database.
  • or write a database/sql extension (similar to https://github.com/jmoiron/sqlx) that supports your proposed syntax.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top