⬅ Previous Topic
SQL Error Handling – BEGIN...HANDLER, SIGNALNext Topic ⮕
Database Normalization – 1NF, 2NF, 3NF, BCNF⬅ Previous Topic
SQL Error Handling – BEGIN...HANDLER, SIGNALNext Topic ⮕
Database Normalization – 1NF, 2NF, 3NF, BCNFWhat if your SQL query depends on user input or varies based on certain conditions? You can't hardcode every case. That’s where Dynamic SQL comes in. It lets you construct and execute SQL statements at runtime — adding flexibility, interactivity, and control.
Dynamic SQL is a SQL statement created and executed at runtime rather than being hardcoded into the procedure. You use it when the structure of your query is not fixed in advance — for example, when filtering by variable columns, table names, or sorting criteria.
PREPARE stmt_name FROM @sql
EXECUTE stmt_name
DEALLOCATE PREPARE stmt_name
CREATE TABLE students (
roll_no INT,
name VARCHAR(50),
marks INT,
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', 85, 'Delhi'),
(2, 'Diya Iyer', 92, 'Chennai'),
(3, 'Sneha Patil', 78, 'Pune'),
(4, 'Mehul Agarwal', 90, 'Delhi');
SET @city_name = 'Delhi';
SET @sql = CONCAT('SELECT name, marks FROM students WHERE city = "', @city_name, '"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
name | marks
----------------+-------
Aarav Sharma | 85
Mehul Agarwal | 90
SET @sort_column = 'marks';
SET @sql = CONCAT('SELECT name, marks FROM students ORDER BY ', @sort_column, ' DESC');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
name | marks
----------------+-------
Diya Iyer | 92
Mehul Agarwal | 90
Aarav Sharma | 85
Sneha Patil | 78
DELIMITER $$
CREATE PROCEDURE get_students_by_city(IN p_city VARCHAR(30))
BEGIN
SET @sql = CONCAT('SELECT name, marks FROM students WHERE city = "', p_city, '"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
CALL get_students_by_city('Pune');
Dynamic SQL adds the power of flexibility to your SQL toolbox. Instead of writing rigid queries, you can build smart, context-aware scripts that adapt to input or conditions. In a school database, this means more intelligent reports, user-driven filters, and robust admin utilities.
Next up: SQL Optimization Techniques — master the art of making your queries fast, efficient, and scalable.
⬅ Previous Topic
SQL Error Handling – BEGIN...HANDLER, SIGNALNext Topic ⮕
Database Normalization – 1NF, 2NF, 3NF, BCNFYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.