A Little Noise

July 11, 2006

Quoth the maven

Filed under: MySQL Gotchas — snoyes @ 2:57 pm

Straight quotes can be used like backticks around aliases IN SOME CASES (as of 5.0.15, at least). Observe:

CREATE TABLE myTable (id int, someData int);
INSERT INTO myTable VALUES (1, 1), (1, 2), (1, 3), (2, 1), (2, 2);

These three queries produce identical output:

SELECT * FROM myTable GROUP BY id;
SELECT * FROM myTable GROUP BY `id`;
SELECT * FROM myTable GROUP BY 'id';

Likewise, these three produce identical output:

SELECT id AS theId FROM myTable;
SELECT id AS `theId` FROM myTable;
SELECT id AS 'theId' FROM myTable;

Same with these nine:

SELECT id AS theId FROM myTable GROUP BY theId;
SELECT id AS theId FROM myTable GROUP BY `theId`;
SELECT id AS theId FROM myTable GROUP BY 'theId';
SELECT id AS `theId` FROM myTable GROUP BY theId;
SELECT id AS `theId` FROM myTable GROUP BY `theId`;
SELECT id AS `theId` FROM myTable GROUP BY 'theId';
SELECT id AS 'theId' FROM myTable GROUP BY theId;
SELECT id AS 'theId' FROM myTable GROUP BY `theId`;
SELECT id AS 'theId' FROM myTable GROUP BY 'theId';

Obviously, these two are different:

SELECT DISTINCT id FROM myTable; -- produces '1' and '2'
SELECT DISTINCT 'id' FROM myTable; -- produces 'id'

As are any queries that compare a straight-quoted value to some other field:

SELECT id AS theId FROM myTable GROUP BY theId = 1; -- two rows in result
SELECT id AS theId FROM myTable GROUP BY 'theId' = 1; -- one row in result

Please refrain from using this knowledge outside of stumping your colleagues with arcane MySQL trivia. I shudder to think what misfortune awaits the developer who deliberately uses straight quotes in this fashion.

UPDATE: Behavior has changed in 4.1.22, 5.0.30, 5.1.13, see http://bugs.mysql.com/bug.php?id=14019

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress