-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy path17.Subquery
More file actions
104 lines (88 loc) · 2.7 KB
/
Copy path17.Subquery
File metadata and controls
104 lines (88 loc) · 2.7 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
====================================================================================
Display a Derived Value for Each Row
SELECT
customer_name,
(SELECT MAX(order_amount) FROM Orders) AS max_order_amount
FROM Customers;
Subquery in where
1.
SELECT customer_name
FROM Customers
WHERE customer_id IN (
SELECT DISTINCT customer_id
FROM Orders
WHERE order_amount > 5000
);
2.
SELECT customer_name
FROM Customers
WHERE EXISTS (
SELECT 1
FROM Orders
WHERE Orders.customer_id = Customers.customer_id
AND order_date >= CURDATE() - INTERVAL 30 DAY
);
Instead of join
SELECT
customer_name,
city,
(SELECT SUM(order_amount)
FROM Orders o
WHERE o.customer_id = c.customer_id) AS total_orders
FROM Customers c;
Use a Subquery in the FROM Clause
SELECT
id,
customer_name,
name_length,
uppercase_name,
lowercase_name,
contact_info,
name_prefix,
trimmed_city,
left_padded_name,
right_padded_name,
updated_name,
position_of_a,
first_5_chars,
last_5_chars,
reversed_name,
formatted_number
FROM (
SELECT
id,
customer_name,
LENGTH(customer_name) AS name_length,
UPPER(customer_name) AS uppercase_name,
LOWER(customer_name) AS lowercase_name,
CONCAT(city, ' - ', COALESCE(phone_number, '00000')) AS contact_info,
SUBSTRING(customer_name, 1, 5) AS name_prefix,
TRIM(' ExampleCity ') AS trimmed_city,
LPAD(customer_name, 15, '*') AS left_padded_name,
RPAD(customer_name, 15, '-') AS right_padded_name,
REPLACE(customer_name, ' ', '_') AS updated_name,
INSTR(customer_name, 'a') AS position_of_a,
LEFT(customer_name, 5) AS first_5_chars,
RIGHT(customer_name, 5) AS last_5_chars,
REVERSE(customer_name) AS reversed_name,
FORMAT(9876543210, 2) AS formatted_number
FROM CustomerDetails
) AS string_handling_results;
Filtering Using CASE and Subquery
SELECT
customer_name,
CASE
WHEN (SELECT SUM(order_amount) FROM Orders WHERE Orders.customer_id = Customers.customer_id) >
(SELECT AVG(order_amount) FROM Orders) THEN 'Above Average'
ELSE 'Below Average'
END AS order_category
FROM Customers;
Subquery for Ranking
SELECT
customer_name,
(SELECT MAX(order_amount)
FROM Orders
WHERE order_amount < (SELECT MAX(order_amount) FROM Orders)) AS second_highest_order
FROM Customers;