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.5 KiB
2.5 KiB
PostGres - Advanced
Lesson Objectives - important
- Linking Tables
- Alias
- Indexes
- Constraints
- Distinct
Lesson Objectives - good to know about
- EER Diagrams
- Unions
- Truncate
- Views
- Functions
- Stored Procedures
- Triggers
- Transactions
- Locks
- Privileges
- Denormalization
- Excel -> CSV -> MySQL
Important
Linking Tables
- Some Nice Visuals
- One to Many/Many to One Relationships
- customer has many orders
- One to One Relationships
- each user has one address
- only one person at that address
- Many to Many Relationships
- actors and movies
- 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
CREATE INDEX index_name ON table_name (column_name);CREATE INDEX index_name ON table_name (column1_name, column2_name);- use
\d table_nameto view indexes - Primary Key
Constraints
- NOT NULL
- Unique
- 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);
