You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.7 KiB

PostGres - Advanced

Lesson Objectives - important

  1. Linking Tables
  2. Alias
  3. Indexes
  4. Constraints
  5. Distinct

Lesson Objectives - good to know about

  1. EER Diagrams
  2. Unions
  3. Truncate
  4. Views
  5. Functions
  6. Stored Procedures
  7. Triggers
  8. Transactions
  9. Locks
  10. Privileges
  11. Denormalization
  12. Excel -> CSV -> MySQL

Important

Linking Tables

  1. Some Nice Visuals
  2. One to Many/Many to One Relationships
    • customer has many orders
  3. One to One Relationships
    • each user has one address
    • only one person at that address
  4. Many to Many Relationships
    • actors and movies
  5. Self Referncing Relationships
    • customer referral

Alias

SELECT t1.column1 as col1, t2.column2 as col2
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.common_filed = t2.common_field;

Indexes

  1. CREATE INDEX index_name ON table_name (column_name);
  2. CREATE INDEX index_name ON table_name (column1_name, column2_name);
  3. use \d table_name to view indexes
  4. Primary Key

Constraints

  1. NOT NULL
  2. Unique
  3. Foreign Keys
CREATE TABLE companies(
  id          SERIAL       PRIMARY KEY,
  name        VARCHAR(16)  NOT NULL UNIQUE,
  city        VARCHAR(16)
);
INSERT INTO companies ( city ) VALUES ('Palo Alto');
CREATE TABLE people(
  id          INT          PRIMARY KEY,
  name        VARCHAR(16)  NOT NULL,
  email       VARCHAR(32)  NOT NULL UNIQUE,
  company_id  INT          REFERENCES companies(id)
);
INSERT INTO people (name, email, company_id) VALUES ('bob', 'bob@bob.com', 999)

Distinct

SELECT DISTINCT city FROM people;

Good to Know About

EER Diagrams

Unions

SELECT name FROM people UNION SELECT name FROM companies; -- show distinct values
SELECT name FROM people UNION ALL SELECT name FROM companies; -- show duplicates

Truncate

TRUNCATE TABLE people; -- delete all data, but don't delete table itself

Views

CREATE VIEW new_yorkers AS SELECT * FROM people WHERE city = 'NYC';
SELECT * FROM new_yorkers

Functions

CREATE FUNCTION add_numbers(a integer, b integer) RETURNS integer AS $$
	BEGIN
		RETURN a + b;
	END;
$$ LANGUAGE plpgsql;

SELECT add_numbers(2,4);

Stored Procedures

CREATE PROCEDURE add_person(new_name VARCHAR(16))
LANGUAGE plpgsql
AS $$
BEGIN
	INSERT INTO people (name) VALUES (new_name);
END
$$;

call add_person('matt');

Triggers

Transactions

Locks

Privileges

Denormalization

Excel -> CSV -> MySQL

SQL Injection