Skip to content

Commit a8ed1a9

Browse files
committed
Add table of contents for GitHub
1 parent e599361 commit a8ed1a9

File tree

1 file changed

+96
-61
lines changed

1 file changed

+96
-61
lines changed

README.md

Lines changed: 96 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,71 @@
22

33
This repository is a quick personal reference to using Postgres and elaborating SQL queries.
44

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 &amp; 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 &amp; 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)
670

771
## Installing Postgres with Docker
872

@@ -30,8 +94,6 @@ This repository is a quick personal reference to using Postgres and elaborating
3094

3195
`$ psql -h localhost -p 5432 -U postgres`
3296

33-
34-
3597
## Postgres Cheat Sheet
3698

3799
| Action | PostgreSQL command |
@@ -50,8 +112,6 @@ This repository is a quick personal reference to using Postgres and elaborating
50112

51113
[Link to complete Postgres Cheat Sheet](https://postgrescheatsheet.com/#/tables)
52114

53-
54-
55115
## Hands-on SQL
56116

57117
### Creating a database
@@ -116,8 +176,8 @@ At this stage, we will create fake date to interact with the database e create s
116176
- For the purpose of this training, we can import data for the _person_ table: [person.sql file](/person.sql)
117177

118178
- 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`
121181

122182
### Sorting
123183

@@ -158,17 +218,17 @@ SELECT * FROM person OFFSET 5 FETCH FIRST 1 ROW ONLY;
158218
SELECT * FROM person OFFSET 5 FETCH FIRST ROW ONLY;
159219
```
160220

161-
### In
221+
### In
162222

163223
Array of values and returns results matching these values
164224

165225
```sql
166226
SELECT * FROM person
167-
WHERE country_of_birth IN ('Brazil', 'China', 'France', 'Mexico')
227+
WHERE country_of_birth IN ('Brazil', 'China', 'France', 'Mexico')
168228
ORDER BY country_of_birth;
169229
```
170230

171-
### Between
231+
### Between
172232

173233
Selects data from a range
174234

@@ -177,9 +237,9 @@ SELECT * FROM person
177237
WHERE date_of_birth BETWEEN DATE '2000-01-01' AND '2022-01-01';
178238
```
179239

180-
### Like
240+
### Like
181241

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.
183243

184244
```sql
185245
SELECT * FROM person WHERE email LIKE '%@google.%';
@@ -195,7 +255,7 @@ SELECT * FROM person WHERE country_of_birth ILIKE 'p%';
195255

196256
```sql
197257
SELECT country_of_birth, COUNT(*) FROM person
198-
GROUP BY country_of_birth
258+
GROUP BY country_of_birth
199259
ORDER BY country_of_birth;
200260
```
201261

@@ -204,9 +264,9 @@ SELECT country_of_birth, COUNT(*) FROM person
204264
Specifies a search condition for a group.
205265

206266
```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
210270
ORDER BY country_of_birth;
211271
```
212272

@@ -236,8 +296,6 @@ SELECT column_name(s) FROM table2;
236296

237297
### Except and Intersect
238298

239-
240-
241299
## Aggregate functions
242300

243301
[Link to aggregate functions](https://www.postgresql.org/docs/9.5/functions-aggregate.html)
@@ -259,8 +317,6 @@ SELECT SUM(price) FROM car;
259317
SELECT make, SUM(price) FROM car GROUP BY make;
260318
```
261319

262-
263-
264320
## Arithmetic Operators
265321

266322
```sql
@@ -276,22 +332,18 @@ SELECT 10 % 4;
276332
SELECT make, model, price, ROUND(price * .10, 2), ROUND((price - price * .10), 2) FROM car;
277333
```
278334

279-
280-
281335
## Alias
282336

283337
```sql
284-
SELECT
285-
make,
286-
model,
338+
SELECT
339+
make,
340+
model,
287341
price AS original_price,
288342
ROUND(price * .10, 2) AS ten_percent,
289343
ROUND((price - price * .10), 2) AS discount_after_ten_percent
290344
FROM car;
291345
```
292346

293-
294-
295347
## Null handling
296348

297349
### Coalesce
@@ -320,8 +372,6 @@ SELECT NULLIF(10, 20);
320372
SELECT COALESCE(10 / NULLIF(0, 0), 0);
321373
```
322374

323-
324-
325375
## Dates
326376

327377
[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
356406
-- then extract fields from dates
357407
```
358408

359-
360-
361-
## DDL - Data Definition Language
409+
## DDL - Data Definition Language
362410

363411
### Create, Alter and Drop
364412

@@ -377,7 +425,7 @@ CREATE TABLE contacts(
377425
email VARCHAR(100),
378426
PRIMARY KEY(contact_id),
379427
CONSTRAINT fk_customer
380-
FOREIGN KEY(customer_id)
428+
FOREIGN KEY(customer_id)
381429
REFERENCES customers(customer_id)
382430
);
383431
```
@@ -394,7 +442,7 @@ ALTER TABLE table_name ADD column_name datatype;
394442
-- Remove column from table
395443
ALTER TABLE table_name DROP COLUMN column_name;
396444

397-
-- Change column data type
445+
-- Change column data type
398446
ALTER TABLE table_name ALTER COLUMN column_name datatype;
399447
```
400448

@@ -425,8 +473,6 @@ Check constraint allow us only to add a string that matches the argument.
425473
ALTER TABLE person ADD CONSTRAINT gender_constraint CHECK (gender == 'Female' OR 'Male');
426474
```
427475

428-
429-
430476
## DML - Data Manipulation Language
431477

432478
### Selecting records
@@ -440,7 +486,7 @@ SELECT column1, column2, ... FROM table_name;
440486
```sql
441487
INSERT INTO person (first_name, last_name, gender, email, date_of_birth, country_of_birth)
442488
VALUES ('John', 'Doe', 'Male', '[email protected]', DATE '1960-01-01', 'Canada');
443-
489+
444490
-- Multirow insert
445491
INSERT INTO table_name (column_list)
446492
VALUES
@@ -454,7 +500,7 @@ VALUES
454500

455501
```sql
456502
-- BE CAREFUL: Deletes every record in the table
457-
DELETE FROM person;
503+
DELETE FROM person;
458504

459505
-- Selectively deletes record
460506
DELETE FROM person WHERE id = 1;
@@ -469,13 +515,13 @@ UPDATE person SET email = '[email protected]';
469515
-- Selectively deletes record
470516
UPDATE person SET email = '[email protected]' WHERE id = 1;
471517

472-
-- Update multiple columns
518+
-- Update multiple columns
473519
UPDATE person SET email = '[email protected]', name = 'John Doe' WHERE id = 1;
474520
```
475521

476522
### On Conflict Do Nothing
477523

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.
479525

480526
```sql
481527
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
489535

490536
### On Conflict Do Update
491537

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.
493539

494540
```sql
495541
-- email refers to the current email and EXCLUDED.email refers to the one inste de VALUES array
496542
INSERT INTO person (id, first_name, last_name, gender, email, date_of_birth, country_of_birth)
497543
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;
499545

500546
INSERT INTO person (id, first_name, last_name, gender, email, date_of_birth, country_of_birth)
501547
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;
503549
```
504550

551+
## Relationships (Foreign Keys & Joins)
505552

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.
510554

511555
```sql
512556
DROP TABLE person;
@@ -531,10 +575,10 @@ Links two tables where primary key and the foreign key is found in both tables.
531575

532576
```sql
533577
SELECT * FROM person
534-
JOIN car ON person.car_id = car.id;
578+
JOIN car ON person.car_id = car.id;
535579

536580
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;
538582
```
539583

540584
### Left Joins
@@ -543,11 +587,11 @@ Links two tables including records that don't have a foreign key relationship (a
543587

544588
```sql
545589
SELECT * FROM person
546-
LEFT JOIN car ON person.car_id = car.id;
590+
LEFT JOIN car ON person.car_id = car.id;
547591

548592
SELECT * FROM person
549593
LEFT JOIN car ON person.car_id = car.id
550-
WHERE car.* IS NULL;
594+
WHERE car.* IS NULL;
551595
```
552596

553597
### Deleting Foreign Keys
@@ -557,8 +601,6 @@ DELETE FROM person WHERE id = 1;
557601
DELETE FROM car WHERE id = 2;
558602
```
559603

560-
561-
562604
## Sequences
563605

564606
```sql
@@ -571,16 +613,14 @@ ALTER SEQUENCE person_id_seq RESTART WITH 10;
571613
SELECT * FROM person_id_seq;
572614
```
573615

574-
575-
576616
## Extensions
577617

578618
```sql
579619
SELECT * FROM pg_available_extensions ORDER BY name;
580620

581621
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
582622

583-
SELECT uuid_generate_v4();
623+
SELECT uuid_generate_v4();
584624
```
585625

586626
### Using UUIDs
@@ -596,17 +636,12 @@ SELECT * FROM person LEFT JOIN car USING (car_uid);
596636
SELECT * FROM person LEFT JOIN car USING (car_uid) WHERE car.* IS NULL;
597637
```
598638

599-
600-
601639
## Exporting to CSV
602640

603641
```sql
604642
\copy (SELECT * FROM person LEFT JOIN car ON person.car_uid = car.car_uid;) TO '~/Desktop/results.csv' DELIMITER ',' CSV HEADER;
605643
```
606644

607-
608-
609645
## References
610646

611647
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

Comments
 (0)