-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy path14.1.case_when
More file actions
53 lines (41 loc) · 1.39 KB
/
Copy path14.1.case_when
File metadata and controls
53 lines (41 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
My complete SQL Masterclass Notes in Tanglish is now live! Covers 30+ topics with syntax, examples, and step-by-step explanations.
Perfect for both beginners and professionals to master SQL easily. Check it out here 👉 https://topmate.io/dataengineering/1697791
====================================================================================
-- Case When Statement
CREATE TABLE CustomerData (
id INT PRIMARY KEY,
customer_name VARCHAR(100),
email VARCHAR(100),
phone_number VARCHAR(15),
address VARCHAR(200),
amount DECIMAL(10, 2)
);
INSERT INTO CustomerData VALUES
(1, 'Ravi', 'ravi@example.com', '98765', 'Chennai', 5000.00),
(2, 'Priya', NULL, '98765', 'Bangalore', NULL),
(3, 'Arjun', 'arjun@example.com', NULL, 'Hyderabad', 1500.00),
(4, 'Meena', NULL, NULL, 'Mumbai', 2500.00),
(5, 'Karthik', 'karthik@example.com', '98765', NULL, 3000.00);
Example 1
--------
SELECT
customer_name,
amount,
CASE
WHEN amount > 4000 THEN 'High Spender'
WHEN amount BETWEEN 2000 AND 4000 THEN 'Medium Spender'
WHEN amount <= 2000 THEN 'Low Spender'
ELSE 'No Data'
END AS spending_category
FROM
CustomerData;
Example 2
---------
select customer_name,
amount,
case
when email is null and phone_number is null then '9999' -- ordering matters
when email is null then phone_number
else email
end as contact
from CustomerData