-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomplex_queries.sql
More file actions
125 lines (101 loc) · 2.08 KB
/
complex_queries.sql
File metadata and controls
125 lines (101 loc) · 2.08 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
-- SubQuery
select *
from products
where unit_price >(
select unit_price
from products
where product_id = 3);
-- In operator
select *
from products
where product_id not in (
select distinct product_id
from order_items);
-- Subqueries vs Joins
use sql_invoicing;
select *
from clients
where client_id not in (
select distinct client_id
from invoices);
select *
from clients
left join invoices
using(client_id)
where invoice_id is null;
-- All Keyword ( 'all' compares given condition with every returned row )
select *
from invoices
where invoice_total > (
select max(invoice_total)
from invoices
where invoice_id = 3
);
select *
from invoices
where invoice_total > all (
select invoice_total
from invoices
where invoice_id = 3
);
-- any keyword
select *
from clients
where client_id in(
select client_id
from invoices
group by client_id
having count(*) > 2
);
select *
from clients
where client_id = any(
select client_id
from invoices
group by client_id
having count(*) > 2
);
-- Correlated subqueries
use sql_hr;
select *
from employees e
where salary >(
select avg(salary)
from employees
where office_id = e.office_id
);
-- exists keyword (when we use 'exists', it doesn't return result set unlike 'in')
use sql_invoicing;
select *
from clients
where client_id in(
select client_id
from invoices);
select *
from clients c
where exists (
select client_id
from invoices
where client_id = c.client_id
);
-- Subqueries in select
select
invoice_id,
invoice_total,
(select avg(invoice_total) from invoices) as invoice_average,
invoice_total - (select invoice_average) as difference
from invoices;
-- Subqueries in from clause
select *
from (
select
client_id,
name,
(select sum(invoice_total)
from invoices
where client_id = c.client_id) as total_sales,
(select avg(invoice_total) from invoices) as invoice_average,
(select total_sales - invoice_average) as difference
from clients c
) as sales_summary
where total_sales is not null;