0
0
MySQLquery~30 mins

Procedure parameters (IN, OUT, INOUT) in MySQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Procedure Parameters (IN, OUT, INOUT) in MySQL
📖 Scenario: You work at a small bookstore. You want to create a stored procedure to manage book stock. The procedure will take the book's ID and the number of new books to add or remove. It will also return the updated stock count.
🎯 Goal: Create a MySQL stored procedure named update_stock that uses IN, OUT, and INOUT parameters to update and return the stock count for a book.
📋 What You'll Learn
Create a table named books with columns book_id (INT) and stock (INT).
Insert one book with book_id 101 and stock 50.
Create a stored procedure update_stock with three parameters: IN p_book_id INT, INOUT p_change INT, and OUT p_new_stock INT.
The procedure should update the stock by adding p_change to the current stock of the book with p_book_id.
The procedure should set p_new_stock to the updated stock value.
If the updated stock is less than zero, set stock to zero and p_change to the actual change applied.
💡 Why This Matters
🌍 Real World
Bookstores and inventory systems often need to update stock counts safely and return updated values to applications.
💼 Career
Knowing how to use procedure parameters is essential for database developers and administrators to write reusable and efficient database logic.
Progress0 / 4 steps
1
Create the books table and insert initial data
Create a table called books with columns book_id (INT) and stock (INT). Insert one row with book_id 101 and stock 50.
MySQL
Need a hint?

Use CREATE TABLE to make the table and INSERT INTO to add the book.

2
Declare the stored procedure with parameters
Create a stored procedure named update_stock with three parameters: IN p_book_id INT, INOUT p_change INT, and OUT p_new_stock INT.
MySQL
Need a hint?

Use CREATE PROCEDURE with the correct parameter modes and names.

3
Write the core logic to update stock and set output parameters
Inside the update_stock procedure, write SQL to update the stock of the book with book_id = p_book_id by adding p_change. Then set p_new_stock to the updated stock. If the updated stock is less than zero, set stock to zero and adjust p_change to the actual change applied.
MySQL
Need a hint?

Use DECLARE to create a variable, SELECT INTO to get current stock, and IF to check for negative stock.

4
Complete the procedure with delimiters and test setup
Ensure the procedure ends with END$$ and the delimiter is reset to ;. This completes the procedure definition.
MySQL
Need a hint?

Remember to reset the delimiter to ; after the procedure.