2
2
3
3
This repository is a quick personal reference to using Postgres and elaborating SQL queries.
4
4
5
- [ TOC]
5
+ - [ SQL and Postgres Quick Reference] ( #sql-and-postgres-quick-reference )
6
+ - [ Installing Postgres with Docker] ( #installing-postgres-with-docker )
7
+ - [ Pull image] ( #pull-image )
8
+ - [ Start Postgres instance] ( #start-postgres-instance )
9
+ - [ Bash into instance] ( #bash-into-instance )
10
+ - [ Login with root superuser access] ( #login-with-root-superuser-access )
11
+ - [ Crate a new database] ( #crate-a-new-database )
12
+ - [ Alternative: Connect <em >psql</em > to docker container (needs <em >pqsl/postgres</em > installed locally)] ( #alternative-connect-psql-to-docker-container-needs-pqslpostgres-installed-locally )
13
+ - [ Postgres Cheat Sheet] ( #postgres-cheat-sheet )
14
+ - [ Hands-on SQL] ( #hands-on-sql )
15
+ - [ Creating a database] ( #creating-a-database )
16
+ - [ Connecting to databases] ( #connecting-to-databases )
17
+ - [ Create a table without constraints] ( #create-a-table-without-constraints )
18
+ - [ Drop table] ( #drop-table )
19
+ - [ Create table with constraints] ( #create-table-with-constraints )
20
+ - [ Insert data] ( #insert-data )
21
+ - [ Selects] ( #selects )
22
+ - [ Adding data] ( #adding-data )
23
+ - [ Sorting] ( #sorting )
24
+ - [ Remove duplicates] ( #remove-duplicates )
25
+ - [ Where clause] ( #where-clause )
26
+ - [ Limit, Offset and Fetch] ( #limit-offset-and-fetch )
27
+ - [ In] ( #in )
28
+ - [ Between] ( #between )
29
+ - [ Like] ( #like )
30
+ - [ Group by] ( #group-by )
31
+ - [ Having] ( #having )
32
+ - [ Union] ( #union )
33
+ - [ Union all] ( #union-all )
34
+ - [ Except and Intersect] ( #except-and-intersect )
35
+ - [ Aggregate functions] ( #aggregate-functions )
36
+ - [ Max, Min, Avg] ( #max-min-avg )
37
+ - [ Sum] ( #sum )
38
+ - [ Arithmetic Operators] ( #arithmetic-operators )
39
+ - [ Working with Arithmetic Operators] ( #working-with-arithmetic-operators )
40
+ - [ Alias] ( #alias )
41
+ - [ Null handling] ( #null-handling )
42
+ - [ Coalesce] ( #coalesce )
43
+ - [ Null if] ( #null-if )
44
+ - [ Dates] ( #dates )
45
+ - [ Adding & ; Subtracting Dates] ( #adding--subtracting-dates )
46
+ - [ Extracting Fields From Dates] ( #extracting-fields-from-dates )
47
+ - [ tableAge function] ( #tableage-function )
48
+ - [ DDL - Data Definition Language] ( #ddl---data-definition-language )
49
+ - [ Create, Alter and Drop] ( #create-alter-and-drop )
50
+ - [ Primary Key Constraint] ( #primary-key-constraint )
51
+ - [ Unique Constraint] ( #unique-constraint )
52
+ - [ Check Constraint] ( #check-constraint )
53
+ - [ DML - Data Manipulation Language] ( #dml---data-manipulation-language )
54
+ - [ Selecting records] ( #selecting-records )
55
+ - [ Inserting Records] ( #inserting-records )
56
+ - [ Deleting Records] ( #deleting-records )
57
+ - [ Updating Records] ( #updating-records )
58
+ - [ On Conflict Do Nothing] ( #on-conflict-do-nothing )
59
+ - [ On Conflict Do Update] ( #on-conflict-do-update )
60
+ - [ Relationships (Foreign Keys & ; Joins)] ( #relationships-foreign-keys--joins )
61
+ - [ Updating Foreign Keys] ( #updating-foreign-keys )
62
+ - [ Inner Joins] ( #inner-joins )
63
+ - [ Left Joins] ( #left-joins )
64
+ - [ Deleting Foreign Keys] ( #deleting-foreign-keys )
65
+ - [ Sequences] ( #sequences )
66
+ - [ Extensions] ( #extensions )
67
+ - [ Using UUIDs] ( #using-uuids )
68
+ - [ Exporting to CSV] ( #exporting-to-csv )
69
+ - [ References] ( #references )
6
70
7
71
## Installing Postgres with Docker
8
72
@@ -30,8 +94,6 @@ This repository is a quick personal reference to using Postgres and elaborating
30
94
31
95
` $ psql -h localhost -p 5432 -U postgres `
32
96
33
-
34
-
35
97
## Postgres Cheat Sheet
36
98
37
99
| Action | PostgreSQL command |
@@ -50,8 +112,6 @@ This repository is a quick personal reference to using Postgres and elaborating
50
112
51
113
[ Link to complete Postgres Cheat Sheet] ( https://postgrescheatsheet.com/#/tables )
52
114
53
-
54
-
55
115
## Hands-on SQL
56
116
57
117
### Creating a database
@@ -116,8 +176,8 @@ At this stage, we will create fake date to interact with the database e create s
116
176
- For the purpose of this training, we can import data for the _ person_ table: [ person.sql file] ( /person.sql )
117
177
118
178
- To execute a SQL script file in Postgres, we can use the ` \i ` command:
119
-
120
- ` $ \i ~/Desktop/person.sql `
179
+
180
+ ` $ \i ~/Desktop/person.sql `
121
181
122
182
### Sorting
123
183
@@ -158,17 +218,17 @@ SELECT * FROM person OFFSET 5 FETCH FIRST 1 ROW ONLY;
158
218
SELECT * FROM person OFFSET 5 FETCH FIRST ROW ONLY;
159
219
```
160
220
161
- ### In
221
+ ### In
162
222
163
223
Array of values and returns results matching these values
164
224
165
225
``` sql
166
226
SELECT * FROM person
167
- WHERE country_of_birth IN (' Brazil' , ' China' , ' France' , ' Mexico' )
227
+ WHERE country_of_birth IN (' Brazil' , ' China' , ' France' , ' Mexico' )
168
228
ORDER BY country_of_birth;
169
229
```
170
230
171
- ### Between
231
+ ### Between
172
232
173
233
Selects data from a range
174
234
@@ -177,9 +237,9 @@ SELECT * FROM person
177
237
WHERE date_of_birth BETWEEN DATE ' 2000-01-01' AND ' 2022-01-01' ;
178
238
```
179
239
180
- ### Like
240
+ ### Like
181
241
182
- An underscore (` _ ` ) in * ` pattern ` * stands for (matches) any single character; a percent sign (` % ` ) matches any sequence of zero or more characters.
242
+ An underscore (` _ ` ) in _ ` pattern ` _ stands for (matches) any single character; a percent sign (` % ` ) matches any sequence of zero or more characters.
183
243
184
244
``` sql
185
245
SELECT * FROM person WHERE email LIKE ' %@google.%' ;
@@ -195,7 +255,7 @@ SELECT * FROM person WHERE country_of_birth ILIKE 'p%';
195
255
196
256
``` sql
197
257
SELECT country_of_birth, COUNT (* ) FROM person
198
- GROUP BY country_of_birth
258
+ GROUP BY country_of_birth
199
259
ORDER BY country_of_birth;
200
260
```
201
261
@@ -204,9 +264,9 @@ SELECT country_of_birth, COUNT(*) FROM person
204
264
Specifies a search condition for a group.
205
265
206
266
``` sql
207
- SELECT country_of_birth, COUNT (* ) FROM person
208
- GROUP BY country_of_birth
209
- HAVING COUNT (* ) > 5
267
+ SELECT country_of_birth, COUNT (* ) FROM person
268
+ GROUP BY country_of_birth
269
+ HAVING COUNT (* ) > 5
210
270
ORDER BY country_of_birth;
211
271
```
212
272
@@ -236,8 +296,6 @@ SELECT column_name(s) FROM table2;
236
296
237
297
### Except and Intersect
238
298
239
-
240
-
241
299
## Aggregate functions
242
300
243
301
[ Link to aggregate functions] ( https://www.postgresql.org/docs/9.5/functions-aggregate.html )
@@ -259,8 +317,6 @@ SELECT SUM(price) FROM car;
259
317
SELECT make, SUM (price) FROM car GROUP BY make;
260
318
```
261
319
262
-
263
-
264
320
## Arithmetic Operators
265
321
266
322
``` sql
@@ -276,22 +332,18 @@ SELECT 10 % 4;
276
332
SELECT make, model, price, ROUND(price * .10 , 2 ), ROUND((price - price * .10 ), 2 ) FROM car;
277
333
```
278
334
279
-
280
-
281
335
## Alias
282
336
283
337
``` sql
284
- SELECT
285
- make,
286
- model,
338
+ SELECT
339
+ make,
340
+ model,
287
341
price AS original_price,
288
342
ROUND(price * .10 , 2 ) AS ten_percent,
289
343
ROUND((price - price * .10 ), 2 ) AS discount_after_ten_percent
290
344
FROM car;
291
345
```
292
346
293
-
294
-
295
347
## Null handling
296
348
297
349
### Coalesce
@@ -320,8 +372,6 @@ SELECT NULLIF(10, 20);
320
372
SELECT COALESCE(10 / NULLIF(0 , 0 ), 0 );
321
373
```
322
374
323
-
324
-
325
375
## Dates
326
376
327
377
[ Date and Time types] ( https://www.postgresql.org/docs/current/datatype-datetime.html )
@@ -356,9 +406,7 @@ SELECT first_name, last_name, date_of_birth, AGE(NOW(), date_of_birth) AS age FR
356
406
-- then extract fields from dates
357
407
```
358
408
359
-
360
-
361
- ## DDL - Data Definition Language
409
+ ## DDL - Data Definition Language
362
410
363
411
### Create, Alter and Drop
364
412
@@ -377,7 +425,7 @@ CREATE TABLE contacts(
377
425
email VARCHAR (100 ),
378
426
PRIMARY KEY (contact_id),
379
427
CONSTRAINT fk_customer
380
- FOREIGN KEY (customer_id)
428
+ FOREIGN KEY (customer_id)
381
429
REFERENCES customers(customer_id)
382
430
);
383
431
```
@@ -394,7 +442,7 @@ ALTER TABLE table_name ADD column_name datatype;
394
442
-- Remove column from table
395
443
ALTER TABLE table_name DROP COLUMN column_name;
396
444
397
- -- Change column data type
445
+ -- Change column data type
398
446
ALTER TABLE table_name ALTER COLUMN column_name datatype;
399
447
```
400
448
@@ -425,8 +473,6 @@ Check constraint allow us only to add a string that matches the argument.
425
473
ALTER TABLE person ADD CONSTRAINT gender_constraint CHECK (gender == ' Female' OR ' Male' );
426
474
```
427
475
428
-
429
-
430
476
## DML - Data Manipulation Language
431
477
432
478
### Selecting records
@@ -440,7 +486,7 @@ SELECT column1, column2, ... FROM table_name;
440
486
``` sql
441
487
INSERT INTO person (first_name, last_name, gender, email, date_of_birth, country_of_birth)
442
488
VALUES (
' John' ,
' Doe' ,
' Male' ,
' [email protected] ' ,
DATE ' 1960-01-01' ,
' Canada' );
443
-
489
+
444
490
-- Multirow insert
445
491
INSERT INTO table_name (column_list)
446
492
VALUES
@@ -454,7 +500,7 @@ VALUES
454
500
455
501
``` sql
456
502
-- BE CAREFUL: Deletes every record in the table
457
- DELETE FROM person;
503
+ DELETE FROM person;
458
504
459
505
-- Selectively deletes record
460
506
DELETE FROM person WHERE id = 1 ;
469
515
-- Selectively deletes record
470
516
UPDATE person
SET email
= ' [email protected] ' WHERE id
= 1 ;
471
517
472
- -- Update multiple columns
518
+ -- Update multiple columns
473
519
UPDATE person
SET email
= ' [email protected] ' , name
= ' John Doe' WHERE id
= 1 ;
474
520
```
475
521
476
522
### On Conflict Do Nothing
477
523
478
- Handle errors. To use it, column must be a primary key or have a unique constraint.
524
+ Handle errors. To use it, column must be a primary key or have a unique constraint.
479
525
480
526
``` sql
481
527
INSERT INTO person (id, first_name, last_name, gender, email, date_of_birth, country_of_birth)
@@ -489,24 +535,22 @@ INSERT INTO person (id, first_name, last_name, gender, email, date_of_birth, cou
489
535
490
536
### On Conflict Do Update
491
537
492
- In this case, we want to update certain fields if the insert encounters an error.
538
+ In this case, we want to update certain fields if the insert encounters an error.
493
539
494
540
``` sql
495
541
-- email refers to the current email and EXCLUDED.email refers to the one inste de VALUES array
496
542
INSERT INTO person (id, first_name, last_name, gender, email, date_of_birth, country_of_birth)
497
543
VALUES (
1 ,
' John' ,
' Doe' ,
' Male' ,
' [email protected] ' ,
DATE ' 1960-01-01' ,
' Canada' )
498
- ON CONFLICT (id) DO UPDATE SET email = EXCLUDED .email ;
544
+ ON CONFLICT (id) DO UPDATE SET email = EXCLUDED .email ;
499
545
500
546
INSERT INTO person (id, first_name, last_name, gender, email, date_of_birth, country_of_birth)
501
547
VALUES (
1 ,
' John' ,
' Doe' ,
' Male' ,
' [email protected] ' ,
DATE ' 1960-01-01' ,
' Canada' )
502
- ON CONFLICT (id) DO UPDATE SET email = EXCLUDED .email , first_name = EXCLUDED .first_name ;
548
+ ON CONFLICT (id) DO UPDATE SET email = EXCLUDED .email , first_name = EXCLUDED .first_name ;
503
549
```
504
550
551
+ ## Relationships (Foreign Keys & Joins)
505
552
506
-
507
- ## Relationships (Foreign Keys & Joins)
508
-
509
- To follow along, remove the current data and recreate tables and date using the given script.
553
+ To follow along, remove the current data and recreate tables and date using the given script.
510
554
511
555
``` sql
512
556
DROP TABLE person;
@@ -531,10 +575,10 @@ Links two tables where primary key and the foreign key is found in both tables.
531
575
532
576
``` sql
533
577
SELECT * FROM person
534
- JOIN car ON person .car_id = car .id ;
578
+ JOIN car ON person .car_id = car .id ;
535
579
536
580
SELECT person .first_name , car .make , car .model FROM person
537
- JOIN car ON person .car_id = car .id ;
581
+ JOIN car ON person .car_id = car .id ;
538
582
```
539
583
540
584
### Left Joins
@@ -543,11 +587,11 @@ Links two tables including records that don't have a foreign key relationship (a
543
587
544
588
``` sql
545
589
SELECT * FROM person
546
- LEFT JOIN car ON person .car_id = car .id ;
590
+ LEFT JOIN car ON person .car_id = car .id ;
547
591
548
592
SELECT * FROM person
549
593
LEFT JOIN car ON person .car_id = car .id
550
- WHERE car.* IS NULL ;
594
+ WHERE car.* IS NULL ;
551
595
```
552
596
553
597
### Deleting Foreign Keys
@@ -557,8 +601,6 @@ DELETE FROM person WHERE id = 1;
557
601
DELETE FROM car WHERE id = 2 ;
558
602
```
559
603
560
-
561
-
562
604
## Sequences
563
605
564
606
``` sql
@@ -571,16 +613,14 @@ ALTER SEQUENCE person_id_seq RESTART WITH 10;
571
613
SELECT * FROM person_id_seq;
572
614
```
573
615
574
-
575
-
576
616
## Extensions
577
617
578
618
``` sql
579
619
SELECT * FROM pg_available_extensions ORDER BY name;
580
620
581
621
CREATE EXTENSION IF NOT EXISTS " uuid-ossp" ;
582
622
583
- SELECT uuid_generate_v4();
623
+ SELECT uuid_generate_v4();
584
624
```
585
625
586
626
### Using UUIDs
@@ -596,17 +636,12 @@ SELECT * FROM person LEFT JOIN car USING (car_uid);
596
636
SELECT * FROM person LEFT JOIN car USING (car_uid) WHERE car.* IS NULL ;
597
637
```
598
638
599
-
600
-
601
639
## Exporting to CSV
602
640
603
641
``` sql
604
642
\copy (SELECT * FROM person LEFT JOIN car ON person .car_uid = car .car_uid ;) TO ' ~/Desktop/results.csv' DELIMITER ' ,' CSV HEADER;
605
643
```
606
644
607
-
608
-
609
645
## References
610
646
611
647
The content of this repository was based on [ this] ( https://www.youtube.com/watch?v=5hzZtqCNQKk ) course and some personal research.
612
-
0 commit comments