0
0
SQLquery~3 mins

Why IF-ELSE in procedures in SQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your database could make smart decisions for you automatically?

The Scenario

Imagine you have a big list of customer orders and you need to give discounts based on order size. Doing this by checking each order manually in a spreadsheet or with separate queries is like sorting through thousands of papers one by one.

The Problem

Manually checking each order is slow and easy to mess up. You might forget a condition or apply the wrong discount. It's hard to keep track and update rules when things change.

The Solution

Using IF-ELSE in procedures lets you write clear rules inside the database. The database automatically checks conditions and applies the right actions for each order, saving time and avoiding mistakes.

Before vs After
Before
SELECT * FROM orders;
-- Then manually check each row and update discounts outside SQL
After
CREATE PROCEDURE ApplyDiscount(IN p_order_id INT, IN p_order_amount DECIMAL(10,2))
BEGIN
  IF p_order_amount > 100 THEN
    UPDATE orders SET discount = 10 WHERE order_id = p_order_id;
  ELSE
    UPDATE orders SET discount = 0 WHERE order_id = p_order_id;
  END IF;
END;
What It Enables

You can automate decision-making inside the database, making your data smarter and your work faster.

Real Life Example

A store automatically applies different discounts to customers based on how much they buy, without anyone needing to check orders manually.

Key Takeaways

Manual checks are slow and error-prone.

IF-ELSE in procedures automates conditional logic.

This saves time and reduces mistakes in data handling.