CASE in SQL

In SQL, we use CASE to apply conditions. See practical example below-

Database ~ jai_school

CREATE DATABASE jai_school;

Create a table result

CREATE TABLE result(students VARCHAR(50),marks INT(10));

Insert data in the table

INSERT INTO result(students,marks)VALUES("Ram",450);
INSERT INTO result(students,marks)VALUES("Rahim",200);
INSERT INTO result(students,marks)VALUES("Shyam",90);
INSERT INTO result(students,marks)VALUES("Anita",350);
INSERT INTO result(students,marks)VALUES("Raman",200);
INSERT INTO result(students,marks)VALUES("Nobita",70);
INSERT INTO result(students,marks)VALUES("Ravi",250);
INSERT INTO result(students,marks)VALUES("Aman",150);
INSERT INTO result(students,marks)VALUES("Ravina",500);

Table Image-

table-for-case

CASE example

SELECT *,
CASE
     WHEN marks <100 THEN "Fail"
     WHEN marks BETWEEN 100 AND 200 THEN "Marks are between 100 and 200"
     WHEN marks BETWEEN 200 AND 300 THEN "Marks are between 200 and 300"
     WHEN marks BETWEEN 300 AND 400 THEN "Marks are between 300 and 400"
     WHEN marks = 500 THEN "First position"
   ELSE "Other students"
END
AS division
FROM result;

query result-

sql-case

Leave a Comment