MySQL SELECT INTO Syntax Part 1 – Uses With Variables.

This blog post, will cover examples of MySQL SELECT INTO syntax for storing column values in variables.


various-pink-letters-strewn-about

Photo by Jason Leung on Unsplash

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.
OS and DB used:

  • Xubuntu Linux 16.04.5 LTS (Xenial Xerus)
  • MySQL 5.7.23
A Brief Opener

This blog post is part 1 in a series of posts exploring MySQL SELECT INTO syntax. I plan to publish these on Monday’s for a personal blogging theme: ‘MySQL Monday Mini’s’. Hope you enjoy them!

I have this table and trivial data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
mysql> select * from demo;
+----+---------------+
| id | name          |
+----+---------------+
|  1 | Apples        |
|  2 | Mark          |
|  3 | Ham-n-cheese  |
|  4 | 57 Chevy      |
|  5 | Little River  |
|  6 | Happy Time    |
|  7 | B-52's        |
|  8 | Peanut Butter |
|  9 | Moon Dance    |
| 15 | Demo Table    |
| 16 | Max Ammount   |
| 17 | Happy Days    |
| 18 | Blue Moon     |
| 19 | Pale Rider    |
| 20 | Harmony       |
+----+---------------+
15 rows in set (0.00 sec)

To start, I will define a couple of session variables to use for the post. One of data type INTEGER assigned a value of 0, while the other will be set as an empty string to handle a VARCHAR data type:

1
2
3
4
5
mysql> SET @var_id = 0;
Query OK, 0 rows affected (0.04 sec)

mysql> SET @var_name = '';
Query OK, 0 rows affected (0.00 sec)

With SELECT INTO, you are free to place the INTO clause in a couple different areas within the SELECT query.

Here, I place it just after listing the target column of the SELECT clause:

1
2
mysql> SELECT id INTO @var_id FROM demo WHERE name = 'Mark';
Query OK, 1 row affected (0.02 sec)

I’ll verify variable @var_id‘s value with an additional SELECT:

1
2
3
4
5
6
7
mysql> SELECT @var_id;
+---------+
| @var_id |
+---------+
|       2 |
+---------+
1 row in set (0.00 sec)

The other option for INTO clause placement, is at the end of the query:

1
2
3
4
5
6
7
8
9
10
mysql> SELECT name FROM demo WHERE id = 2 INTO @var_name;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @var_name;
+-----------+
| @var_name |
+-----------+
| Mark      |
+-----------+
1 row in set (0.00 sec)

Results are all good with that usage as well.

Can you place the INTO clause just after the target table name of the FROM clause? I am not 100% sure. But we are going to find out. Together.
Let’s try and see:

1
2
mysql> SELECT name FROM demo INTO @var_name WHERE id = 18;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 18' at line 1

Nope. Lesson learned here.

Multiple variables can be the target of a SELECT INTO clause.

1
2
mysql> SELECT id, name INTO @var_id, @var_name FROM demo WHERE id = 20;
Query OK, 1 row affected (0.01 sec)

Let’s retrieve the query results for those variables now:

1
2
3
4
5
6
7
mysql> SELECT @var_id, @var_name;
+---------+-----------+
| @var_id | @var_name |
+---------+-----------+
|      20 | Harmony   |
+---------+-----------+
1 row in set (0.00 sec)

Assignment at the end of the query is also valid:

1
2
3
4
5
6
7
8
9
10
mysql> SELECT id, name FROM demo WHERE id = 9 INTO @var_id, @var_name;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @var_id, @var_name;
+---------+------------+
| @var_id | @var_name  |
+---------+------------+
|       9 | Moon Dance |
+---------+------------+
1 row in set (0.00 sec)

What if you do not have the same number of SELECT clause columns and variables?

1
2
mysql> SELECT id, name FROM demo WHERE id = 16 INTO @var_id;
ERROR 1222 (21000): The used SELECT statements have a different number of columns

SELECT INTO has great use in Stored Procedures. The demo procedure here will return a string to the caller containing the name associated with the correct id, which is supplied as an argument.
Up first, the procedure’s definition:

1
2
3
4
5
6
7
8
9
10
DELIMITER $$
CREATE
    DEFINER = CURRENT_USER
PROCEDURE sproc_whose_name(IN p_id INTEGER(11))
BEGIN
    DECLARE v_name VARCHAR(25);
        SELECT name FROM demo WHERE id = p_id INTO v_name;
    SELECT CONCAT(v_name, ' belongs to id: ', p_id);
END $$
DELIMITER ;

Then, CALL the procedure, supplying id 15 as the parameter:

1
2
3
4
5
6
7
8
9
mysql> CALL sproc_whose_name(15);
+------------------------------------------+
| CONCAT(v_name, ' belongs to id: ', p_id) |
+------------------------------------------+
| Demo Table belongs to id: 15             |
+------------------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Like what you have read? See anything incorrect? Please share your thoughts and comments below. Thanks for reading!!!

Explore the official MySQL 5.7 Online Manual for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

3 thoughts on “MySQL SELECT INTO Syntax Part 1 – Uses With Variables.

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.