Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learn SQL using MySQL in One Day and Learn It Well

You're reading from  Learn SQL using MySQL in One Day and Learn It Well

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781836205678
Pages 121 pages
Edition 1st Edition
Languages
Author (1):
Jamie Chan Jamie Chan
Profile icon Jamie Chan

Variables

 

So what is a variable?

 

A variable is a name given to data that we need to store and use in our SQL statements.

 

For instance, suppose we want to get all information related to employee 1 from the employees and mentorships tables. We can do that as follows:

 

SELECT * FROM employees WHERE id = 1;

SELECT * FROM mentorships WHERE mentor_id = 1;

SELECT * FROM mentorships WHERE mentee_id = 1;

 

However, if we realize that we made a mistake and want the information of employee 2 instead, we’ll have to change all the three SQL statements above. This is relatively easy for three statements, but can be a lot of trouble if there are hundreds of statements. A better way is to use variables.

 

To do that, we can first declare and initialize a variable using the statement below:

 

SET @em_id = 1;
 

Here, we declare a variable called @em_id. User defined variables in MySQL have to be prefixed with the @ symbol.

 

...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}