Search code examples
mysqlwhere-clause

MySQL user-defined variable in WHERE clause


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.


Solution

  • 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