MySQL user-defined variable in WHERE clause

Paulo Freitas picture Paulo Freitas · Oct 21, 2010 · Viewed 35.8k times · Source

I want to know if there is a way to use a user-defined variable in WHERE clause, as in this example:

SELECT id, location, @id := 10 FROM songs WHERE id = @id

This query runs with no errors but doesn't work as expected.

Answer

Maxym picture Maxym · May 16, 2011

Not far from what Mike E. proposed, but one statement:

SELECT id, location FROM songs, ( SELECT @id := 10 ) AS var WHERE id = @id;

I used similar queries to emulate window functions in MySQL. E.g. Row sampling - just an example of using variables in the same statement