forked from brianchiang-tw/SQL_for_DataScience
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQL Note.txt
2382 lines (1232 loc) · 48.9 KB
/
SQL Note.txt
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
### SQL for data science
# Learning objectives
# Define SQL
# Discuss how SQL differs from other computer language
# Explain how SQL is used in a database
### What is SQL ?
# Structured Query Language is a standard computer language for
# relational database management and data manipulation
# Used to query, insert, update and modif data
## Recall: CURD
#
# C: Create
# U: Update
# R: Read
# D: Delete
# Used to communicate with databases
# Statements are made up of descriptive words and are easy to learn
# SQL is a non-procedural language:
#
# Cannot write complete appliations
#
# Simple, but powerful
### How is SQL used?
## SQL is all about data
# Read/retrieve data
# Write data: add data to a table
# Update data: insrty new data
### Database adminstrator or Data Scientist
## Data administrator
# Manages/govenrs entire database
# Gives permissions to users
# Determines access to data
# Manages and create tables
# Uses SQL to query and retrieve data
## Data Scientist
# End user of a database
# Uses SQL to query and retrieve data
### How do data scientist use SQL?
# Retrieve data
# May create their own table or test environent
# Combine multiple sources together
# Write complex queries for analysis
### SQL and database management systems
# How you write syntax will depend on what DBMS you are using
# Each DBMS has its own "dialect"
# SQL can translate
# You will tweak based on the "dialect" you DBS speaks
### Relational Database Management Systems
# Microsoft SQL Server
# IBM DB2 Oracle
# Sybase ASE
# PostgreSQL
# MySQL
# Apache Open Office Base
# SQLite
### Learning objectives
# Thinking before codeing is importnat
#
# Before we start to write code or write our query,
# think about what the problem is we're trying to solve.
# Crucial to understand how the database relates to one another
# Describe what a database is
### Understand your data
# Understand the business process or subject matter the data is modeled after
# Know the business rules
# Understand how you data is organized and structured in the table (modeled)
### Why this is worthwhile
# Get more accurate results
# Speed up you work
# Have less rework
### Comparison betweeen database and table
## Database:
# a container (usually a file or set of files) to store organized data
# a set of related information
## Tables:
# a structured list of data or a specific type
### Columns and Rows
# Column: a single field in a table - all tables are made up of one or more columns
# Row: a record in a table
### The evolution fo data models
# Data modeling
# Relational database system
# Discuss advent of relational databses in SQL
### What is data modeling?
# Organizes and structures information into multiple, related tables
# Can represent a business process or show relationship between usiness processes
# Should represent real world as closely as possible
### Types of Data Models
# Models for prediction built by data scientists.
# Data model as data tables represented and organized in a database
### SQL in a big data world
# NoSQL - not only SQL
# A mechanism for storage and retrieval of unstructured data modeled by means
# other than tabular relations in relational databases
### Learning objectives
# Define and describe both relational and transactional database models
# Define entities, attributes, and relationships
# Describe and explain the differences between a one-one, one-many, and
# many-many relationships
# Primary keys in a database
# How ER diagrams are used to document and illustrate relationships.
### Relational v.s. Transactional Model
## Relational Model
# Allows for easy querying and data manipulation in an easy, logical
# and intuitive way
## Transactional Model
# Operational databse
# insurance claims within a healthcare database
### Data model building blocks
## Entity:
#
# Person, place thing or event distinguishable, unique, and distinct
## Attribute:
#
# A characteristic of an entity
## Relationship:
#
# Describes association among entities
#
# One-to-many
# Many-to-many
# one-to-one
### Data model building blocks
# One-to-many: customer to invoices
# Many-to-many: student to classes
# One-to-one: manager to store
### ER Diagrams
## ER(i.e., Entity-Relationship) model
# It is composed of entity types and specifies relationships that can
# exist between instances of those entity types
### ER Diagrans
# Show relationship
# Business process
# Represened visually
# Show links (primary keys)
### Primary keys and Foreign keys
## Primary key
# A column (or set of columns) whose values uniquely identify every row in a table.
## Foreign key
# One or more columns that can be used together to identify a single row in another table.
### ER diagram Notation
# Chen Notation
# Crow's Foot Notation
# UML Class Diagram Notation
### Learning objective
# Write a basic "SELECT" statement
# Tell a database which table your data will com "FROM"
# "SELECT" either all or particular columns from a table in a query
# Limit the amount of data which is reurned in a query
### The SELECt Statement
# Need to specify two pieces of information to use a SELECT statement:
# what you want and where you want to select it from.
# Example:
# SELEC prod_name FROM Products;
# Output:
# prod_name
# ----------
# Shampoo
# Toothpaste
# Deodorant
# Toothbrush
### Retrieving Multiple Columns
# Add multiple column names, be sure to use a comma
# Example:
# SELECT prod_name, prod_id, prod_price FROM Products;
# Example:
# SELECT prod_name
# ,prod_id
# ,prod_price
# FROM Products
### Retrieving Multi Columns using a wildcard
# Request all columns by using the asterisk (*) wildcard character
# instead of column names
# Example:
# SELECT * FROM Products
## Recall
## FROM where:
# A "SELECT" statement must always say where you wnat data selected from
# SELECT what
# A "SELECT" sttement must always say what you want selected
### Limit results
# If your database is large
# You might only want to see a sample of the data
# Example:
# "SELECT" columns you wish to see
# "FROM" specific table
# "LIMIT" number of records
### Limiting results using different syntaxes
## SQLite:
# Example:
#
# SELECT prod_name
# FROM Products
# LIMIT 5;
## Oracle:
# Examples:
#
# SELECT prod_name
# FROM Products
# WHERE ROWNUM <= 5;
## DB2
# Examples:
#
# SELECT prod_name
# FROM Products
# FETCH FIRST 5 ROWS ONLY;
### Learning objectives
# Discuss situations where it's beneficial to create new tables
# Create new tables within an existing database
# Write data to a new table
# Defining whether columns can accept NULL values or not
### Why tables are useful
# Use tables to make models and predictiosn
# Create dashboards
# Visualize data with other tools
# Extract data from other sources
### Creating your own table
#
# CREATE TABLE Shoes
# (
# Id char(10) PRIMARY KEY,
# Brand char(10) NOT NULL,
# Type char(250) NOT NULL,
# Color char(250) NOT NULL,
# Price decimal(8,2) NOT NULL,
# Desc Varchar(750) NULL
# );
### Adding data to the table
# INSERT INTO Shoes
# VALUES ('14535974'
# ,'Gucci'
# ,'Slippers'
# ,'Pink'
# ,'695.00'
# ,NULL
# );
# INSERT INTO Shoes
# (Id
# ,Brand
# ,Type
# ,Color
# ,Price
# ,Desc
# )
# VALUES ('14535974'
# ,'Gucci'
# ,'Slippers'
# ,'Pink'
# ,'695.00'
# ,NULL
# );
### Create temporary tables
### Learning objectives
# Create temporary tables
# Describe limitations of temporary tables
# Discuss stategies for researching syntax for particular database management systems
### Why create temporary tables
# temporary tables will be deleted when current session is terminated
# Faster than creating a real table
# Useful for compex queries using subsets and joins
### How to create a temporary table
CREATE TEMPORARY TABLE Sandals as
(
SELECT *
FROM Shoes
WHERE shoe_type='sandals'
)
### Never stop Learning
#
# Key words: statements, RDBMS
#
# Research how to:
# Update Tables
# Delete tables
### Adding Comments to SQL
### Learning objectives
# Discuss importance of writing comments as a part of your code
# Describe several comment syntaxes used in SQL
# Write comments in your code
### Adding comments
## Single line, by adding "--"
SELECT shoe id
--, brand_id
,shoe_name
from shoes
## Section, by adding /* ... */
SELECT shoe_id
/*,braind_id
,shoe_name
*/
from shoes
### Source Code Editors
# Environment separate from the database where you can write and edit code
# e.g.: Notepad++
# Automatically highlights and indents statements
# Helps you write clean code
### Quiz
SELECT
albums.title as album_title,
tracks.name as track_name
FROM tracks
JOIN albums ON tracks.albumid = albums.albumid
output:
+---------------------------------------+-----------------------------------------+
| album_title | track_name |
+---------------------------------------+-----------------------------------------+
| For Those About To Rock We Salute You | For Those About To Rock (We Salute You) |
| For Those About To Rock We Salute You | Put The Finger On You |
| For Those About To Rock We Salute You | Let's Get It Up |
| For Those About To Rock We Salute You | Inject The Venom |
| For Those About To Rock We Salute You | Snowballed |
| For Those About To Rock We Salute You | Evil Walks |
| For Those About To Rock We Salute You | C.O.D. |
| For Those About To Rock We Salute You | Breaking The Rules |
| For Those About To Rock We Salute You | Night Of The Long Knives |
| For Those About To Rock We Salute You | Spellbound |
| Balls to the Wall | Balls to the Wall |
| Restless and Wild | Fast As a Shark |
| Restless and Wild | Restless and Wild |
| Restless and Wild | Princess of the Dawn |
| Let There Be Rock | Go Down |
| Let There Be Rock | Dog Eat Dog |
| Let There Be Rock | Let There Be Rock |
| Let There Be Rock | Bad Boy Boogie |
| Let There Be Rock | Problem Child |
| Let There Be Rock | Overdose |
| Let There Be Rock | Hell Ain't A Bad Place To Be |
| Let There Be Rock | Whole Lotta Rosie |
| Big Ones | Walk On Water |
| Big Ones | Love In An Elevator |
| Big Ones | Rag Doll |
+---------------------------------------+-----------------------------------------+
(Output limit exceeded, 25 of 3503 total rows shown)
### Learning objectives
# Describe the basics of filtering your data
# Use the "WHERE" clause with common operators
# Use the "BETWEEN" clause
# Explain the concept of a "NULL" values
### Why filtering
# Be specific about the data you want to retrieve
# Reduce the number of records you retrieve
# Increase query performance
# Reduce the strain on the client application
# Governance limitations
### WHERE Clause operators
SELECT column_name, column_name
FROM table_name
WHERE column_name operator value;
### WHERE Clause operators
#------------------------------------------------------------------------------------------------
# operator | Description
#------------------------------------------------------------------------------------------------
# = | Equal
#------------------------------------------------------------------------------------------------
# <> | Not equal. Note: In some version of SQL this operator may be written as !=
#------------------------------------------------------------------------------------------------
# > | Greater than
#------------------------------------------------------------------------------------------------
# < | Less than
#------------------------------------------------------------------------------------------------
# >= | Greater than or equal
#------------------------------------------------------------------------------------------------
# <= | Less than or equal
#------------------------------------------------------------------------------------------------
# BETWEEN | Between an inclusive range
#------------------------------------------------------------------------------------------------
# IS NULL | Is a null value
#------------------------------------------------------------------------------------------------
# Example:
SELECT ProductName, UnitPrice, SupplierID FROM Products WHERE UnitPrice >= 75;
SELECT ProductName, UnitPrice, SupplierID FROM Products WHERE ProductName <>'Alice';
SELECT ProductName, UnitPrice, SupplierID, UnitsInStock FROM Products WHERE UnitsInStock BETWEEN 15 and 80;
SELECT ProductName, UnitPrice, SupplierID, UnitsInStock FROM Products WHERE ProductName IS NULL;
### Learning objective
# Use the IN and OR operators to filter your data and get results you want
# Differentiate between use of the IN and BETWEEN operators
# Discuss importance of order of operations
# Explain how and when to use the NOT operator
### IN operator
# Specifies a range of conditions
# Comma delimited list of values
# Enclosed in ()
### IN Operator Example
SELECT ProductID, UnitPrice, SupplierID FROM Products WHERE SupplierID IN (9, 10, 11);
### OR Operator
# DBMS will not evaluate the second conditions in a WHERE clause if the first condition is matter
# Use for any rows matching the specific conditions
### OR Operator Example
SELECT ProductName, ProductID, UnitPrice, SupplierID, ProductName FROM Products WHERE ProductName = 'Tofu' OR 'Konbu'
### IN vs. OR
## In works the same as OR
## Benefits of IN
# Long list of options
# IN executes faster than OR
# Don't have to think about the order with IN
# Can contain another SELECT
### OR with and
SELECT ProductID, UnitPrice, SuppleirID FROM Products
WHERE ( SupplierID = 9 OR SupplierID = 11 )
AND UnitPrice > 15;
### Order of operations
# Can contain AND and OR operators
# SQL processes AND before OR
# Use ()
### Note:
#
# Don't rely on the default order of operations.
# You are better being specific and getting in the habit of using the ()
### NOT Operator
SELECT * FROM Employees
WHERE NOT City='London' AND NOT City='Seattle';
### Learning objectives
# Explain the concept of wildcards advantages and disadvantages usefulness
# Describe how to use the LIKE operator with wildcard
# Write appropriate syntax when using wildcards
### What are wildcards?
# Can only be used with strings
# Cannot be used for non-text datatypes
# Helpful for data scientist as they explore string variable
### Using % wildcards
Wildcard Action
---------------------------------------------------------------
'%Pizza' Grab anything ending with the word pizza
---------------------------------------------------------------
'Pizza%' Grab anything after the word pizza
---------------------------------------------------------------
'%Pizza%' Grab anything before and after the word pizza
---------------------------------------------------------------
### Using % wildcards
Wildcard Action
-----------------------------------------------------------------------------------
'S%E' Grab anything that starts with "S" and ends with "E" (Like Sadie)
-----------------------------------------------------------------------------------
't%@gmail.com' Grab gmail addresses that start with 't'
-----------------------------------------------------------------------------------
### Using % wildcards
% wildcard will not match NULLs
NULL represents no value in a column
### Underscore _ Wildcard
# Matches a single character
# Is not supported by DB2
WHERE size like '_pizza'
Output:
spizza
mpizza
lpizza
### Bracket [] Wildcard
# Used to specify a set of characters in a specific location
# Does not work with all DBMS
# Does not work with SQLite
### Downsides of wildcards
# Take longer to run
# Better to use another operator (if possible):
=, <, =>, and etc.
# Statements with wildcards will take longer to run if used at the end of search patterns
# Placement of wildcards is important
### Learning objectives of Sorting with ORDER by
# Discuss the importance of sorting data for analysis purposes
# Explain some of the rules related to using the ORDER BY clause
# Use the ORDER BY clause to sort data either in ascending or descending order
### Why sort data?
# Data displayed appears in the order of the underlying tables.
# Updated and deleted data can change this order.
# Sequence of retrieved data cannot be assumed if order was not specified.
# Sorting data logically helps keep information you want on Toothpaste
# ORDER BY clause allows user to sort data by particular columns
# Example
SELECT column
FROM database
ORDER BY characteristic
### Rules for ORDER BY
# Takes the name of one or more columns
# Add a commna "," after each additional column name
# Can sort by a column not retrieved
# Must always be the last clause in a select statement
### Sorting by column position
ORDER BY 2, 3
2 means 2nd column
3 means 3rd column, etc.
# Sort direction
# DESC for descending order
# ASC for ascending order
# Only applies to the column names it directly precedes
### Math operations
# Perform basic math calculations using our data
# Discuss the order of operations
# Describe analysis possibilities of using math operators and SQL together
### Math operators
Operator Description
---------------------------------------
+ Addition
---------------------------------------
- Subtraction
---------------------------------------
* Multiplication
---------------------------------------
/ Division
---------------------------------------
### Multiplication Example
# Total units on order multipplied by the unit price to calculate the total order comments
SELECT
ProductID
, UnitsOnOrder
, UnitPrice
, UnitsOnOrder * UnitPrice AS Total_Order_Cost
FROM Products
### Order of operations
# Parentheses
# Exponents
# Multiplication
# Division
# Addition
# Substraction
# A pithy formula for order of operations
"Please excuse my dear Aunt Sally"
### Combining Math operations
SELECT
ProductID
,Quantity
,UnitPrice
,Discount
,(UnitPrice-Discount)/Quantity AS Total_Order_Cost
FROM OrderDetails
### Learning object of Aggregate Functions
# Describe various aggregate Functions
# Explain how each of the aggregate functions can help you to analyze data
# Use various aggregate functions: Average, Count, Min, Max, and SUM to summarize and analyze data and
# Describe the DISTINCT function
### What are aggregate functions
# Used to summarize data
# Finding the highest and lowest values
# Finding the total number of rows
# Finding the average value
### Aggregate Functions
Functions Description
AVG Averages a column of values