Dave's Brain

Browse - Programming Tips - What's the nicest way to do a MYSQL INSERT?

Date: 2008jan14 
Language: sql

Q.  What's the nicest way to do a MYSQL INSERT?

A.  Many textbooks and tutorials suggest a syntax like this:

INSERT mytable (name, address) VALUES('Bill', '123 Main St'); # Error prone
But when you get a big list of fields its easy to make a mistake alining the field names and values. Also its hard for somebody to verify latter that its correct. So use the following syntax that Mysql permits:
INSERT mytable SET name='Bill', address='123 Main St'; # Nice
The name/values are together and as a bonus its even slightly shorter. This syntax is has always been used for UPDATEs but not many people use it for INSERT - they should. Unfortunately, at time of writing, this syntax does NOT work with the current version of Postgresql (8.2.6). Related http://www.davekb.com/search.php?target=perl+DBI http://www.davekb.com/search.php?target=mysql

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.