69

I tried the following -

I created a variable at the command prompt as follows -

mysql> set @myId = 1;
Query OK, 0 rows affected (0.00 sec)

Then, to display it, I tried the following without success -

    mysql> show myId;
    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 'myId' at line 1
    mysql> show @myId;
    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 '@myId' at line 1
    mysql> PRINT @myId;
    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 'PRINT @myId' at line 1
    mysql> PRINT myId;
    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 'PRINT myId' at line 1

So how can I display the value of @myId?

sonjz
  • 4,870
  • 3
  • 42
  • 60
CodeBlue
  • 14,631
  • 33
  • 94
  • 132

3 Answers3

105

Simply SELECT the variable like this:

SELECT @myId;

Here is the MySQL documentation on user-defined variables:

http://dev.mysql.com/doc/refman/5.5/en/user-variables.html

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
10

If you're looking for a variable that you set yourself like the OP did, then @MikeBrant's answer is correct:

SELECT @myId;

But if you want to see the MySQL system variables (which is what I came here looking for), then you need to run:

show variables like '%slow%';

or possibly:

show global variables like '%slow%';
Ryan Shillington
  • 23,006
  • 14
  • 93
  • 108
  • Now bonus question: Is it possible to only display a system variable's value, without also displaying its name again? So that it could be used to simply query the value of the specific variable? – Raven Apr 28 '22 at 17:47
  • @Raven that requires you to run the MySQL command line with specific options to not print the headers. – Ryan Shillington Apr 29 '22 at 23:49
  • Thanks! I think I have found a better way by now though: https://stackoverflow.com/a/72074905/3907364 – Raven May 01 '22 at 07:46
3

SHOW GLOBAL STATUS LIKE '%com_stmt%'; may be used to determine any SHOW GLOBAL STATUS current values using wildcard.

Likewise, SELECT @@thread_cache_size; may be used to display any specific SHOW GLOBAL VARIABLES current value.

There are more than 300 GLOBAL STATUS values.

There are more than 400 GLOBAL VARIABLES with or without values. (Could be empty placeholders).

You CAN NOT create a GLOBAL VARIABLE in MySQL.

Wilson Hauck
  • 2,094
  • 1
  • 11
  • 19