Archive for the ‘MySQL’ Category

Syntax quirks between MySQL and PostgreSQL

October 29, 2008

Earlier I used to work with MySQL and recently I have started working with PostgreSQL. Today I noticed a syntax quirk between the two.

select count(*) foo from bar;

The above works in MySQL with no AS applied between the alias. But PostgreSQL demands for an AS before the alias otherwise throws a syntax error.

For PostgreSQL

select count(*) as foo from bar;

I have to check as to what is the correct syntax according to SQL standards.

LAST_INSERT_ID() function

January 13, 2008

Recently at work I had to insert a row into a table and then get the id of the newly inserted row. I had planned on doing it as

Insert into table foo;

select max(id) from foo;

My colleague suggested a better approach

Insert into table foo;

select LAST_INSERT_ID();

What does this function do?

LAST_INSERT_ID() (with no argument) returns the first automatically generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT statement to affect such a column.