Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Case in SQL

Case in SQL

? CASE Statement in SQL

The CASE statement is used to create conditional logic inside SQL queries. It works like an IF-THEN-ELSE or switch statement in programming.


? Syntax

1. Simple CASE

CASE expression    WHEN value1 THEN result1    WHEN value2 THEN result2    ...    ELSE result_defaultEND
  • Compares an expression to values and returns the matching result.


2. Searched CASE

CASE    WHEN condition1 THEN result1    WHEN condition2 THEN result2    ...    ELSE result_defaultEND
  • Evaluates multiple conditions in order and returns the result for the first true condition.


? Examples

1. Simple CASE Example: Grade conversion

SELECT student_name,       CASE grade           WHEN 'A' THEN 'Excellent'           WHEN 'B' THEN 'Good'           WHEN 'C' THEN 'Average'           ELSE 'Poor'       END AS performanceFROM students;

2. Searched CASE Example: Salary bracket

SELECT employee_name, salary,       CASE           WHEN salary >= 100000 THEN 'High'           WHEN salary >= 50000 THEN 'Medium'           ELSE 'Low'       END AS salary_levelFROM employees;

3. Using CASE in ORDER BY

SELECT * FROM productsORDER BY    CASE category        WHEN 'Electronics' THEN 1        WHEN 'Furniture' THEN 2        ELSE 3    END;

? Key Points

  • CASE must end with END.

  • ELSE is optional; if omitted and no conditions match, returns NULL.

  • Can be used in SELECT, WHERE, ORDER BY, etc.

  • Useful for transforming or grouping data dynamically.


Want examples with nested CASE statements or combining CASE with aggregates?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql