SQL else
Created By: chatGPT
In SQL, the
ELSE
statement is used in conjunction with a CASE expression or an IF statement. It allows you to define a default action or return a value when no other conditions are met. It's particularly useful for handling conditional logic in your queries.SELECT employee_id,
employee_name,
CASE
WHEN salary > 70000 THEN 'High'
WHEN salary > 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_bracket
FROM employees;
In the example above, the query categorizes employee salaries into three brackets: High, Medium, and Low. If an employee's salary does not meet the first two conditions, the ELSE clause returns 'Low'. This is a clear and manageable way to categorize data based on conditions.
SELECT order_id,
order_date,
CASE
WHEN status = 'Shipped' THEN 'Order is on its way'
WHEN status = 'Pending' THEN 'Order is not yet processed'
ELSE 'Order has been cancelled'
END AS order_status
FROM orders;
ELSE can also be used in IF statements. In many SQL dialects, such as SQL Server or MySQL, you can implement logical checks with an
IF
control flow.SELECT product_id,
product_name,
IF(quantity_in_stock > 0, 'In Stock', 'Out of Stock') AS stock_status
FROM products;
In this example, if a product's quantity in stock is greater than zero, it will return 'In Stock'; otherwise, it will return 'Out of Stock'. This simple yet powerful use of conditions helps to manage inventories more effectively.
SELECT * FROM customers
WHERE credit_score >= 700
AND CASE
WHEN account_status = 'Active' THEN 'Eligible for Rewards'
ELSE 'Not Eligible'
END = 'Eligible for Rewards';