Using variables in MySQL queries

Variables. One of the cornerstones of most, if not all, programming languages.
They save you time by not having to type the same crap over and over. They can
be manipulated for your own gain. They can even be used in your MySQL queries.

The declaration syntax for variables in MySQL is a bit interesting, but not so
outlandish that it’s not easy to remember:

SET @nameOfStringVariable := 'some string'
SET @nameOfNumberVariable := 12345

With our variables set, you can reference them right in our queries:

SELECT column_1, column_2, column_3
FROM some_table
WHERE some_column = @someVariable

The variables can be used in comparison operators, or concatenated with results,
all of the usual stuff.

Also, they make it easy to select a value, and assign it to a variable, so that
you can use it in a subsequent query:

SELECT @someOtherValue := some_other_column
FROM some_table
WHERE some_column = @someVariable

Keep in mind, that if your query returns multiple rows, the last row will be the
one that’s value is assigned to the variable.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.