-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.SQL basics.sql
More file actions
128 lines (105 loc) · 2.32 KB
/
Copy path4.SQL basics.sql
File metadata and controls
128 lines (105 loc) · 2.32 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
117
118
119
120
121
122
123
124
125
126
127
128
use ecom;
-- SELECT
-- -------
select * from dim_customer; -- Read all columns
-- LIMIT
-- ------
select
customer_id,email
from
dim_customer -- Read relevant columns
limit 20; -- Output 20 records
-- WHERE [CONDITION] Used when we want to filter out (prune) our data.
-- -----------------
-- Query 1
-- Show details of all female customers
select
*
from
dim_customer
where
gender = 'F';
-- We can only write one WHERE clause in whole SQL statement. For multiple conditions we do the following.
-- Query 2 (AND/OR)
-- Select female customers, from France or customers who joined after 2021.
select
*
from
dim_customer
where
(gender = 'F') and ((country = 'France') or (join_date > '2021-01-01'));
-- LIKE Operator
-- -------------
-- Query 3
-- Select all customers whose first name starts with S.
select
*
from
dim_customer
where
first_name like 'S%';
-- Query 4
-- Select all customers whose first name starts with T, 4th letter F and ends with Y.
select
*
from
dim_customer
where
first_name like 'T__F%Y'; -- Case insensitive
-- ORDEDR BY [Sorting]
-- -------------------
select * from dim_product;
-- Query 5
-- Sort the dim_products table such that product with high unit price come at top and lowest unit price comes at bottom. And return top 3 products.
select
*
from
dim_product
order by
unit_price desc -- Default behaviour - ascending (ASC)
limit 3;
-- AS [ALIAS]
-- ------------
select
product_key,
product_id,
product_name AS 'Product Name', -- Renames the column
unit_price
from
dim_product;
-- GROUP BY [Grouping the data]
-- ----------------------------
select * from dim_product;
-- Query 6
-- Find the averge and total price per category sorted along total price in descending order. (avg/sum/min/max)
select
category,
avg(unit_price) as avg_price,
sum(unit_price) as total_price
from
dim_product
group by
category
order by
total_price desc;
-- We use where clause only on columns which are already available in the table.
-- HAVING [condition on group by]
-- -------------------------------
-- Query 7
-- Find those categories whose average price is greater than 500.
select
category
from
dim_product
group by
category
having
avg(unit_price) > 500;
-- FLOW OF EXCECUTION:
-- 1) FROM
-- 2) WHERE
-- 3) GROUP BY
-- 4) HAVING
-- 5) SELECT
-- 6) ORDER BY
-- 7) LIMIT