Introduction
IF-ELSE lets you make decisions inside a procedure. It helps the database choose what to do based on conditions.
IF-ELSE lets you make decisions inside a procedure. It helps the database choose what to do based on conditions.
IF condition THEN -- statements ELSE -- statements END IF;
IF score >= 60 THEN SET result = 'Pass'; ELSE SET result = 'Fail'; END IF;
IF user_exists THEN UPDATE users SET last_login = NOW() WHERE id = user_id; END IF;
This procedure checks the age and sets a category. It uses IF, ELSEIF, and ELSE to decide.
DELIMITER $$ CREATE PROCEDURE CheckAge(IN age INT, OUT category VARCHAR(20)) BEGIN IF age < 13 THEN SET category = 'Child'; ELSEIF age < 20 THEN SET category = 'Teenager'; ELSE SET category = 'Adult'; END IF; END$$ DELIMITER ; -- Call the procedure CALL CheckAge(15, @cat); SELECT @cat;
Remember to use DELIMITER when creating procedures in MySQL to avoid confusion with semicolons.
IF-ELSE helps make your procedures smart by choosing actions based on data.
IF-ELSE lets you run different code based on conditions inside procedures.
You can use IF, ELSEIF, and ELSE for multiple choices.
It makes your database actions flexible and dynamic.
IF-ELSE statements inside SQL procedures?IF condition THEN.DECLARE v_score INT DEFAULT 75; IF v_score >= 90 THEN SELECT 'Grade A'; ELSEIF v_score >= 80 THEN SELECT 'Grade B'; ELSEIF v_score >= 70 THEN SELECT 'Grade C'; ELSE SELECT 'Grade F'; END IF;
IF score > 50 SELECT 'Pass'; ELSE SELECT 'Fail'; END IF;
IF score > 50 but no THEN keyword.Pass the test and this pattern moves unknown