-
Notifications
You must be signed in to change notification settings - Fork 0
/
SQL@_30.sql
1352 lines (1054 loc) · 42.8 KB
/
SQL@_30.sql
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
show databases;
create database mera_database;
-- do not use special characters except _
show databases;
use mera_database;
show tables;
create table Students(
id int,
name varchar(30),
gender char(1)
);
desc students;
insert into students values(16554,"vipin",'M');
select * from students;
insert into students values
(17429,"chandan",'M'),
(17805,"kushagra",'M'),
(null,"krishna",'M'),-- 9871523415
(null,"atul",'M'), -- 8756078385
(null,"hiranmayee",'F'), -- 8801958380
(15805,"anil",'M'),
(15770,"gaurav",'M'),
(17820,"neha",'F'),
(16377,"himanshu",'M'),
(17360,"kundan",'M'),
(17658,"sonia",'F'),
(16796,"ravi",'M'),
(18354,"ankit",'M'),
(17747,"bhumika",'F');
select * from students;
select name,id from students;
-- next staturday recap
-- 11-08-2024
use mera_database;
-- single line comment (here space is mandatory after -- )
# single line comment
/*
multiple
line
comment
*/
/*
what is comment and why comment
1. documentation
2. plugability of query
SQL queries can be categorized into
1. DML -> data manipulation language eg. insert,update,delete
2. DDL -> data defining language eg. create,alter,drop etc
3. DQL -> data query language eg. select
4. DCL -> data control language eg. grant,revoke
5. TCL -> transaction control language eg. commit,rollback,savepoint
*/
drop table students;
create table Employee(empid int,empname varchar(50),
salary float,mobileNo bigint,gender char(1),ismarried bool,
dob date,joining_time timestamp,description text);
-- -2^31 to 2^31 -1 (-2,14,74,83,648 to 2,14,74,83,647)
-- -2^63 to 2^63 -1
-- -2^n-1 to 2^n-1 -1 where n=no. of bits (1 byte =8 bits)
-- medium int => -83,88,608 to 83,88,607
insert into employee values(
100,"Aman Tiwari",56000.1234,
8448179216,'M',false,'2024-08-11',
'2024-08-11 15:10:5',"this is some description");
select * from employee;
desc employee;
insert into employee(empid,empname,gender) select id,name,gender from students;
set sql_safe_updates=0;
update employee set empid=18271 where empname="hiranmayee";
update employee set empid=18269 where empname="krishna";
delete from employee where empid=100;
show databases;
use classicmodels;
show tables;
select * from customers;
-- data filtering through operators (on sunday)
-- 17 Aug 2024
show databases;
create database mera_database;
use mera_database;
/*
multiple
line
comment
*/
-- single line comment (there is space after 2 hyphen)
#single line comment
create table DucatStaff(
id int,name varchar(50),gender char(1),salary decimal(7,2),
ismarried boolean,dob date,joining_date timestamp,address varchar(255),
mobileNo bigint,skills text);
show tables;
-- -2^n-1 to 2^n-1 -1 where n=no. of bits
-- 1 byte = 8 bits
-- int -> 4 bytes
-- -2^31 to 2^31 -1
-- insert into DucatStaff values(2147483647,"Aman","M");
-- insert into DucatStaff values(2147483648,"Aman","M");
drop table DucatStaff;
desc DucatStaff;
insert into DucatStaff(id,name) values(101,"Aman Tiwari");
select *
from ducatstaff;
select name,id
from ducatstaff;
insert into ducatstaff values
(101,"Aman Tiwari",'M',56000.78,true,'2024-8-17','2024-8-17 15:27:10','anand vihar delhi-96',8448179216,"MEAN,MERN,etc"),
(102,"Aman Tiwari",'M',56000.78,true,'2024-8-17','2024-8-17 15:27:10','anand vihar delhi-96',8448179216,"MEAN,MERN,etc"),
(103,"Aman Tiwari",'M',56000.78,true,'2024-8-17','2024-8-17 15:27:10','anand vihar delhi-96',8448179216,"MEAN,MERN,etc"),
(104,"Aman Tiwari",'M',56000.78,true,'2024-8-17','2024-8-17 15:27:10','anand vihar delhi-96',8448179216,"MEAN,MERN,etc");
truncate ducatstaff;
drop table ducatstaff;
use classicmodels;
show tables;
select * from customers;
select * from ducatstaff;
update ducatstaff set salary=72000 ;
delete from ducatstaff;
update ducatstaff set salary=72000 where id=101;
delete from ducatstaff where id=102;
select distinct * from ducatstaff;
-- CRUD
-- classicmodels
use classicmodels;
select * from customers where contactfirstname like 'J%';
desc table classicmodels.customers;
-- operators for data filtering
use classicmodels;
select 10+20;
select 10+20 as sum;
select 10+20 sum;
select 100*0.15 as "15 percent";
select 27%4; -- mod (to find remainder)
-- relational operator for data filtering
-- eg. <,>,<=,>=,=,!= and <>(not equal)
select * from customers;
select customernumber,contactFirstName,phone,
creditlimit,addressline1
from customers;
select count(*) as 'total no. of rows' from customers;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit<50000
-- order by creditlimit desc;
order by contactFirstName;
update customers set contactfirstname="Aman"
where customernumber=447;
update customers set contactlastname="xavier"
where customernumber=293;
update customers set contactfirstname="Aman"
where customernumber=293;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit<110000
order by contactFirstName,contactLastName;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit>110000
order by contactFirstName;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit=110000
order by contactFirstName;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit<=110000
order by creditlimit;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit>=110000
order by creditlimit;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit!=110000
order by creditlimit;
select customernumber,contactFirstName,contactLastName,phone,
creditlimit,addressline1
from customers
where creditlimit<>110000
order by creditlimit;
-- logical operator
select customernumber,contactFirstName,country,phone,
creditlimit
from customers
where creditlimit<=110000 and country="USA"
order by creditlimit;
-- and : both conditions must be true to fetch data
select customernumber,contactFirstName,country,phone,
creditlimit
from customers
where creditlimit<=110000 or country="USA"
order by creditlimit;
/*
and
true true -> true
true false -> false
false true -> false
false false -> false
*/
select customernumber,contactFirstName,country,phone,
creditlimit
from customers
where not country="USA"
order by creditlimit;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where country="USA"
order by creditlimit;
-- wild card
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where contactFirstName like "a%"
order by contactfirstname;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where contactFirstName like "%a"
order by contactfirstname;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where contactFirstName like "%a%"
order by contactfirstname;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where contactFirstName like "_ean"
order by contactfirstname;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where country in ("usa","france")
order by contactfirstname;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where creditlimit between 50000 and 110000
order by contactfirstname;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where creditlimit between 50000 and 110000
order by creditlimit
limit 10;
select customernumber,contactFirstName,country,phone,
creditlimit, creditlimit*1.15 as "15% hike"
from customers
where creditlimit between 50000 and 110000
order by creditlimit
limit 5 offset 10;
-- gniitwala amantiwari8861
-- constraints
use mera_database;
create table Employee(
id int primary key auto_increment,
name varchar(50),
mobileNo bigint not null unique,
email varchar(30) unique,
address varchar(255),
city varchar(50) not null,
country varchar(50) default "india",
age int check(age>=18),
aadharNo bigint not null unique
-- primary key(id)
);
-- unique not null check default
-- primary key (unique and not null)
-- only 1 primary key per table
-- primary key should rarely be changed
-- primary key should be given at the time of data insertion
alter table employee rename column mobieNo to mobileNo;
SET @@auto_increment_increment=2;
truncate employee;
insert into employee(id,mobileNo,city,aadharNo) values(100,13232434,"delhi",343343443);
insert into employee(mobileNo,city,aadharNo) values(1323243365444,"delhi",32344);
insert into employee(mobileNo,city,aadharNo) values(314151512,"delhi",34343443);
insert into employee(city,aadharNo) values("delhi",34343443);
select * from employee;
create table movies(userId int,movieId int primary key auto_increment,
moviename varchar(100),price decimal(5,2),
constraint fk_empId_and_movie foreign key(userId) references employee(id)
);
SET @@auto_increment_increment=1;
INSERT INTO Employee (name, mobileNo, email, address, city, country, age, aadharNo) VALUES
('Amit Sharma', 9876543210, 'amitsharma@example.com', '123 Main Street, Delhi', 'Delhi', 'India', 25, 123456789012),
('Deepika Pandey', 8765432109, 'deepikapandey@example.com', '456 Main Street, Mumbai', 'Mumbai', 'India', 30, 234567890123),
('Raman Raj', 7654321098, 'ramanraj@example.com', '789 Main Street, Kolkata', 'Kolkata', 'India', 35, 345678901234),
('Anjali Singh', 6543210987, 'anjalisingh@example.com', '101 Main Street, Chennai', 'Chennai', 'India', 40, 456789012345);
INSERT INTO movies VALUES
(1,200,'Dilwale Dulhania Le Jayenge', 250.00);
INSERT INTO movies (userId, movieName, price) VALUES
(1, 'Stree 2', 250.00),
(2, 'Sholay', 200.00),
(2, 'Munjya', 200.00),
(3, '3 Idiots', 300.00),
(4, 'Baahubali: The Beginning', 350.00);
select * from employee;
select * from movies;
update movies set userId=null where movieId=205;
-- test
INSERT INTO movies (userId, movieName, price) VALUES
(101, 'Stree 2', 250.00);
update employee set id=101 where id=1;
delete from employee where id=1;
-- many to many
drop database mera_database;
create database mera_database;
use mera_database;
create table user(
id int primary key auto_increment,
name varchar(50),
mobileNo bigint not null unique,
email varchar(30) unique,
address varchar(255),
city varchar(50) not null,
country varchar(50) default "india",
age int check(age>=18),
aadharNo bigint not null unique
-- primary key(id)
);
create table movies(
movieId int primary key auto_increment,
moviename varchar(100),price decimal(5,2));
create table user_movie(userId int,movieId int,rentedAt timestamp default current_timestamp(),
constraint fk_user_id foreign key(userId) references user(id)
on update cascade
on delete cascade,
constraint fk_movie_id foreign key(movieId) references movies(movieId)
on update cascade
-- on delete cascade, error bcz primary key can't be null
on delete cascade,
primary key(userId,movieId)
);
INSERT INTO user (name, mobileNo, email, address, city, country, age, aadharNo) VALUES
('Amit Sharma', 9876543210, 'amitsharma@example.com', '123 Main Street, Delhi', 'Delhi', 'India', 25, 123456789012),
('Deepika Pandey', 8765432109, 'deepikapandey@example.com', '456 Main Street, Mumbai', 'Mumbai', 'India', 30, 234567890123),
('Raman Raj', 7654321098, 'ramanraj@example.com', '789 Main Street, Kolkata', 'Kolkata', 'India', 35, 345678901234),
('Anjali Singh', 6543210987, 'anjalisingh@example.com', '101 Main Street, Chennai', 'Chennai', 'India', 40, 456789012345);
INSERT INTO movies VALUES
(200,'Dilwale Dulhania Le Jayenge', 250.00);
INSERT INTO movies (movieName, price) VALUES
('Stree 2', 250.00),
('Sholay', 200.00),
('Munjya', 200.00),
('3 Idiots', 300.00),
( 'Baahubali: The Beginning', 350.00);
select * from user;
select * from user_movie;
select * from movies;
desc user_movie;
insert into user_movie(userid,movieId) values
(1,200),
(1,201),
(2,200),
(2,203),
(3,204);
truncate user_movie;
truncate user;
drop table user_movie;
truncate user;
drop table user;
drop table movies;
delete from user where id=1;
delete from movies where movieid=204;
-- on update cascade,set null,restrict
-- on delete cascade,set null,restrict
-- joins
-- cross join
create table Table1(A int,B int);
create table Table2(C int,D int);
insert into Table1 values(1,11),(2,22);
insert into Table2 values(33,333),(44,444),(55,555),(66,666);
select * from Table1;
select * from Table2;
select * from Table1,Table2;
create table categories(
categoryid varchar(20) primary key,
category_name varchar(30),
abcd varchar(20));
create table products(
product_id varchar(20),
catid varchar(30),
product_name varchar(30),
xyz varchar(20),
primary key(product_id),
foreign key (catid) references categories (categoryid)
);
insert into categories values(
101, 'phones', 'any description'),
(102, 'laptop', 'any description'),
(103, 'fashion', 'any description'),
(104, 'food', 'any description'),
(105,'guns', 'any description');
insert into products values
(201,101,'realmext', 'hello'),
(202,101, 'redmi note 9', 'hello'),
(203,102,'hp', 'hello'),
(204, 102, 'dell vestro', 'hello'),
(205,103,'shirt', 'hello'),
(206, null, 'others', 'hello'),
(207, null, 'watch', 'hello');
select * from categories;
select * from products;
-- Alias (Nickname)
select 10+20 as 'sum';
select 10+20 'sum';
select 10+20 sum;
-- inner join
select *
from categories
inner join products
on categories.categoryid = products.catid;
select *
from categories c
inner join products p
on c.categoryid = p.catid;
select * from user;
select * from user_movie;
select * from movies;
select *
from user u
inner join user_movie um
on u.id=um.userid
inner join movies m
on um.movieId=m.movieId;
select u.id,u.name,m.moviename,m.price,um.rentedAt
from user u
inner join user_movie um
on u.id=um.userid
inner join movies m
on um.movieId=m.movieId;
select u.id,u.name,m.moviename,m.price,um.rentedAt
from user u
inner join user_movie um
on u.id=um.userid
inner join movies m
on um.movieId=m.movieId
where m.movieid=200;
insert into user_movie values(4,200,current_timestamp());
-- Alter Query
-- 1) Used to make changes in the structure of the table.
-- 2) There are 4 commands with the alter query
-- a) change - Used to rename a column + add/change its data types +
-- add/change/remove its constraints.
-- b) modify - Used to change the data types of a colum +
-- add/change/remove its constraints
-- c) add - used to add a new column with its data type + add constraint
-- d) drop - used to drop an exitsing column
-- e) rename - used to rename a column.
create database mera_database;
use mera_database;
CREATE TABLE departments (
department_id INT AUTO_INCREMENT PRIMARY KEY,
department_name VARCHAR(50) NOT NULL
);
CREATE TABLE employees (
employee_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100),
department_id INT,
salary DECIMAL(10, 2)
);
desc departments;
desc employees;
drop table employees;
-- Dropping a Primary Key with auto_increment
alter table employees modify column employee_Id int; -- to remove auto_increment
insert into employees (first_name) values("Aman");
ALTER TABLE employees DROP PRIMARY KEY; -- after removing primary key the column is not null
insert into employees (employee_id) values(100);
insert into employees (employee_id) values(100);
select * from employees;
truncate employees;
-- Adding a Primary Key
ALTER TABLE employees ADD PRIMARY KEY (employee_id);
-- Adding a Unique Constraint
ALTER TABLE employees ADD CONSTRAINT unique_email UNIQUE (email);
-- Adding a Foreign Key Constraint
ALTER TABLE employees
ADD CONSTRAINT fk_department
FOREIGN KEY (department_id) REFERENCES departments(department_id);
-- Adding a Check Constraint (MySQL 8.0.16 and later)
select version();
ALTER TABLE employees ADD CONSTRAINT check_salary CHECK (salary > 0);
-- to add the not null constraint
alter table employees modify department_id int not null ;
-- to drop the not null constraints
alter table employees modify department_id int default null;
-- or
alter table employees modify department_id int ;
insert into employees(employee_id,salary) values(101,-566);
-- Dropping a Unique Constraint
alter table employees modify column email varchar(50);
ALTER TABLE employees DROP INDEX unique_email;
-- Dropping a Foreign Key Constraint
ALTER TABLE employees DROP FOREIGN KEY fk_department;
-- Dropping a Check Constraint (MySQL 8.0.16 and later)
ALTER TABLE employees DROP CONSTRAINT check_salary;
-- Adding Constraints
ALTER TABLE employees
ADD CONSTRAINT unique_email UNIQUE (email);
ALTER TABLE employees
ADD CONSTRAINT fk_department
FOREIGN KEY (department_id) REFERENCES departments(department_id);
ALTER TABLE employees ADD CONSTRAINT check_salary CHECK (salary > 0);
-- Disabling Foreign Key Checks
SET foreign_key_checks = 0; -- 0 means false
-- Performing Bulk Insert
INSERT INTO departments (department_name) VALUES ('HR'), ('IT'), ('Finance');
INSERT INTO employees (first_name, last_name, email, department_id, salary)
VALUES ('John', 'Doe', 'john.doe@example.com', 1, 5000),
('Jane', 'Smith', 'jane.smith@example.com', 2, 6000);
-- Enabling Foreign Key Checks
SET foreign_key_checks = 1;-- 1 means true
-- Dropping Constraints
ALTER TABLE employees DROP INDEX unique_email;
ALTER TABLE employees
DROP FOREIGN KEY fk_department;
ALTER TABLE employees
DROP CONSTRAINT check_salary;
alter table employees add column xyz int;
alter table employees add column abc int not null unique ;
alter table employees add column abc2 int after employee_id ;
alter table employees add column abc0 int first ;
alter table employees drop column abc0;
alter table employees drop abc2;
alter table employees modify column abc double ;
ALTER TABLE employees DROP INDEX abc;
desc employees;
alter table employees rename column email to email_id;
alter table employees rename to ducat_employees;
show create table employees;
desc ducat_employees;
-- views
use classicmodels;
select * from customers;
create view CustomerKYCview
as
select customerNumber,customerName,
addressline1,phone,city,state,country
from customers
where country='usa';
select * from CustomerKYCview;
drop view CustomerKYCview ;
update CustomerKYCview set addressline1="sector 14 gurugram"
where customernumber=112;
select * from customers;
delete from CustomerKYCview
where addressline1="sector 14 gurugram";
-- functions -> string,date,time & window
-- function & stored procedures
-- reading & writing csv
use classicmodels;
select * from customers;
select * from customers limit 10; -- 131
select * from customers limit 5 offset 10; -- 141
-- functions : group of statements which together performs a task
-- advantages of function
-- 1. reusability
-- 2. modularity
-- there are 2 types of function
-- 1.pre-defined/built-in function
-- 2.user-defined function
select curdate();
select length("8448179216");
-- parameters ,return type ,function defination ,function name
-- user defined functions
/*
If you use the mysql client program to define a
stored program containing semicolon characters, a problem arises.
By default, mysql itself recognizes the semicolon as a statement delimiter,
so you must redefine the delimiter temporarily to cause mysql to pass the
entire stored program definition to the server.
To redefine the mysql delimiter, use the delimiter command.
delimiter is changed to $$ to enable the entire definition to be passed to the
server as a single statement, and then restored to ; before invoking the procedure.
This enables the ; delimiter used in the procedure body to be passed through
to the server rather than being interpreted by mysql itself.
*/
use classicmodels;
delimiter //
create function addFxn(a int,b int) returns int
deterministic
begin
declare c int;
set c=5;
return a+b+c;
end //
delimiter ;
select addFxn(10,20); -- calling of addFxn
-- select addFxn((select 10),20); -- calling of addFxn
drop function addFxn;
select addFxn(1,3),addFxn(5,3) as sum,addFxn(10,3),addFxn(1,30);
DELIMITER $$
CREATE FUNCTION CustomerLevel(
credit DECIMAL(10,2)
)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE customerLevel VARCHAR(20);
IF credit > 50000 THEN
SET customerLevel = 'PLATINUM';
ELSEIF (credit >= 10000 and credit <= 50000 ) THEN
SET customerLevel = 'GOLD';
ELSEIF credit < 10000 THEN
SET customerLevel = 'SILVER';
END IF;
-- return the customer level
RETURN (customerLevel);
END$$
DELIMITER ;
select customerNumber,contactFirstname,phone,
creditlimit,customerlevel(creditlimit)
from customers;
drop function CustomerLevel;
-- pre-defined string,date and time functions
-- String functions - LCase, UCase, Length, Mid, concat
select lcase('NASA');
select lower('HELLO');
select ucase('india') as Country;
select upper('india') as Country;
select Length('HEllo') as Length; -- length of the string
-- add1,add2,city
select lcase('hello');
select concat('Hello',' ','World');
select concat(ucase('hello'),' ',ucase('world'));
-- trim - removes leading or trailing whitespace from string
select length(' Welcome to SQL '); -- 16
select trim(' Welcome to SQL '), length(trim(' Welcome to SQL '));
select ltrim(' Welcome to SQL '), length(ltrim(' Welcome to SQL '));
select rtrim(' Welcome to SQL '), length(rtrim(' Welcome to SQL '));
select reverse('Welcome to SQL');
-- 1) insert (str1,pos,no,str2)
-- str1 - str to be modified or inserted into
-- pos - index where str2 will be inserted into str1
-- index starts from 1
-- no - No of chars to replace
-- str2 - str to be inserted into str1
select insert('welcome to SQL', 1, 7, 'Python'); -- Python to SQL
select insert('welcome to SQL', 1, 5, 'Python'); -- Pythonme to SQL
select insert('Dell laptop vs HP Laptop', 16, 2, 'ASUS'); --
select insert('Good morning',6,7,'evening India'); --
select insert('Good morning',3,5,'evening'); -- Goeveningrning
-- 2) replace(str1,str2,str3)
-- str1 - string in which replacement will happen
-- str2 - a substring of str1 which will be replaced
-- str3 - The string with which str2 will be replaced with in str1
select replace("Welcome to SQL", "SQL", "Python");
select replace("Welcome to SQL", "sql", "Python");
select replace("MySQL to SQLServer", "SQL", "Python");
select replace("Covid cases are rising", "rising", "falling");
select replace("Covid XE", "XE", "Delta") as Covid_data;
select replace("Covid XE", "vid", "vaxin") as Covid_data;
SELECT replace("Hello world","when","India");
SELECT replace("Hello world sql","SQL","India"); -- no replacement
select replace("S Hello Q world L","SQL","India"); -- no replacement
select replace("Hello world","o","India");
select replace(" Hello world "," ","___");
-- 3) mid(str,start,len)
-- It is used to extract a substring from a string (starting at any position).
-- str - The str to extract from
-- start - Starting index, can be +ve or -ve.
-- Index starts from 1(towards +ve) from left to right
-- Index starts from -1(towards -ve) from right to left
-- len - No of chars to extract (in left to right direction)
-- 1 2 3 4 5
-- T o d a y
-- -5 -4 -3 -2 -1
select length('Startups in India'); -- 17
select mid("Startups in India",4,7); -- rtups i
select mid("Startups in India",1,5); -- Start
select mid('Today',-3,2); --
select mid("Startups in India",-5,5); -- India
select mid("Startups in India",-8,4); -- in I
select mid("Startups in India",-3,7); -- dia
select mid('ING-2143-D7',1,3) as Flight_Name,
mid('ING-2143-D7',5,4) as Flight_Code,
mid('ING-2143-D7',-2,2) as Seat_num;
select mid('PGA-23224',1,3) as Course, mid('PGA-23224',5,5) as Batch;
-- 4) repeat(str,n)
-- It repeats a string n number of times
select repeat("Hello ",3) as Ex_str,length(repeat("Hello ",3)) as Len;
-- 5) Lpad(str,len,lpad_str)
-- str - str which will be padded
-- len - len of resultant str after padding
-- lpad_str - the str to left_pad str
select lpad('5264', 7,'AI-'); -- AI-5264
select lpad('5264', 10,'AI-'); -- AI-AI-5264
select lpad('5264', 9,'AI-'); -- AI-AI5264
select lpad('5264',10,'I-');
select lpad('5264',10,'I-');
-- 6) Rpad(str,len,rpad_str)
-- str - str which will be padded
-- len - len of resultant str agter padding
-- lpad_str - the str to right_pad str
select rpad('5264', 7,'-AI'); -- 5264-AI
select rpad('5264', 10,'-AI'); -- 5264-AI-AI
select rpad('5264', 8,'-AI'); -- 5264-AI-
# 1 2 3 4 5
# T O D A Y
-- 7) position(substr IN str)
-- It returns the position(index) of the first occurrence of the substring
-- in the left to right direction in the string
-- substr - The substr to be searched on str
-- str - The str that will be searched
-- if substr is not in str, result is 0
select position("7" IN "Hello 2378234") AS MatchPosition;
select position("7" IN "Hello 273982734") AS MatchPosition;
select position("llo" IN "Hello 23782734") AS MatchPosition;
select position("eo" IN "Hello 23782734") AS MatchPosition; -- 0
select position("and" IN "Hello 23782734") AS MatchPosition;
-- 8) Left(str,n)
-- Extract n chars from left of the str
select left("Welcome to SQL",7);
-- 9) Right(str,n)
-- Extract n chars from right of the str
select right("Welcome to SQL",6);
-- left,right,mid,position,insert or replace, lpad,rpad
## Date functions
## YYYY-MM-DD or YYYY/MM/DD
## DateTime
## YYYY-MM-DD HH:MM:SS
select now(); -- returns current date and time -- YYYY-MM-DD HH:MM:SS, HH in 24 hr clock
select date(now());
select year(now()), month(now()), day(now()), quarter(now());
select monthname(now()), dayname(now());
select curdate(); -- returns current date
select year(curdate()), month(curdate()), day(curdate()), quarter(curdate());
select date('2023-02-07 14:23:56') as Date;
select year('2019-10-08'), month('2019-10-08'), day('2019-10-08'),quarter('2019-10-08');
select year('10-13-2010'); -- null value
select dayname('2018-09-24');
select dayofweek('2022/08/16');
select dayofweek('2023/04/21');
# 1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday,
# 5=Thursday, 6=Friday, 7=Saturday.
select weekday('2022/11/12');
select weekday('2023-04-21') as Wday;
-- Mon-0,Tue-1, Wed-2, Thu-3,Fri-4,Sat-5,Sun-6
select week('2022-04-21') as Week;
select week('2022-11-12 14:23:56') as Week; -- 45
select weekofyear('2022-04-21 14:23:56') as Week_of_Year; -- 45
select week('2021-12-31') as Dec_LastWeek; -- 52
select week('2022-01-01') as Jan_Week1; -- 0 (Sat)
select week('2022-01-02') as Jan_Week1; -- 1
select week('2022-01-03') as Jan_Week1; -- 1
select week('2022-01-10') as Jan_Week1; -- 2
-- New week starts from Sun as per week()
select weekofyear('2021-12-31') as Dec_LastWeek; -- 52
select weekofyear('2022-01-01') as Jan_Week1; -- 52
select weekofyear('2022-01-02') as Jan_Week1; -- 52
select weekofyear('2022-01-03') as Jan_Week1; -- 1
-- New week starts from Mon as per weekofyear()
-- Time Functions
-- HH:MM:SS
select time(now());
select hour(now()), minute(now()), second(now());
select hour('17:45:26'),minute('17:45:26'), second('17:45:26');
select minute('1999/10/23 14:23:56') as Min;
select hour('1999/10/23 14:23:56') as Hr;
select second('1999/10/23 14:23:56') as Sec;
select hour('1999/10/23') as Sec; # Null
-- Date Time Addition and Subtraction
-- select adddate(date,days_to_be_added)
select adddate('2012-10-05',12); -- addition of day
select adddate('2012-10-05',-15); -- subtraction of day
select adddate('2012-12-28',12);
select adddate(date(now()),5); -- addition of day
select adddate('2012-10-05',interval 1 year); -- addition of year
select adddate('2012-10-05',interval -3 year); -- subtraction of year
select adddate('2012-10-05',interval 1 quarter); -- addition of quarter