Repository navigation
Expand file tree
/
Copy pathModule_1.Rmd
More file actions
1591 lines (907 loc) · 51 KB
/
Copy pathModule_1.Rmd
File metadata and controls
1591 lines (907 loc) · 51 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
---
title: "Module 1"
description: |
Jump into Relational databases. A quick re-introduction to db browser and relational databases
output:
distill::distill_article:
toc: true
toc_depth: 2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
# Game Plan
At this point everyone should have the class technology up and running on their machines. We are going to learn the basics ETL using mostly RStudio, but we will start off with concepts learned in ACC3003, relational databases and excel. You should have experience with relational databases and excel, but if you have forgotten do not worry. We will pick up here and discover how R can push these technologies further. Lets get started with Relational databases.
This case study is provided by [PWC](https://www.pwc.com/us/en/careers/university-relations/data-and-analytics-case-studies.html). It was developed for a [masters level course](https://www.pwc.com/us/en/careers/university-relations/data-and-analytics-case-studies.html), but I am adapting it for our class. I will provide all of the knowledge based content because it is important to get an understanding of what accounting firms are looking for, but we may only discuss portions in class.
# Lets Get Started
#### Module 1 Objectives
- Demonstrate knowledge of relational databases, [data lineage, and ERP systems](Module_1_A.html)
- Demonstrate how to interpret an entity relationship diagram
- Demonstrate how to use SQL to transform and analyze data
## Review
#### Data Analytics Process

## What is a Relational Database
A **relational database** is a collection of data that organizes data in tables and maintains relationships between the tables for information retrieval
A **relational database management system** (RDBMS) is computer software that enables users to create, modify, and analyze data in a relational database
#### Enterprise RDBMS include:
- Microsoft SQL Server
- Oracle Database
- Oracle MySQL
- IBM DB2
- SAP Sybase
- Teradata
- PostgreSQL
#### Lightweight RDBMS include:
- Microsoft Access
- SQLite (what we are using 😏)
## Key Terms
- A [**table**](#tables) is the basic unit of data storage in a database. Data is stored in rows and columns. You can specify rules for each column of a table like establishing its data type, forcing a column to contain a value in every row, or ensuring unique records
- A **view** is a tailored presentation of data selected from one or more tables, possibly including other views. A view contains no actual data but rather derives what it shows from the tables and views on which it is based. Therefore, a view can be thought of as a virtual table
- A **schema** is a "container" within a database similar to a directory on a file system that groups tables together
- The connection between tables is made by a **Primary Key -- Foreign Key** pair, where the Foreign Key in a table is the Primary Key of another table
- A **query** is used to create, manipulate, or view database objects
- A **report** is formatted view of data from the database within user-defined parameters, often generated in an external file format such as.txt
## Tables {#tables}
- Tables consist of one or more records or rows of data
- The data for each row is organized into a defined set of attributes, organized into columns
::: {.floatting}
```{r out.width='40%', out.extra='style="float:right; padding:10px"'}
knitr::include_graphics("images/Simple_table.png")
```
- Data types include:
- String/Text/Character
- Numeric (Integer, Float)
- Date/Time
- Boolean (Yes/No, True/False)
:::
#### Relational Tables

#### Primary Key
- Primary key is a unique identifier of records in a table
- Primary key values may be generated manually or automatically
- A primary key can consist of more than one field
## Relationship Types
#### **One-to-One**
- Each instance of one entity relates to only one instance of the second
- Not frequently used in database systems
- Might use to divide a table with many fields in order to isolate part of a table
#### **One-to-Many**
- Each instance of one entity relates to one or more instances of the second entity
- Most common type of relationship and it is used to relate one record from the 'primary' table with many records in the 'related' table.
- In a one-to-many relationship, a record ('parent') in Table A can have many matching records ('children') in Table B, but a record ('child') in Table B has only one matching record ('parent') in Table A.
#### **Many-to-Many**
- Multiple instances of one entity relate to multiple instances of the second entity
#### Entity Relationship Diagram

# [Other Information in PWC Case Study](Module_1_A.html)
# Structured Query Language
## What is SQL
- Structured Query Language (SQL) is the programming language used when interacting with data in a relational database
- SQL implementations for different databases may have minor differences in functions and syntax
- SQL statements can be categorized into two groups: Data Definition Language (DDL) and Data Manipulation Language (DML)
- DDL statements are used to create and/or alter table structures in a SQL Server database
- DML statements are used to add, modify, query, or remove data from a SQL Server database
## SQL Basics
- A statement is a complete sequence of functions, keywords, operators, and values that can be evaluated by the database engine
- A query returns records from one or more tables in the database
- A clause is a component of a statement or query
- An expression is a combination of one or more values, operators, and functions that evaluates to a value
- Extra white space (spaces, new lines, etc.) is not evaluated
- SQL is typically case-insensitive, but functions are capitalized by convention
- SQL statements are often required to end with a semi-colon (;)
## SQLite and DB Browser for SQLite
www.sqlite.org:
- "SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine"
- "SQLite is the most used database engine in the world"
sqlitebrowser.org:
- "DB Browser for SQLite [DB4S] is a high quality, visual, open source tool to create, design, and edit database files compatible with SQLite"
- Create, define, modify and delete tables
- Browse, edit, add and delete records
- Search records
- Import and export tables from/to CSV files
- Issue SQL queries and inspect the results
## SQLite/DB4S Basics
{width="100%"}
## Comments
- Adding comments is a best practice when writing code, in any programming language
- These statements are not evaluated by the SQL engine but help the reader understand the intent and the approach behind an individual line of code or the script as a whole
- In SQL, single-line comments are generally preceded by a double dash ("--"), while block comments across multiple lines are marked by "/\* ... \*/"
{width="100%"}
## Chinook Sample Database
::: {.floatting}
```{r out.width='60%', out.extra='style="float:right; padding:10px"'}
knitr::include_graphics("images/Chinook_Database.png")
```
- Chinook is a digital media store with several employees
- Customers can buy individual tracks from a variety of musical artists
- The database contains master and transactional data for the business
- Download the database and open the Chinook_Sqlite.sqlite file in DB4S
:::
## SYNTAX
### SELECT statement
- A SELECT statement is used to fetch records from a database table in the form of a table called a result set
- One or more columns may be specified, or the asterisk (\*) can be used to return all records from the table
- Use the LIMIT keyword to return only the first n rows from the result set
- The result set is not stored in the database without the use of additional functions
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{SELECT * FROM}}$ table_name
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name $\color{red}{\text{LIMIT}}$ 5
### CREATE TABLE statement
- A **CREATE TABLE** statement is used to add the result set from a query to the database as a new table
- Complicated queries can be broken down by creating intermediate tables
- The ability to create a table depends on the level of access granted to a user, so it may not be possible in some situations
$\color{red}{\text{CREATE TABLE}}$ new_table $\color{red}{\text{AS}}$
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
### ORDER BY
The $\color{red}{\text{ORDER BY}}$ keyword can be added to a **SELECT** statement to sort the records
The typical default order is ascending **(ASC)**, but you can also specify descending **(DESC)**
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{ORDER BY}}$ column2, column1, column3 $\color{red}{\text{DESC}}$
### COUNT
- The COUNT function returns the number of records in the result set
- The input parameter can be \* or 1
$\color{red}{\text{SELECT}}$ COUNT(\*) $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{SELECT}}$ COUNT(1) $\color{red}{\text{FROM}}$ table_name
## Exercise \#1
Answer the following questions using the Chinook Database in DB Browser $\color{red}{\text{(Do not peek at the answers 👿 )}}$:
1. How many columns does the customer table have?[^1]
[^1]: I did not find a great SQL solution. If you find a better one please let me know.
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_1_1_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_1_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_1_1_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_1_B.png")
```
</p>
</details>
2. If you select only the first 5 rows, what is the country in the last row?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_1_2_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_2_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_1_2_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_2_B.png")
```
</p>
</details>
3. If you sort the table on last name, what is the last name in the third row?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_1_3_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_3_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_1_3_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_3_B.png")
```
</p>
</details>
4. How many rows are in the invoice table?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_1_4_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_4_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_1_4_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_1_4_B.png")
```
</p>
</details>
### WHERE clause
- The **WHERE** clause can be added to a **SELECT** statement to filter records that meet certain conditions, i.e. return a subset of the table
- We use expressions to define these conditions
- Most conditional operators are self-explanatory (=, \<, \>, etc.)
- A common operator for "not equals" is \<\> or !=
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name $\color{red}{\text{WHERE}}$ column1 = 'ABC'
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name $\color{red}{\text{WHERE}}$ column2 \> 100
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name $\color{red}{\text{WHERE}}$ column3 != 0
### Comparative Operators
| $\color{red}{\text{Operator}}$ | $\color{red}{\text{Operator Description}}$ | $\color{red}{\text{Example (a=10, b=20)}}$ |
|--------------------------------|--------------------------------------------------------------------------------------------------------------------|--------------------------------------------|
| = | Checks if the values of two operands are equal or not, if yes then condition becomes true | (a= b) is not true |
| != | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true | (a != b) is true |
| \<\> | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true | (a \<\> b) is true |
| \> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true | (a \> b) is not true |
| \< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true | (a \< b) is true |
: Comparative Operators
### AND/OR
- An AND/OR operator can be added to a WHERE clause to filter records on based on multiple conditions
- The AND operator returns all records where both conditions are true
- The OR operator returns all records if either the first condition or the second condition are true
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ a_condition $\color{red}{\text{AND}}$ another_condition
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ a_condition $\color{red}{\text{OR}}$ another_condition
### IN
- The **IN** operator can be used to specify multiple values in a **WHERE** clause
- This is equivalent to a series of **OR** clauses
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ column1 $\color{red}{\text{IN}}$ (value1, value2, ..., valueN)
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ column1 = value1 $\color{red}{\text{OR}}$ column1 = value $\color{red}{\text{OR}}$ ... $\color{red}{\text{OR}}$ column1 = valueN
### BETWEEN
- The **BETWEEN** operator can be used in a **WHERE** clause to select values within a range
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ column2 $\color{red}{\text{BETWEEN}}$ value1 $\color{red}{\text{AND}}$ value2
### LIKE
- The **LIKE** operator can be used in a **WHERE** clause to search for a specified pattern in a column
- **LIKE** supports the several wildcards
$\color{red}{\text{SELECT}}$ column1, column2, column3 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ column2 $\color{red}{\text{LIKE}}$ '$\color{red}{\text{%}}$value1$\color{red}{\text{%}}$'
| $\color{red}{\text{Wildcard}}$ | $\color{red}{\text{Description}}$ |
|--------------------------------|------------------------------------------------------------|
| \% | A substitute for zero or more characters |
| \_ (underscore) | A substitute for a single character |
| [charlist] | Sets and ranges of characters to match |
| [\^charlist] | Matches only a character NOT specified within the brackets |
### NULL and NOT
- **NULL** means that a value has not been entered for a particular column in a row, i.e. the value is missing
- **NULL** is not numeric or any other value so it can't equal itself or anything else
- **NOT** creates the negation of an expression
- To test for a **NULL** value you will want to use the expressions **IS** **NULL** or **IS NOT NULL**
$\color{red}{\text{SELECT}}$ column1, column2 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ column2 $\color{red}{\text{IS NULL}}$
$\color{red}{\text{SELECT}}$ column1, column2 $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{WHERE}}$ column2 $\color{red}{\text{IS NOT NULL}}$
## Exercise \#2
Answer the following questions using the Chinook Database in DB Browser $\color{red}{\text{(Do not peek at the answers 👿 )}}$: [^2]
[^2]: These are not the only answers
1. How many invoices have totals greater than \$20?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_2_1_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_1_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_2_1_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_1_B.png")
```
</p>
</details>
2. How many invoices have totals greater than \$10 and less than \$20?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_2_2_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_2_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_2_2_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_2_B.png")
```
</p>
</details>
3. How many invoices are from customers in Brazil, Argentina, or Chile?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_2_3_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_3_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_2_3_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_3_B.png")
```
</p>
</details>
4. How many invoices have a billing country that starts with "C"?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_2_4_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_4_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_2_4_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_4_B.png")
```
</p>
</details>
5. How many customers list their company?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_2_5_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_5_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_2_5_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_2_5_B.png")
```
</p>
</details>
### Expressions
- An expression is a combination of one or more values, operators, and SQL functions that evaluates to a value
- Any time the data must be displayed, filtered, or ordered in a way that is different from how it is stored, you can use expressions and functions to manipulate it
- We can use expressions to create calculated or derived fields, as in the example below:
- $\color{red}{\text{end_bal}}$ -- $\color{red}{\text{beg_bal}}$ is the expression
- Minus ($\color{red}{\text{-}}$) is an operator
- $\color{red}{\text{end_bal}}$ and $\color{red}{\text{beg_bal}}$ are columns in the existing table
- $\color{red}{\text{AS "difference"}}$ provides a name for a new column in the result set
SELECT column1, end_bal, end_bal -- beg_bal $\color{red}{\text{AS}}$ "difference"
FROM table_name
### Arithmetic operators
| $\color{red}{\text{Operator}}$ | $\color{red}{\text{Description}}$ |
|--------------------------------|-----------------------------------------------------------------------------------|
| \+ | Adds values on either side of the operator |
| \- | Subtracts right hand operand from left hand operand |
| \* | Multiplies values on either side of the operator |
| / | Divides left hand operand by right hand operand |
| \% | Divides left hand operand by right hand operand and returns remainder ("modulus") |
## String functions
- The **RTRIM** and **LTRIM** functions remove spaces from the right side or left side of a string
$\color{red}{\text{RTRIM(<string>)}}$
$\color{red}{\text{LTRIM(<string>)}}$
- Use **SUBSTR** to return a portion of a string starting at a given position and for a specified number of characters
$\color{red}{\text{SUBSTR(<string>,<start location>,<length>)}}$
- Use **LENGTH** to return the number of characters in a string (other SQL implementations may use **LEN**)
$\color{red}{\text{LENGTH(<string>)}}$
### String functions (continued)
- Use **UPPER** and **LOWER** to change a string to either uppercase or lowercase
- You may need to display all uppercase data in a report, for example
$\color{red}{\text{UPPER(<string>)}}$
$\color{red}{\text{LOWER(<string>)}}$
- Use **REPLACE** to substitute one string value for another
- Use **REPLACE** to clean up data; for example, you may need to replace slashes (/) in a phone number column with hyphens (-) for a report
$\color{red}{\text{REPLACE(<string value>,<string to replace>,<replacement>) }}$
$\color{red}{\text{SELECT}}$ column1, $\color{red}{\text{REPLACE}}$ (column1, '/', '-') $\color{red}{\text{AS}}$ new_col
$\color{red}{\text{FROM}}$ table_name
### Numeric functions
- Use **ROUND** to specify a number of significant digits:
$\color{red}{\text{SELECT}}$ column1, $\color{red}{\text{ROUND}}$ (column1, 2) $\color{red}{\text{AS}}$ new_col
$\color{red}{\text{FROM}}$ table_name
- Use **RANDOM** in combination with the absolute value function **ABS** and modulus operator % to generate a random number on a specific range:
$\color{red}{\text{SELECT}}$ \*, $\color{red}{\text{ABS}}$($\color{red}{\text{RANDOM}}$() % 100) $\color{red}{\text{AS}}$ new_col
$\color{red}{\text{FROM}}$ table_name
### Data functions
::: {style="display: flex;"}
::: {.column width="50%"}
- Different SQL implementations have varying functions and operators for dates and times
- In SQLite, date objects are created by DATE and related functions, and arithmetic operators are used to do calculations involving dates
- **DATE('now')** returns the current date and time of the server
- **JULIANDAY** interprets dates in the standard YYYY-MM-DD format
- **STRFTIME** provides flexible options for managing dates and times using substitutions shown at right
:::
<div>
| $\color{red}{\text{Sub}}$ | $\color{red}{\text{Description}}$ |
|---------------------------|-----------------------------------|
| %d | day of month: 00 |
| %f | fractional seconds: SS.SSS |
| %H | hour: 00-24 |
| %j | day of year: 001-366 |
| %J | Julian day number |
| %m | month: 01-12 |
| %M | minute: 00-59 |
| %s | seconds since 1970-01-01 |
| %S | seconds: 00-59 |
| %w | day of week 0-6 with Sunday = 0 |
| %W | week of year: 00-53 |
| %Y | year: 0000-9999 |
</div>
:::
### Example - Date functions
$\color{red}{\text{SELECT JULIANDAY}}$('now') - $\color{red}{\text{JULIANDAY}}$('1776-07-04');
$\color{red}{\text{SELECT}}$ column1, $\color{red}{\text{STRFTIME}}$('%Y-%m-%d', column1) $\color{red}{\text{AS}}$ new_col
$\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{SELECT}}$ column1, $\color{red}{\text{STRFTIME}}$('%w', column1) $\color{red}{\text{AS}}$ new_col
$\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{SELECT}}$ column1, $\color{red}{\text{STRFTIME}}$('%W', column1) $\color{red}{\text{AS}}$ new_col
$\color{red}{\text{FROM}}$ table_name
### CAST
- The **CAST** function is used for explicitly changing the data type of a column, often from text to numeric and vice versa
- Available data types include:
- **INT** - Integer
- **CHAR** - Text
- **TEXT** - Text
- **REAL** - Numeric
- **FLOAT** - Numeric
$\color{red}{\text{SELECT}}$ column1, $\color{red}{\text{CAST}}$(column1 $\color{red}{\text{AS INT}}$) $\color{red}{\text{AS}}$ int_col $\color{red}{\text{FROM}}$ table_name
$\color{red}{\text{SELECT}}$ column2, $\color{red}{\text{CAST}}$(column2 $\color{red}{\text{AS CHAR}}$) $\color{red}{\text{AS}}$ char_col $\color{red}{\text{FROM}}$ table_name
## Exercise \#3
Answer the following questions using the Chinook Database in DB Browser $\color{red}{\text{(Do not peek at the answers 👿 )}}$:
1. How many employees does Chinook have?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_3_1_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_3_1_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_3_1_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_3_1_B.png")
```
</p>
</details>
2. Create a new column that shows their phone numbers without the area code.
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_3_2_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_3_2_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_3_2_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_3_2_B.png")
```
</p>
</details>
3. How long is the longest last name?
<details>
<summary>
Answer 1
</summary>
<p>
```{r SQL_Exercise_3_3_A, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_3_3_A.png")
```
</p>
</details>
<details>
<summary>
Answer 2
</summary>
<p>
```{r SQL_Exercise_3_3_B, echo=FALSE, out.width = '80%'}
knitr::include_graphics("images/SQL_Exercise_3_3_B.png")
```
</p>
</details>
4. How many employees were born on a Sunday?
<details>