INSERT INTO `table` (`column`,`col2`) VALUES isn’t completely worthless

In most cases, when doing an insert statement I use SET to increase readability. It is also nice because I can make dynamic statements with insert/update. It is because of these two reasons I never saw any value (for lack of a better term that isn’t punny) to using VALUES. That is until I ran into a situation where I wanted to have a database level solution as opposed to making an application layer solution. The situation is as follows:
– create an entry in the parent table
– create entries in the child table that depends on the last insert id of the parent table.

Now that I think about it, there may have been a way to do it procedurally in SQL but the first solution I was stuck on how to make my next INSERT statement fulfill my criteria and be readable. This is where VALUES comes in. By using VALUES instead of SET, you can do a multi-row insert statement.

example:

INSERT INTO Resource SET ModuleID=LAST_INSERT_ID(), Name='contact', Description='Contact resource in the default module';
/* multi-row insert */
INSERT INTO Privilege (ResourceID,Name,Description) VALUES
	(LAST_INSERT_ID(),'*','All privileges for this resource'),
	(LAST_INSERT_ID(),'browse','Browse only privilege for this resource'),
	(LAST_INSERT_ID(),'read','Read only privilege for this resource'),
	(LAST_INSERT_ID(),'edit','Edit only privilege for this resource'),
	(LAST_INSERT_ID(),'add','Add only privilege for this resource'),
	(LAST_INSERT_ID(),'delete','Delete only privilege for this resource');

So now, VALUES isn’t completely useless after all.

0 comments on “INSERT INTO `table` (`column`,`col2`) VALUES isn’t completely worthlessAdd yours →

Leave a Reply