-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday6.sql
2482 lines (1821 loc) · 83.3 KB
/
day6.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
-- Create the airline database if it does not already exist
CREATE DATABASE IF NOT EXISTS airline123;
USE airline123; -- Set the context to the airline database
-- Functions
/*
Functions in MySQL are predefined operations that can be used to perform calculations, manipulate data,
and retrieve specific information. These functions make it easier to work with strings, numbers, dates, and more.
Functions--- 1. Built-in functions (sum(),avg(),count()...)
2. User defined functions.
They are categorized as follows based on their functionality:
1. String Functions
These functions are used to manipulate and process string data.
LENGTH(str): Returns the length of a string.
CONCAT(str1, str2, ...): Concatenates two or more strings.
UPPER(str): Converts a string to uppercase.
LOWER(str): Converts a string to lowercase.
SUBSTRING(str, start, length): Returns a substring from a string.
2. Numeric Functions
These functions perform operations on numeric data.
ROUND(number, decimals): Rounds a number to a specified number of decimal places.
FLOOR(number): Returns the largest integer less than or equal to a number.
CEIL(number): Returns the smallest integer greater than or equal to a number.
ABS(number): Returns the absolute value of a number.
3. Date and Time Functions
These functions are used to manipulate and format date and time values.
NOW(): Returns the current date and time.
CURDATE(): Returns the current date.
DATE_FORMAT(date, format): Formats a date according to a specified format.
DATEDIFF(date1, date2): Returns the difference in days between two dates.
4. Aggregate Functions
These functions perform calculations on a set of values and return a single value.
COUNT(expression): Returns the number of rows that match a specified condition.
SUM(column): Returns the sum of a numeric column.
AVG(column): Returns the average value of a numeric column.
MAX(column): Returns the maximum value of a column.
MIN(column): Returns the minimum value of a column.
5. Control Flow Functions
These functions allow for conditional logic in SQL queries.
IF(condition, true_value, false_value): Returns one value if the condition is true and another value
if it is false.
CASE: Provides a way to perform conditional logic in a more complex manner.
6. Conversion Functions
These functions convert data from one type to another.
CAST(expression AS type): Converts an expression to a specified data type.
CONVERT(expression, type): Similar to CAST, but with different syntax.
7. JSON Functions
These functions are used to work with JSON data types.
JSON_EXTRACT(json_doc, path): Extracts data from a JSON document.
JSON_ARRAYAGG(value): Aggregates values into a JSON array.
8. User -Defined Functions (UDFs)
MySQL allows users to create their own functions for specific tasks.
*/
-- ------------------------------------Table Queries --------------------------------------
-- Data Definition Language (DDL) {Create,Alter,Drop,Truncate,Rename,Comment}
-- Data Manipulation Language (DML) {Insert, Update, Delete}
-- Data Query Language (DQL) {select query}
-- Table-1 Create Flights table
CREATE TABLE Flights (
Flight_ID INT PRIMARY KEY, -- Unique identifier for each flight (Primary Key)
Flight_Number VARCHAR(10) NOT NULL, -- Flight number (e.g., AA123) (Not Null)
Departure_Airport VARCHAR(100) NOT NULL, -- Name of the departure airport (Not Null)
Arrival_Airport VARCHAR(100) NOT NULL, -- Name of the arrival airport (Not Null)
Departure_Time DATETIME NOT NULL, -- Scheduled departure time (Not Null)
Arrival_Time DATETIME NOT NULL, -- Scheduled arrival time (Not Null)
Flight_Duration INT NOT NULL, -- Duration of the flight in minutes (Not Null)
Seats_Available INT NOT NULL CHECK (Seats_Available >= 0),
-- Number of available seats (Not Null, must be non-negative)
Aircraft_Type VARCHAR(50) NOT NULL, -- Type of aircraft used for the flight (Not Null)
Status ENUM('On Time', 'Delayed', 'Cancelled') NOT NULL DEFAULT 'On Time'
-- Current status of the flight (Not Null, default is 'On Time')
);
-- Insert Records into Flights Table
INSERT INTO Flights (Flight_ID, Flight_Number, Departure_Airport, Arrival_Airport, Departure_Time, Arrival_Time, Flight_Duration, Seats_Available, Aircraft_Type, Status)
VALUES
(1, 'AI101', 'Delhi (DEL)', 'Mumbai (BOM)', '2023-10-01 06:00:00', '2023-10-01 08:00:00', 120, 50, 'Boeing 737', 'On Time'),
(2, 'AI102', 'Mumbai (BOM)', 'Delhi (DEL)', '2023-10-01 09:00:00', '2023-10-01 11:00:00', 120, 60, 'Airbus A320', 'On Time'),
(3, 'AI103', 'Delhi (DEL)', 'Bangalore (BLR)', '2023-10-01 07:00:00', '2023-10-01 09:30:00', 150, 70, 'Boeing 737', 'On Time'),
(4, 'AI104', 'Bangalore (BLR)', 'Delhi (DEL)', '2023-10-01 10:00:00', '2023-10-01 12:30:00', 150, 80, 'Airbus A320', 'On Time'),
(5, 'AI105', 'Delhi (DEL)', 'Chennai (MAA)', '2023-10-01 08:00:00', '2023-10-01 10:30:00', 150, 40, 'Boeing 737', 'On Time'),
(6, 'AI106', 'Chennai (MAA)', 'Delhi (DEL)', '2023-10-01 11:00:00', '2023-10-01 13:30:00', 150, 50, 'Airbus A320', 'On Time'),
(7, 'AI107', 'Delhi (DEL)', 'Kolkata (CCU)', '2023-10-01 09:00:00', '2023-10-01 11:30:00', 150, 30, 'Boeing 737', 'On Time'),
(8, 'AI108', 'Kolkata (CCU)', 'Delhi (DEL)', '2023-10-01 12:00:00', '2023-10-01 14:30:00', 150, 20, 'Airbus A320', 'On Time'),
(9, 'AI109', 'Delhi (DEL)', 'Hyderabad (HYD)', '2023-10-01 10:00:00', '2023-10-01 12:30:00', 150, 60, 'Boeing 737', 'On Time'),
(10, 'AI110', 'Hyderabad (HYD)', 'Delhi (DEL)', '2023-10-01 13:00:00', '2023-10-01 15:30:00', 150, 50, 'Airbus A320', 'On Time'),
(11, 'AI111', 'Delhi (DEL)', 'Pune (PNQ)', '2023-10-01 14:00:00', '2023-10-01 16:00:00', 120, 40, 'Boeing 737', 'On Time'),
(12, 'AI112', 'Pune (PNQ)', 'Delhi (DEL)', '2023-10-01 17:00:00', '2023-10-01 19:00:00', 120, 30, 'Airbus A320', 'On Time'),
(13, 'AI113', 'Delhi (DEL)', 'Ahmedabad (AMD)', '2023-10-01 15:00:00', '2023-10-01 17:00:00', 120, 50, 'Boeing 737', 'On Time'),
(14, 'AI114', 'Ahmedabad (AMD)', 'Delhi (DEL)', '2023-10-01 18:00:00', '2023-10-01 20:00:00', 120, 40, 'Airbus A320', 'On Time'),
(15, 'AI115', 'Delhi (DEL)', 'Jaipur (JAI)', '2023-10-01 16:00:00', '2023-10-01 17:30:00', 90, 60, 'Boeing 737', 'On Time');
select * from flights;
-- Select, Alter, delete & update Queries
/*
1. SELECT Query
The SELECT statement is used to retrieve data from a database table.
It allows you to specify the columns you want to fetch and apply conditions to filter the results.
Syntax-
SELECT column1, column2, ...
FROM table_name
WHERE condition;
2. ALTER Query
The ALTER statement is used to modify the structure of an existing table,
such as adding, deleting, or modifying columns.
The ALTER query changes the table structure, not the data.
Syntax-
ALTER TABLE table_name
ADD column_name datatype;
-- or
ALTER TABLE table_name
DROP COLUMN column_name;
-- or
ALTER TABLE table_name
MODIFY column_name new_datatype;
3. DELETE Query
The DELETE statement is used to remove rows from a table based on a specified condition.
Syntax-
DELETE FROM table_name
WHERE condition;
4. UPDATE Query
The UPDATE statement is used to modify existing records in a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
*/
-- 1. Select Queries
-- Select all records from Flights table
SELECT * FROM Flights;
-- Select flights that are delayed
SELECT * FROM Flights WHERE Status = 'Delayed';
-- Select distinct aircraft types used in flights
SELECT DISTINCT Aircraft_Type FROM Flights;
-- Select all flights ordered by Departure_Time
SELECT * FROM Flights ORDER BY Departure_Time;
-- Count the number of flights per status
SELECT Status, COUNT(*) AS NumberOfFlights
FROM Flights
GROUP BY Status;
-- Select statuses with more than 5 flights
SELECT Status, COUNT(*) AS NumberOfFlights
FROM Flights
GROUP BY Status
HAVING COUNT(*) > 5;
-- Select Flights from a Specific Departure Airport
SELECT * FROM Flights WHERE Departure_Airport = 'Delhi (DEL)';
-- Select Flights with More Than 50 Seats Available
SELECT * FROM Flights WHERE Seats_Available > 50;
-- Select Flights Ordered by Arrival Time
SELECT * FROM Flights ORDER BY Arrival_Time;
-- Select Flights with a Duration Greater Than 120 Minutes
SELECT * FROM Flights WHERE Flight_Duration > 120;
-- Select Distinct Aircraft Types
SELECT DISTINCT Aircraft_Type FROM Flights;
-- Select Flights with Arrival Time After a Specific Date
SELECT * FROM Flights WHERE Arrival_Time > '2023-10-01 12:00:00';
-- Select Flights with a Specific Flight Number
SELECT * FROM Flights WHERE Flight_Number = 'AI101';
-- 2. Update Queries
-- Update the number of available seats for a specific flight
UPDATE Flights
SET Seats_Available = 45
WHERE Flight_ID = 1;
-- Update the Status of a Flight
UPDATE Flights SET Status = 'Cancelled' WHERE Flight_ID = 1;
-- Update the Arrival Airport for a Specific Flight
UPDATE Flights SET Arrival_Airport = 'Chennai (MAA)' WHERE Flight_ID = 3;
-- Update the Flight Duration for a Specific Flight
UPDATE Flights SET Flight_Duration = 130 WHERE Flight_ID = 4;
-- Update the Aircraft Type for a Specific Flight
UPDATE Flights SET Aircraft_Type = 'Boeing 777' WHERE Flight_ID = 5;
-- Update the Departure Time for a Specific Flight
UPDATE Flights SET Departure_Time = '2023-10-01 07:00:00' WHERE Flight_ID = 6;
-- Update Multiple Fields for a Specific Flight
UPDATE Flights SET Seats_Available = 60, Status = 'On Time' WHERE Flight_ID = 7;
-- Update Status for All Delayed Flights
UPDATE Flights SET Status = 'On Time' WHERE Status = 'Delayed';
-- Update the Flight Number for a Specific Flight
UPDATE Flights SET Flight_Number = 'AI201' WHERE Flight_ID = 8;
-- Update the Departure Airport for Multiple Flights
UPDATE Flights SET Departure_Airport = 'Delhi (DEL)' WHERE Arrival_Airport = 'Mumbai (BOM)';
-- 3. Delete Queries
-- Delete a specific flight
DELETE FROM Flights
WHERE Flight_ID = 2;
-- Delete All Delayed Flights
DELETE FROM Flights WHERE Status = 'Delayed';
-- Delete Flights with No Available Seats
DELETE FROM Flights WHERE Seats_Available = 0;
-- Delete a Flight by Flight Number
DELETE FROM Flights WHERE Flight_Number = 'AI101';
-- Delete Flights Departing Before a Specific Date
DELETE FROM Flights WHERE Departure_Time < '2023-10-01 00:00:00';
-- Delete All Flights to a Specific Destination
DELETE FROM Flights WHERE Arrival_Airport = 'Jaipur (JAI)';
-- Delete Flights with a Duration Less Than a Specific Value
DELETE FROM Flights WHERE Flight_Duration < 90;
-- Delete Flights with a Specific Status
DELETE FROM Flights WHERE Status = 'Cancelled';
-- Delete Flights with a Specific Aircraft Type
DELETE FROM Flights WHERE Aircraft_Type = 'Airbus A320';
-- Delete All Flights with Less Than 30 Seats Available
DELETE FROM Flights WHERE Seats_Available < 30;
-- 4. Alter Queries
-- Add a new column for flight's terminal
ALTER TABLE Flights
ADD COLUMN Terminal VARCHAR(10);
-- Drop the Terminal column from Flights table
ALTER TABLE Flights
DROP COLUMN Terminal;
-- Add a New Column for Flight's Airline
ALTER TABLE Flights ADD COLUMN Airline VARCHAR(50);
-- Change the Data Type of Flight_Number
ALTER TABLE Flights MODIFY Flight_Number VARCHAR(15);
-- Rename the Arrival_Airport Column
ALTER TABLE Flights RENAME COLUMN Arrival_Airport TO Destination_Airport;
-- Add a Default Value for Seats_Available
ALTER TABLE Flights ALTER COLUMN Seats_Available SET DEFAULT 100;
-- Rename the Flights Table
ALTER TABLE Flights RENAME TO Flight_Schedules;
-- 5. Add & drop Constraints Queries
-- Add a CHECK constraint to ensure Flight_Duration is positive
ALTER TABLE Flights
ADD CONSTRAINT chk_flight_duration CHECK (Flight_Duration > 0);
-- Drop the CHECK constraint on Flight_Duration
ALTER TABLE Flights
DROP CONSTRAINT chk_flight_duration;
-- Add a CHECK Constraint for Flight Duration
ALTER TABLE Flights ADD CONSTRAINT chk_flight_duration CHECK (Flight_Duration > 0);
-- Drop the CHECK Constraint on Flight Duration
ALTER TABLE Flights DROP CONSTRAINT chk_flight_duration;
-- Add a UNIQUE Constraint on Flight_Number
ALTER TABLE Flights ADD CONSTRAINT unique_flight_number UNIQUE (Flight_Number);
-- Add a CHECK Constraint for Seats Available
ALTER TABLE Flights ADD CONSTRAINT chk_seats_available CHECK (Seats_Available >= 0);
-- Drop the CHECK Constraint on Seats Available
ALTER TABLE Flights DROP CONSTRAINT chk_seats_available;
-- Add a FOREIGN KEY Constraint (if applicable)
ALTER TABLE Flights ADD CONSTRAINT fk_airport FOREIGN KEY (Departure_Airport) REFERENCES Airports(Airport_Name);
-- Drop the FOREIGN KEY Constraint
ALTER TABLE Flights DROP CONSTRAINT fk_airport;
-- Add a NOT NULL Constraint to Flight_Number
ALTER TABLE Flights MODIFY Flight_Number VARCHAR(10) NOT NULL;
-- Drop the NOT NULL Constraint from Flight_Number
ALTER TABLE Flights MODIFY Flight_Number VARCHAR(10);
-- Add a DEFAULT Constraint for Status
ALTER TABLE Flights ALTER COLUMN Status SET DEFAULT 'On Time';
-- Drop the DEFAULT Constraint for Status
ALTER TABLE Flights ALTER COLUMN Status DROP DEFAULT;
-- Add a UNIQUE Constraint on Aircraft_Type
ALTER TABLE Flights ADD CONSTRAINT unique_aircraft_type UNIQUE (Aircraft_Type);
-- Drop the UNIQUE Constraint on Aircraft_Type
ALTER TABLE Flights DROP CONSTRAINT unique_aircraft_type;
-- Clauses {Where, Distinct, From, Order By, Group By, Having}
/*
1. WHERE Clause
The WHERE clause is used to filter records in a table based on specific conditions.
It is typically used with SELECT, UPDATE, and DELETE statements.
Syntax:
SELECT column1, column2
FROM table_name
WHERE condition;
2. DISTINCT Clause
The DISTINCT clause is used to return unique values from a column by removing duplicates
in the result set.
Syntax:
SELECT DISTINCT column1
FROM table_name;
3. FROM Clause
The FROM clause specifies the table or tables from which the data is retrieved.
It is a mandatory part of the SELECT statement and can also be used with joins for
combining data from multiple tables.
Syntax:
SELECT column1, column2
FROM table_name;
4. ORDER BY Clause
The ORDER BY clause is used to sort the result set in ascending (ASC) or descending (DESC) order
based on one or more columns.
Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column_name [ASC|DESC];
5. GROUP BY Clause
The GROUP BY clause groups rows with the same values into summary rows,
often used with aggregate functions (e.g., COUNT, SUM, AVG).
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
6. HAVING Clause
The HAVING clause is used to filter grouped data after the GROUP BY clause.
It works similarly to the WHERE clause but is applied to aggregated results.
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
7. LIMIT (or FETCH or TOP) Clause
The LIMIT clause is used to restrict the number of rows returned by a query.
Different databases may use variations like FETCH or TOP.
Syntax (MySQL):
SELECT column1, column2
FROM table_name
LIMIT number_of_rows;
8. JOIN Clause
The JOIN clause is used to combine rows from two or more tables based on a related column.
Syntax:
SELECT columns
FROM table1
JOIN table2
ON table1.common_column = table2.common_column;
9. UNION Clause
The UNION clause is used to combine the results of two or more SELECT statements.
Duplicate rows are removed by default.
Syntax:
SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;
10.INTO Clause
The INTO clause is used to insert query results into a new table or export data.
Syntax:
SELECT columns
INTO new_table_name
FROM table_name
WHERE condition;
11.CASE Clause
The CASE clause allows conditional logic in SQL queries, similar to an if-else statement.
Syntax:
SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias_name
FROM table_name;
12. IN Clause
The IN clause is used to filter records based on a list of values.
Syntax:
SELECT column1, column2
FROM table_name
WHERE column_name IN (value1, value2, ...);
13. BETWEEN Clause
The BETWEEN clause filters data within a specified range, inclusive of the boundaries.
Syntax:
SELECT column1, column2
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
14. LIKE Clause
The LIKE clause is used to search for a specified pattern in a column. Wildcards include % (any number of
characters) and _ (a single character).
Syntax:
SELECT column1, column2
FROM table_name
WHERE column_name LIKE pattern;
15. EXISTS Clause
The EXISTS clause checks for the existence of rows in a subquery.
Syntax:
SELECT column1, column2
FROM table_name
WHERE EXISTS (subquery);
16. AS Clause
The AS clause is used to provide an alias (temporary name) for columns or tables,
improving query readability.
Syntax:
SELECT column_name AS alias_name
FROM table_name;
*/
-- 1. WHERE Clause Queries
-- Select flights that are delayed
SELECT * FROM Flights WHERE Status = 'Delayed';
-- Select flights departing from Delhi
SELECT * FROM Flights WHERE Departure_Airport = 'Delhi (DEL)';
-- Select flights arriving in Mumbai
SELECT * FROM Flights WHERE Arrival_Airport = 'Mumbai (BOM)';
-- Select flights with a duration greater than 120 minutes
SELECT * FROM Flights WHERE Flight_Duration > 120;
-- Select flights with available seats less than 30
SELECT * FROM Flights WHERE Seats_Available < 30;
-- Select flights that departed after a specific date
SELECT * FROM Flights WHERE Departure_Time > '2023-10-01 00:00:00';
-- Select flights with a specific flight number
SELECT * FROM Flights WHERE Flight_Number = 'AI101';
-- Select flights that are either cancelled or delayed
SELECT * FROM Flights WHERE Status IN ('Cancelled', 'Delayed');
-- Select flights with a flight duration between 90 and 150 minutes
SELECT * FROM Flights WHERE Flight_Duration BETWEEN 90 AND 150;
-- Select flights with more than 50 available seats
SELECT * FROM Flights WHERE Seats_Available > 50;
-- 2. DISTINCT Clause Queries
select * from flights;
-- Select distinct aircraft types used in flights
SELECT DISTINCT Aircraft_Type FROM Flights;
-- Select distinct departure airports
SELECT DISTINCT Departure_Airport FROM Flights;
-- Select distinct arrival airports
SELECT DISTINCT Arrival_Airport FROM Flights;
-- Select distinct flight statuses
SELECT DISTINCT Status FROM Flights;
-- Select distinct flight numbers
SELECT DISTINCT Flight_Number FROM Flights;
-- Select distinct combinations of departure and arrival airports
SELECT DISTINCT Departure_Airport, Arrival_Airport FROM Flights;
-- Select distinct flight durations
SELECT DISTINCT Flight_Duration FROM Flights;
-- Select distinct departure times
SELECT DISTINCT Departure_Time FROM Flights;
-- Select distinct arrival times
SELECT DISTINCT Arrival_Time FROM Flights;
-- Select distinct seat availability counts
SELECT DISTINCT Seats_Available FROM Flights;
-- 3. FROM Clause Queries
-- Select all records from Flights table
SELECT * FROM Flights;
-- Select flight numbers and statuses from Flights table
SELECT Flight_Number, Status FROM Flights;
-- Select departure and arrival airports from Flights table
SELECT Departure_Airport, Arrival_Airport FROM Flights;
-- Select flight ID and duration from Flights table
SELECT Flight_ID, Flight_Duration FROM Flights;
-- Select all columns from Flights table where status is 'On Time'
SELECT * FROM Flights WHERE Status = 'On Time';
-- Select all flights with a specific aircraft type
SELECT * FROM Flights WHERE Aircraft_Type = 'Boeing 737';
-- Select all flights departing after a specific time
SELECT * FROM Flights WHERE Departure_Time > '2023-10-01 12:00:00';
-- Select all flights arriving in a specific city
SELECT * FROM Flights WHERE Arrival_Airport = 'Chennai (MAA)';
-- Select all flights with available seats greater than 40
SELECT * FROM Flights WHERE Seats_Available > 40;
-- Select all flights with a specific flight duration
SELECT * FROM Flights WHERE Flight_Duration = 120;
-- 4. ORDER BY Clause Queries
-- Select all flights ordered by Departure_Time
SELECT * FROM Flights ORDER BY Departure_Time;
-- Select all flights ordered by Flight_Duration in descending order
SELECT * FROM Flights ORDER BY Flight_Duration DESC;
-- Select all flights ordered by Seats_Available
SELECT * FROM Flights ORDER BY Seats_Available;
-- Select all flights ordered by Status and then by Departure_Time
SELECT * FROM Flights ORDER BY Status, Departure_Time;
SELECT * FROM Flights ORDER BY Arrival_Airport, Departure_Time;
-- Select all flights ordered by Arrival_Airport
SELECT * FROM Flights ORDER BY Arrival_Airport;
-- Select all flights ordered by Flight_Number in descending order
SELECT * FROM Flights ORDER BY Flight_Number DESC;
-- Select all flights ordered by Departure_Airport and then by Flight_Duration
SELECT * FROM Flights ORDER BY Departure_Airport, Flight_Duration;
-- Select all flights ordered by Arrival_Time in descending order
SELECT * FROM Flights ORDER BY Arrival_Time DESC;
-- Select all flights ordered by Flight_ID
SELECT * FROM Flights ORDER BY Flight_ID;
-- Select all flights ordered by Arrival_Time
SELECT * FROM Flights ORDER BY Arrival_Time;
-- 5. GROUP BY Clause Queries
-- Count flights grouped by status
SELECT Status, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Status;
-- Group flights by Departure_Airport and count them
SELECT Departure_Airport, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Departure_Airport;
-- Group flights by Arrival_Airport and count them
SELECT Arrival_Airport, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Arrival_Airport;
-- Group flights by Aircraft_Type and calculate average duration
SELECT Aircraft_Type, AVG(Flight_Duration) AS AverageDuration FROM Flights GROUP BY Aircraft_Type;
-- Group flights by Flight_Number and count them
SELECT Flight_Number, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Flight_Number;
-- Group flights by Departure_Airport and calculate total available seats
SELECT Departure_Airport, SUM(Seats_Available) AS TotalSeats FROM Flights GROUP BY Departure_Airport;
-- Group flights by Status and calculate maximum duration
SELECT Status, MAX(Flight_Duration) AS MaxDuration FROM Flights GROUP BY Status;
-- Group flights by Arrival_Airport and calculate minimum duration
SELECT Arrival_Airport, MIN(Flight_Duration) AS MinDuration FROM Flights GROUP BY Arrival_Airport;
-- Group flights by Departure_Airport and calculate average available seats
SELECT Departure_Airport, AVG(Seats_Available) AS AverageSeats FROM Flights GROUP BY Departure_Airport;
-- Group flights by Aircraft_Type and count distinct statuses
SELECT Aircraft_Type, COUNT(DISTINCT Status) AS DistinctStatusCount FROM Flights GROUP BY Aircraft_Type;
-- 6. HAVING Clause Queries
-- Select statuses with more than 5 flights
SELECT Status, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Status HAVING COUNT(*) > 5;
-- Select departure airports with more than 3 flights
SELECT Departure_Airport, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Departure_Airport HAVING COUNT(*) > 3;
-- Select aircraft types with an average flight duration greater than 120 minutes
SELECT Aircraft_Type, AVG(Flight_Duration) AS AverageDuration FROM Flights GROUP BY Aircraft_Type HAVING
AVG(Flight_Duration) > 120;
-- Select arrival airports with less than 2 flights
SELECT Arrival_Airport, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Arrival_Airport HAVING COUNT(*) < 2;
-- Select statuses with a total of available seats greater than 200
SELECT Status, SUM(Seats_Available) AS TotalSeats FROM Flights GROUP BY Status HAVING SUM(Seats_Available) > 200;
-- Select flight numbers with more than 1 occurrence
SELECT Flight_Number, COUNT(*) AS Occurrences FROM Flights GROUP BY Flight_Number HAVING COUNT(*) > 1;
-- Select departure airports with an average available seat count less than 50
SELECT Departure_Airport, AVG(Seats_Available) AS AverageSeats FROM Flights GROUP BY Departure_Airport
HAVING AVG(Seats_Available) < 50;
-- Select aircraft types with a maximum flight duration of less than 150 minutes
SELECT Aircraft_Type, MAX(Flight_Duration) AS MaxDuration FROM Flights GROUP BY Aircraft_Type HAVING
MAX(Flight_Duration) < 150;
-- Select statuses with a count of flights equal to 1
SELECT Status, COUNT(*) AS NumberOfFlights FROM Flights GROUP BY Status HAVING COUNT(*) = 1;
-- Select arrival airports with an average flight duration greater than 100 minutes
SELECT Arrival_Airport, AVG(Flight_Duration) AS AverageDuration FROM Flights GROUP BY Arrival_Airport
HAVING AVG(Flight_Duration) > 100;
-- 7. LIMIT (or FETCH or TOP) Clause
/*
In MySQL, the LIMIT clause is used to restrict the number of rows returned by a query.
Unlike some other SQL databases (e.g., SQL Server or PostgreSQL) that use TOP or FETCH,
MySQL exclusively supports LIMIT.
Syntax for LIMIT
SELECT column1, column2, ...
FROM table_name
LIMIT [offset,] row_count;
Key Components
1. row_count: Specifies the number of rows to return.
2. offset (optional): Specifies the starting point from which rows are returned. If omitted,
the default is 0 (start from the first row).
3. LIMIT: Used to specify the maximum number of records to return.
4. Using LIMIT with a comma: An alternative way to specify both the offset and the limit in a single clause.
5. ROW_COUNT(): While not directly applicable, you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS() to get the
total count of rows.
*/
-- Select the first 5 flights
SELECT * FROM Flights LIMIT 5;
SELECT * FROM Flights LIMIT 5 offset 2;
-- Select the first 10 flights ordered by Departure_Time
SELECT * FROM Flights ORDER BY Departure_Time LIMIT 10;
-- Select the last 3 flights based on Flight_ID
SELECT * FROM Flights ORDER BY Flight_ID DESC LIMIT 3;
-- Select the first 7 flights that are delayed
SELECT * FROM Flights WHERE Status = 'Delayed' LIMIT 7;
-- Select the first 5 flights departing from Delhi
SELECT * FROM Flights WHERE Departure_Airport = 'Delhi (DEL)' LIMIT 5;
-- Select the first 10 flights with available seats greater than 50
SELECT * FROM Flights WHERE Seats_Available > 50 LIMIT 10;
-- Select the first 5 flights arriving in Mumbai
SELECT * FROM Flights WHERE Arrival_Airport = 'Mumbai (BOM)' LIMIT 5;
-- Select the first 10 flights with a flight duration greater than 120 minutes
SELECT * FROM Flights WHERE Flight_Duration > 120 LIMIT 10;
-- Select the first 5 flights ordered by Flight_Number
SELECT * FROM Flights ORDER BY Flight_Number LIMIT 5;
-- Select the first 3 flights that departed after a specific date
SELECT * FROM Flights WHERE Departure_Time > '2023-10-01 00:00:00' LIMIT 3;
-- Select 5 flights starting from the 10th record (OFFSET)
SELECT * FROM Flights LIMIT 5 OFFSET 10;
-- Select 10 flights starting from the 20th record
SELECT * FROM Flights LIMIT 10 OFFSET 20;
-- Select 3 flights starting from the 5th record
SELECT * FROM Flights LIMIT 3 OFFSET 5;
-- Select 7 flights starting from the 15th record
SELECT * FROM Flights LIMIT 7 OFFSET 15;
-- Select 4 flights starting from the 0th record (first record)
SELECT * FROM Flights LIMIT 4 OFFSET 0;
-- Select 5 flights starting from the 10th record
SELECT * FROM Flights LIMIT 10, 5; -- This means skip 10 records and then return the next 5
-- Select 10 flights starting from the 20th record
SELECT * FROM Flights LIMIT 20, 10; -- Skip 20 records and return the next 10
-- Select 3 flights starting from the 5th record
SELECT * FROM Flights LIMIT 5, 3; -- Skip 5 records and return the next 3
-- Select 7 flights starting from the 15th record
SELECT * FROM Flights LIMIT 15, 7; -- Skip 15 records and return the next 7
-- Select 4 flights starting from the 0th record (first record)
SELECT * FROM Flights LIMIT 0, 4; -- Skip 0 records and return the first 4
-- Get the total number of flights and limit the results
SELECT SQL_CALC_FOUND_ROWS * FROM Flights LIMIT 5;
SELECT FOUND_ROWS(); -- This will return the total number of rows without the LIMIT
-- 8. JOIN Clause
/*
Note - to join 2 or more table their 1 attributes must be common.
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN: Returns all records from the left table (Flights) and the matched records from the right
table (Bookings or Airlines). If there is no match, NULL values are returned for columns from the right table.
RIGHT JOIN: Returns all records from the right table (Bookings) and the matched records from the left table
(Flights). If there is no match, NULL values are returned for columns from the left table.
*/
-- Join Flights with Bookings to get flight details along with booking information
SELECT f.Flight_ID, f.Flight_Number, b.Booking_ID, b.Booking_Date, b.Number_of_Seats
FROM Flights f
INNER JOIN Bookings b ON f.Flight_ID = b.Flight_ID;
-- Join Flights with Passengers to get flight details along with passenger information
SELECT f.Flight_ID, f.Flight_Number, p.Passenger_ID, p.First_Name, p.Last_Name
FROM Flights f
INNER JOIN Bookings b ON f.Flight_ID = b.Flight_ID
INNER JOIN Passengers p ON b.Passenger_ID = p.Passenger_ID;
-- Left join Flights with Bookings to get all flights and their booking status (if any)
SELECT f.Flight_ID, f.Flight_Number, b.Booking_ID, b.Booking_Status
FROM Flights f
LEFT JOIN Bookings b ON f.Flight_ID = b.Flight_ID;
-- Left join Flights with Airlines to get flight details along with airline information
SELECT f.Flight_ID, f.Flight_Number, a.Airline_Name, a.IATA_Code
FROM Flights f
LEFT JOIN Airlines a ON f.Airline_ID = a.Airline_ID; -- Assuming Airline_ID is added to Flights table
-- Right join Bookings with Flights to get all bookings and their corresponding flight details (if any)
SELECT b.Booking_ID, b.Booking_Date, f.Flight_Number, f.Departure_Airport
FROM Bookings b
RIGHT JOIN Flights f ON b.Flight_ID = f.Flight_ID;
-- 9. UNION Clause
/*
The UNION clause is used to combine the results of two or more SELECT statements. Duplicate rows are
removed by default.
*/
-- 1. Select Flights from Two Different Departure Airports
SELECT Flight_ID, Flight_Number, Departure_Airport, Arrival_Airport
FROM Flights
WHERE Departure_Airport = 'Delhi (DEL)'
UNION
SELECT Flight_ID, Flight_Number, Departure_Airport, Arrival_Airport
FROM Flights
WHERE Departure_Airport = 'Mumbai (BOM)';
-- 2. Select All Delayed and Cancelled Flights
SELECT Flight_ID, Flight_Number, Status
FROM Flights
WHERE Status = 'Delayed'
UNION
SELECT Flight_ID, Flight_Number, Status
FROM Flights
WHERE Status = 'Cancelled';
-- 3. Select Flights with More Than 50 Available Seats
SELECT Flight_ID, Flight_Number, Seats_Available
FROM Flights
WHERE Seats_Available > 50
UNION
SELECT Flight_ID, Flight_Number, Seats_Available
FROM Flights
WHERE Flight_Duration < 120; -- Assuming you want to compare with a different condition
-- 4. Select Flights to Chennai and Bangalore
SELECT Flight_ID, Flight_Number, Arrival_Airport
FROM Flights
WHERE Arrival_Airport = 'Chennai (MAA)'
UNION
SELECT Flight_ID, Flight_Number, Arrival_Airport
FROM Flights
WHERE Arrival_Airport = 'Bangalore (BLR)';
-- 5. Select Flights with Specific Flight Numbers
SELECT Flight_ID, Flight_Number, Departure_Airport
FROM Flights
WHERE Flight_Number = 'AI101'
UNION
SELECT Flight_ID, Flight_Number, Departure_Airport
FROM Flights
WHERE Flight_Number = 'AI102';
-- 6. Select Flights with a Duration Greater Than 150 Minutes
SELECT Flight_ID, Flight_Number, Flight_Duration
FROM Flights
WHERE Flight_Duration > 150
UNION
SELECT Flight_ID, Flight_Number, Flight_Duration
FROM Flights
WHERE Status = 'On Time';
-- 7. Select Flights with Arrival in Specific Cities
SELECT Flight_ID, Flight_Number, Arrival_Airport
FROM Flights
WHERE Arrival_Airport = 'Hyderabad (HYD)'
UNION
SELECT Flight_ID, Flight_Number, Arrival_Airport
FROM Flights
WHERE Arrival_Airport = 'Pune (PNQ)';
-- 8. Select Flights with Specific Statuses
SELECT Flight_ID, Flight_Number, Status
FROM Flights
WHERE Status = 'On Time'
UNION
SELECT Flight_ID, Flight_Number, Status
FROM Flights
WHERE Status = 'Delayed';
-- 9. Select Flights with Departure After a Specific Time
SELECT Flight_ID, Flight_Number, Departure_Time
FROM Flights
WHERE Departure_Time > '2023-10-01 12:00:00'
UNION
SELECT Flight_ID, Flight_Number, Departure_Time
FROM Flights
WHERE Departure_Time > '2023-10-01 14:00:00';
-- 10. Select Flights with Different Aircraft Types
SELECT Flight_ID, Flight_Number, Aircraft_Type
FROM Flights
WHERE Aircraft_Type = 'Boeing 737'
UNION
SELECT Flight_ID, Flight_Number, Aircraft_Type
FROM Flights
WHERE Aircraft_Type = 'Airbus A320';
-- 10. INTO Clause (Mysql does not support into clause directly in this way)
-- Create a new table to store flights with less than 50 available seats
SELECT Flight_Number, Departure_Airport
INTO New_Flights_Table
FROM Flights
WHERE Seats_Available < 50;