What is the syntax for input parameters (variables) in a MySQL query?


To set a variable in MySQL, you need to use the SET command. Following is the syntax:

set @yourVariableName:=yourValue;
select *from yourTableName where yourColumnName=@yourVariableName;

Let us first create a table:

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(20),
   LastName varchar(20)
);
Query OK, 0 rows affected (0.83 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values(10,'Carol','Taylor');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(20,'John','Doe');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(30,'John','Smith');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(40,'David','Miller');
Query OK, 1 row affected (0.18 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output:

+------+-----------+----------+
| Id   | FirstName | LastName |
+------+-----------+----------+
| 10   | Carol     | Taylor   |
| 20   | John      | Doe      |
| 30   | John      | Smith    |
| 40   | David     | Miller   |
+------+-----------+----------+
4 rows in set (0.00 sec)

Let us now see how to set user defined variables in MySQL:

mysql> set @myId:=30;
Query OK, 0 rows affected (0.00 sec)
mysql> select *from DemoTable where Id=@myId;

This will produce the following output

+------+-----------+----------+
| Id   | FirstName | LastName |
+------+-----------+----------+
| 30   | John      | Smith    |
+------+-----------+----------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements