-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathIntroduction to MYSQL.txt
More file actions
2026 lines (1855 loc) · 53 KB
/
Introduction to MYSQL.txt
File metadata and controls
2026 lines (1855 loc) · 53 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### How to Select Database
```sql
### How to Select Database
USE <Dbname> || use <Dbname>
USE mydb || use mydb
```
### How to Select all Table fields in Database using "*"
- First Select Database
- Select table
- Also use semicolon ; at the end of each statement
```sql
USE mydb;
SELECT * FROM customers;
```
### How to Select and filter a specific row using WHERE Clause
```sql
USE mydb;
SELECT *
FROM customers
WHERE customer_id = 5;
```
### How to Select Table and sort using First_name with ORDER BY Clause
```sql
USE mydb;
SELECT *
FROM customers
-- WHERE customer_id = 5 "--" Double Hyphen is used to comment something
ORDER BY first_name;
```
### How to Select a specific fields with field name
```sql
SELECT first_name, last_name , points FROM customers;
```
### How to Select a specific fields with field name and calculate something in run time
```sql
SELECT first_name, last_name , points, points+10 FROM customers;
```
### Select specific field and calculate something but change calculated name in run time with AS Alias
```sql
SELECT first_name, last_name , points, (points+10)*100 AS discount_factor FROM customers;
```
### if you want to add Space in Alias name
```sql
SELECT first_name, last_name , points, (points+10)*100 AS 'Discount Factor' FROM customers;
```
### How to select only unique and non duplicate value
```sql
SELECT DISTINCT city FROM customers;
```
- Make sure if you use SELECT DISTINCT first_name, city FROM customer it means both first_name and city
must be distinct.
- It does not mean that only the city column should be distinct.
### How to filter with WHERE Clause
```sql
SELECT * FROM customers WHERE points>1500;
```
- filter those records whose points are greater than 1500
- Also you should use these operators >,<,>=,<=,!=, <>
### How to filter string matched record with WHERE Clause
```sql
SELECT * FROM customers WHERE city = 'karachi';
```
### How to filter those records which does not contain string 'karachi'
```sql
SELECT * FROM customers WHERE city != 'karachi';
or
SELECT * FROM customers WHERE city <> 'karachi';
```
### How to filter those records whose birth_date > '2023-08-07'
```sql
SELECT * FROM customers WHERE birth_date > '2023-08-07';
```
### How to filter those records whose birth_date > 2023-08-07 and Points > 1500
- We use AND operator it return true if both condition meets true
```sql
SELECT * FROM customers WHERE birth_date > '2023-08-07' AND points > 1500;
```
### How to filter those records whose birth_date > '2023-08-07' OR Points > 1500
- We use OR operator it return true if at least one condition meets true
```sql
SELECT * FROM customers WHERE birth_date > '2023-08-07' OR points > 1500;
```
### How to filter those records whose birth_date > 2023-08-07 is NOT Greater than
- We use NOT operator to reverse
```sql
SELECT * FROM customers WHERE NOT(birth_date > '2023-08-07' OR points > 1500);
```
### How to filter those records whose birth_date > 2023-08-07 OR Points > 1500 AND city ="kohat"
- We use OR and AND both to add multiple conditions
```sql
SELECT * FROM customers WHERE birth_date > '2023-08-07' OR (points > 1500 AND city = 'kohat');
```
### How to select those result whose city is kohat or karachi
- We use IN operator, we can also use OR operator but IN operator is shorter and it works like OR operator
```sql
SELECT * FROM customers WHERE city IN ('karachi','kohat');
```
### How to select those result whose city is not in kohat or karachi
- We use NOT IN operator
```sql
SELECT * FROM customers WHERE city NOT IN ('karachi','kohat');
```
### How to select those points >= 1000 and <= 1500
- We use BETWEEN operator, note we can also use >= <= operators but BETWEEN is shorter
```sql
SELECT * FROM customers WHERE points BETWEEN 1000 AND 1500;
```
### How to select those rows that matched with specific string pattern using LIKE operator
- we use WHERE last_name LIKE 's%' it means last_name must be start with s but after s it contain any letters.
```sql
SELECT * FROM customers WHERE last_name LIKE 's%';
SELECT * FROM customers WHERE last_name LIKE 'summer%'; //start with summer ends with any letter
```
### change the pattern in LIKE operator
```sql
SELECT * FROM customers WHERE last_name LIKE '%s';// start with any letter but ends with s
SELECT * FROM customers WHERE last_name LIKE '%s%';// start with any letter and ends with any letter but s letter can be any
where
```
### Use underscore to define how many letters end with that pattern
```sql
SELECT * FROM customers WHERE last_name LIKE '_______s'
```
### we can also specify first and last letter and Between letters range with "__" underscore
```sql
SELECT * FROM customers WHERE last_name LIKE 'v______s'
```
### use REGEXP to use complex string pattern
- Look we use like operator
```sql
SELECT * FROM customers WHERE first_name LIKE '%hr%'
```
- we can also use REGEXP for more complex string patterns
```sql
SELECT * FROM customers WHERE first_name REGEXP 'hr'
```
### first_name must start with hr
```sql
SELECT * FROM customers WHERE first_name LIKE '%hr%'
```
- we can also use REGEXP for more complex string patterns
SELECT * FROM customer WHERE first_name REGEXP 'hr'
```
### first_name must start with hr
SELECT * FROM customers WHERE first_name REGEXP '^hr'
```
### first_name must end with t
```sql
SELECT * FROM customers WHERE first_name REGEXP 't$'
```
### we can also use pipe operator | in REGEXP
```sql
SELECT * FROM customers WHERE first_name REGEXP '^ch|t$'
```
- it means first_name must start with ch
- Or first_name must end with t
### we can also specify []
```sql
SELECT * FROM customers WHERE first_name REGEXP '[agc]t'
```
- first_name will be at, gt, ct anywhere
### we can change pattern
```sql
SELECT * FROM customers WHERE first_name REGEXP 't[agc]'
```
- first_name will be ta, tg, tc anywhere
### we can also specify range [a-h]
```sql
SELECT * FROM customers WHERE first_name REGEXP '[a-h]t'
```
- first_name will be at,bt,ct,dt,et,ft, gt, ht anywhere
### How to select those records whone phone no is NULL using "IS NULL" operator
```sql
SELECT * FROM customers WHERE phone IS NULL;
```
### How to select and sort data by column name
- by default every column is sorted according to primary key column
```sql
SELECT * FROM customers ORDER by first_name;
```
### We can also sort by multiple columns
```sql
SELECT * FROM customers ORDER by first_name;
```
### We can also sort by multiple columns
SELECT * FROM customer ORDER by first_name, last_name;
```sql
SELECT * FROM customers ORDER by first_name DESC, last_name ASC;
```
### How to Select first 10 records using "LIMIT" Clause
```sql
SELECT * FROM customers LIMIT 10;
```
### How to skip first 10 records using "LIMIT" Clause and select 3 records before 10 records
- we define offset 10 , 3
```sql
SELECT * FROM customers LIMIT 10 , 3;
```
### Reterieve Random record with RAND Function
- Please use ORDER By Clause otherwise you got an error
```
SELECT * FROM orders ORDER BY RAND() LIMIT 1;
```
### How to select one table with relationship to another table using "INNER JOIN"
- lets we have orders table in orders table we have customer_id which is a foriegn key to customer table
- In Orders table we have orders_id, customer_id, status, comments
- In Customer table we have customer_id, first_name, last_name, birth_date, phone, address, city and state
- We want to inner join with orders table and customer table
```sql
SELECT * FROM orders INNER JOIN customerON orders.customer_id = customer.customer_id;
```
### We can also achieve "INNER JOIN" with implicit Syntax
```sql
SELECT * FROM orders o, customers c WHERE o.customer_id = c.customer_id;
```
### How to find only select first_name, city and phone from customer table
```sql
SELECT order_id, orders.customer_id first_name, phone, city
FROM orders
INNER JOIN customers
ON
orders.customer_id = customer.customer_id;
```
### We can also use alias in inner join
```sql
SELECT order_id, o.customer_id first_name, phone, city
FROM orders o
INNER JOIN customers c
ON
o.customer_id = c.customer_id;
```
### We to join tables across Databases
- suppose we have a Database name inventory
- In the inventory db we have products table
- this product table is associated with orders_items
- we can easily join using db.table name
```sql
select *
FROM orders_items oi
INNER JOIN inventory.products p
ON
oi.product_id = p.product_id;
```
### How to select only selected name, quantity from products table
```sql
select oi.product_id, unit_price, name
FROM orders_items oi
INNER JOIN inventory.products p
ON
oi.product_id = p.product_id;
```
### How to Select Self join table itself
- Suppose we have employe table we want to check who is manager in our complany
- But the best thing is manager is itself an employe of this complany
```sql
SELECT *
FROM employees m
JOIN employees e
ON
e.reports_to = m.employee_id;
```
### How to Select Self join table itself
- only want to check the manager
```sql
SELECT
e.employee_id,
e.first_name,
m.first_name as Manager
FROM employees m
JOIN employees e
ON
e.reports_to = m.employee_id;
```
### How to JOIN multiple tables
- We have three tables orders, order_status and customer we want to join
```sql
SELECT *
FROM orders o
JOIN customers c
ON
o.customer_id = c.customer_id
JOIN order_status os
ON os.status_is = o.status;
```
### Lets Extract Beautifully
```sql
SELECT
o.order_id,
o.order_date,
c.first_name,
c.last_name,
os.name AS Status
FROM orders o
JOIN customers c
ON
o.customer_id = c.customer_id
JOIN order_status os
ON os.status_is = o.status;
```
### Left Join
- Left outer join select those records which are not
- like in our example we also select those customers who don't have any order as well as who do
```sql
SELECT
c.customer_id,
c.first_name,
o.order_id
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
ORDER BY c.customer_id
```
### Right Join
- Right outer join select those records which satisfy the condition
- like in our example we only select those customers who have orders
```sql
SELECT
c.customer_id,
c.first_name,
o.order_id
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
ORDER BY c.customer_id
```
### USING Clause
- USING Clause can replace JOIN complex steps
- But it can only work when both table have same column name
```sql
SELECT
o.order_id,
c.first_name
FROM orders o
JOIN customers c
-- ON o.customer_id = c.first_name
USING (customer_id);
```
### Cross JOIN
- combine every record from first table to second table
- WE combine every record from customer table to products table
```sql
SELECT
c.first_name AS customer,
p.name AS product
FROM customers c
CROSS JOIN inventory.products p
ORDER BY c.first_name;
```
### Combine tables rows with UNION
```sql
SELECT
order_id,
order_date,
'Active' AS status
FROM orders
WHERE order_date >= '2023-11-09'
UNION
SELECT
order_id,
order_date,
'Archived' AS status
FROM orders
WHERE order_date < '2023-11-09'
```
### INSERT RECORDS
```sql
INSERT INTO customers (
customer_id,
first_name,
last_name,
birth_date,
phone,
address,
city,
state,
points
) VALUES (
52,
'Ahmed',
'Raheem',
NULL,
NULL,
'Azad Chaiwala Institute',
'Rawalpindi',
'Punjab',
DEFAULT
);
```
### INSERT Multiple RECORD
```sql
INSERT INTO customers (
customer_id,
first_name,
last_name,
birth_date,
phone,
address,
city,
state,
points
) VALUES (
53,
'Ishaque',
'Chaiwala',
NULL,
NULL,
'Azad Chaiwala Institute',
'Rawalpindi',
'Sindh',
DEFAULT
),
(
54,
'Muhammad',
'Mowahid',
NULL,
NULL,
'Azad Chaiwala Institute',
'Rawalpindi',
'Punjab',
DEFAULT
);
```
### INSERT Hierarchical RECORDS
```sql
INSERT INTO customers(customer_id,first_name,last_name,birth_date)
VALUES (DEFAULT,'IGI','ORIGIN','2023-12-25');
INSERT INTO orders(order_id,order_date, status,customer_id)
VALUES(DEFAULT,'2023-12-25',1,LAST_INSERT_ID());
INSERT INTO
orders_items(order_id,product_id,unit_price,quantity)
VALUES (LAST_INSERT_ID(),9,35,3);
```
### Creating Copy of a Table
```sql
CREATE TABLE orders_archived AS
SELECT * FROM orders;
```
### Creating only data from one table to another
```sql
CREATE TABLE orders_archived AS
SELECT * from orders WHERE order_date > '2023-12-01';
```
### Updating Single Record
```sql
UPDATE customers
SET first_name="Muhammad", last_name="Hashim", birth_date="2023-12-30"
WHERE customer_id = 1;
```
### Using subqueries in Update
```sql
UPDATE orders
SET comments = "Gold Customer"
WHERE c_id IN
(SELECT customer_id
FROM customers
WHERE points > 1800);
```
### Using subqueries in Delete
```sql
DELETE FROM orders
WHERE c_id = (
SELECT customer_id
FROM customers
WHERE first_name = "Delano"
);
```
### Aggregate Functions
```sql
SELECT
MAX(salary) AS Highest,
MIN(salary) AS lowest,
AVG(salary) AS average,
SUM(salary) AS total,
COUNT(salary) AS number_of_records
FROM employees;
```
### The GROUP By Clause in Aggregate Functions
```sql
SELECT
client_id,
SUM(invoice_total) as total_sales
FROM invoices
GROUP BY client_id
ORDER BY total_sales DESC;
```
### The GROUP By Clause with WHERE Clause in Aggregate Functions
```sql
SELECT
client_id,
SUM(invoice_total) as total_sales
FROM invoices
WHERE invoice_date >= '2019-07-01'
GROUP BY client_id
ORDER BY total_sales DESC;
```
### The GROUP By Clause with inner JOIN in Aggregate Functions
```sql
SELECT
name,
state,
city,
SUM(invoice_total) as total_sales
FROM invoices i
JOIN clients c USING(client_id)
GROUP BY state, city;
```
### The GROUP By Clause with inner JOIN in Aggregate Functions
```sql
SELECT date,
pm.name,
SUM(amount) AS total_amounts
FROM payments p
JOIN payment_methods pm
ON p.payment_method = pm.payment_method_id
GROUP BY date
ORDER BY date DESC;
```
### Having Clause with Aggregate Functions
```sql
SELECT
client_id,
COUNT(*) AS number_of_invoices,
SUM(invoice_total) as total_sales
FROM invoices
GROUP BY client_id
HAVING total_sales > 500;
```
### Having Clause with Aggregate Functions
```sql
SELECT
client_id,
COUNT(*) AS number_of_invoices,
SUM(invoice_total) as total_sales
FROM invoices
GROUP BY client_id
HAVING total_sales > 500 AND number_of_invoices > 5;
```
### Aggregate functions WITH ROLLUP
```sql
SELECT
client_id,
SUM(invoice_total) as total_sales
FROM invoices
GROUP BY client_id WITH ROLLUP;
```
### Aggregate functions WITH ROLLUP and JOIN
```sql
SELECT
state,
city,
SUM(invoice_total) as total_sales
FROM invoices i
JOIN clients c USING(client_id)
GROUP BY state, city WITH ROLLUP;
```
### Write more about subqueries
- expensive than lettuce (id = 3)
- MySQL first execute innersubquery than pass it to out query
```sql
SELECT *
FROM products
WHERE unit_price > (
SELECT unit_price
FROM products
WHERE product_id = 3
);
```
### Write more about subqueries
- In Sql_hr database
- find employees who earn more than average
```sql
SELECT * FROM
employees WHERE salary > (
SELECT AVG(salary)
FROM employees
);
```
### Write more about subqueries using IN operator
- find that product that have never been ordered
```sql
SELECT * FROM products
WHERE product_id NOT IN (
SELECT DISTINCT product_id
FROM order_items
);
```
### Write more about subqueries using IN operator
- find clients without invoices
```sql
SELECT *
FROM clients
WHERE client_id NOT IN (
SELECT DISTINCT client_id
FROM invoices
);
```
## join vs sub query
### using subqueries
- find customer who have ordered lettuce
- select customer_id , first_name, last_name
```sql
SELECT customer_id,
first_name,
last_name
FROM customers
WHERE customer_id IN(
SELECT o.customer_id
FROM order_items oi
JOIN orders o USING (order_id)
WHERE product_id = 3
);
```
### using JOIN
```sql
SELECT DISTINCT customer_id,
first_name,
last_name
FROM customers c
JOIN orders o USING(customer_id)
JOIN order_items oi USING(order_id)
WHERE oi.product_id = 3;
```
### without ALL keyword
- select invoices larger than all invoices of client 3
```sql
SELECT *
FROM invoices
WHERE invoice_total >(
SELECT MAX(invoice_total)
FROM invoices
WHERE client_id = 3
);
```
### ALL keyword
```sql
SELECT *
FROM invoices
WHERE invoice_total > ALL(
SELECT invoice_total
FROM invoices
WHERE client_id = 3
);
```
### Correlated subqueries
- For each employe
- calculate the avg salary for employee.office
- return the employee if salary > avg
```sql
SELECT *
FROM employees e
WHERE salary > (
SELECT AVG(salary)
FROM employees
WHERE office_id = e.office_id
);
```
### The EXISTS operator
- Select client that have an invoice
- one method
```sql
Select *
FROM clients
WHERE client_id IN (
select DISTINCT client_id
FROM invoices
);
```
- second method
```sql
SELECT *
FROM clients
INNER JOIN (
SELECT DISTINCT client_id
FROM invoices
) AS distinct_clients
ON clients.client_id = distinct_clients.client_id;
```
- third method
```sql
Select *
FROM clients c
WHERE EXISTS (
select client_id
FROM invoices
WHERE client_id = c.client_id
);
```
### Date Functions to check dynamically current Year orders
```sql
SELECT *
FROM orders
WHERE YEAR(order_date) = YEAR(NOW());
```
### FORMAT_DATE Function
```sql
SELECT DATE_FORMAT(order_date,'%D %M %Y')
FROM orders;
```
### ADDING DATE Function
```sql
SELECT DATE_ADD(order_date, INTERVAL 1 YEAR)
FROM orders;
```
### IFNULL Function
```sql
SELECT
order_id,
shipper_id
FROM orders;
SELECT
order_id,
IFNULL(shipper_id,'Not Assigned') AS shipper
FROM orders;
```
### COALESCE Function
```sql
SELECT
order_id,
COALESCE(shipper_id,comments,'Not Assigned') AS shipper
FROM orders;
SELECT
order_id,
IFNULL(shipper_id,'...') AS shipperID,
COALESCE(shipper_id,comments,'Not Assigned') AS shipper
FROM orders;
```
### IF Function
```sql
SELECT
order_id,
order_date,
IF(YEAR(order_date) = YEAR(NOW()), 'Active', 'Archived') AS order_status
FROM orders;
```
### CASE Operator
```sql
SELECT
order_id,
CASE
WHEN YEAR(order_date) = YEAR(NOW()) THEN 'Active'
WHEN YEAR(order_date) = YEAR(NOW()) - 1 THEN 'Last Year'
WHEN YEAR(order_date) < YEAR(NOW()) - 1 THEN 'Archived'
ELSE 'Future'
END AS Category
FROM orders;
```
### Practice
```sql
SELECT
CONCAT(first_name,' ',last_name) AS Customer,
points,
CASE
WHEN points > 3000 THEN 'Gold Customer'
WHEN points >= 2000 THEN 'Silver Customer'
ELSE 'Bronze Customer'
END AS category
FROM customers;
```
### Creating View
```sql
CREATE VIEW sales_by_client AS
SELECT
c.client_id,
c.name,
SUM(invoice_total) AS total_sales
FROM clients c
JOIN invoices i USING(client_id)
GROUP BY client_id, name;
```
### Drop View
```sql
DROP VIEW invoices_with_balance;
```
### Updatable View
- DISTINCT
- Aggregate functions (MIN , MAX, SUM) etc
- GROUP BY / HAVING
- UNION
- If we dont have these in mention above
- than our view is Updatable view
``` sql
CREATE OR REPLACE VIEW invoices_with_balance AS
SELECT
invoice_id,
number,
client_id,
invoice_total,
payment_total,
invoice_total - payment_total AS balance,
invoice_date,
payment_date,
due_date
FROM invoices
WHERE (invoice_total-payment_total) > 0;
DELETE FROM invoices_with_balance
WHERE invoice_id = 1;
```
- prevent view as only read-only
- add WITH check OPTION;
```sql
CREATE OR REPLACE VIEW invoices_with_balance AS
SELECT
invoice_id,
number,
client_id,
invoice_total,
payment_total,
invoice_total - payment_total AS balance,
invoice_date,
payment_date,
due_date
FROM invoices
WHERE (invoice_total-payment_total) > 0
WITH check OPTION;
```
### Creating Store Procedure
```sql
DELIMITER $$
CREATE PROCEDURE get_clients()
BEGIN
SELECT * FROM clients;
END$$
DELIMITER ;
```
### Select Procedure
```sql
CALL get_clients()
```
### Dropping Procedure
```sql
DROP Procedure IF EXISTS get_clients;
```
### Parameters in Procedure
```sql
CALL get_clients()
```
### Dropping Procedure
DROP Procedure IF EXISTS get_clients;
```
### Parameters in Procedure
DROP PROCEDURE IF EXISTS get_clients_by_states;
DELIMITER $$
CREATE PROCEDURE get_clients_by_states
(
state CHAR(2)
)
BEGIN
SELECT * FROM clients c
WHERE c.state = state;
END$$
DELIMITER ;
CALL get_clients_by_states('CA');
```
### Parameters with defaults values in Procedure
```sql
DELIMITER $$
CREATE PROCEDURE get_clients_by_default_states
(
state CHAR(2)
)
BEGIN
IF state IS NULL THEN
SET state = 'CA';
END IF;
SELECT * FROM clients c
WHERE c.state = state;
END$$
DELIMITER ;
CALL get_clients_by_default_states(NULL)
```
### Parameters with IF ELSE in Procedure
```sql
DELIMITER $$
CREATE PROCEDURE get_clients_by_default_states
(
state CHAR(2)
)
BEGIN
IF state IS NULL THEN
select * from clients;
ELSE
SELECT * FROM clients c
WHERE c.state = state;
END IF;
END$$
DELIMITER ;
CALL get_clients_by_default_states(NULL)
CALL get_clients_by_default_states('CA')
```
### Practice Procedure
- Write a stored procedure call get_payments
- with two Parameters
- client_id => id(5)
- payment_method_id => TINYINT(1) 0-255
```sql
DELIMITER $$
CREATE PROCEDURE get_payments
(
client_id INT,
payment_method_id TINYINT(1)
)
BEGIN
SELECT *
from payments p
WHERE
p.client_id = IFNULL(client_id, p.client_id) AND
p.payment_method = IFNULL(payment_method_id,p.payment_method);
END$$
DELIMITER ;
CALL get_payments(NULL,NULL);
CALL get_payments(5,NULL);
CALL get_payments(5,2);
CALL get_payments(NULL,2);