How can I create a stored procedure to select values on the basis of some conditions from a MySQL table?


We can create a stored procedure with IN and OUT operators to SELECT records, based on some conditions, from MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −

mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Bangalore  | Computers  |
+------+---------+------------+------------+
4 rows in set (0.01 sec)

Now, by creating the procedure named ‘select_studentinfo’ as follow, we can select the values from ‘student_info’ table by providing the value of ‘id’ −

mysql> DELIMITER // ;
mysql> Create Procedure Select_studentinfo ( IN p_id INT, OUT p_name varchar(20),OUT p_address varchar(20), OUT p_subject varchar(20))
   -> BEGIN
   -> SELECT name, address, subject INTO p_name, p_address, p_subject
   -> FROM student_info
   -> WHERE id = p_id;
   -> END //
Query OK, 0 rows affected (0.03 sec)

Now, invoke the procedure with the values we want to provide as condition as follows −

mysql> DELIMITER ; //
mysql> CALL Select_studentinfo(110, @p_name, @p_address, @p_subject);
Query OK, 1 row affected (0.06 sec)

mysql> Select @p_name AS Name,@p_Address AS Address, @p_subject AS Subject;
+--------+------------+-----------+
| Name   | Address    | Subject   |
+--------+------------+-----------+
| Rahul  | Chandigarh | History   |
+--------+------------+-----------+
1 row in set (0.00 sec)

Updated on: 22-Jun-2020

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements