PostgreSQL Flashcards
PostgreSQL
use Homebrew to start and stop the psql server
brew services start postgresql
brew services stop postgresql
brew services restart postgresql
PostgreSQL
create a new database from the command line
$ createdb dbname
PostgreSQL
delete a database from the command line
$ dropdb dbname
PostgreSQL
backup or export a database from the command line
$ pg_dump dbname > file.sql
PostgreSQL
restore a database from an sql file
$ psql -d dbname < file.sql
PostgreSQL
open an existing database from the command line
$ psql dbname
PostgreSQL
print a list of current databases
\l
\list
PostgreSQL
switch to a different database
\c dbname
PostgreSQL
list existing tables
\dt
PostgreSQL
create a new table in a database
CREATE TABLE
ex
CREATE TABLE users
( id serial,
username CHAR(25) NOT NULL,
enabled boolean DEFAULT TRUE,
PRIMARY KEY (id)
);
PostgreSQL
different data types you can choose for fields added with CREATE TABLE
serial
varchar
boolean
date
time
timestamp
int
decimal / numeric
PostgreSQL
constraints / restrictions that can be specified for columns in a PostgreSQL db
NOT NULL
NULL
DEFAULT
UNIQUE
PRIMARY KEY
FOREIGN KEY
PostgreSQL
list all the columns of the users
table
\d users
PostgreSQL
add a new record to the users
table
INSERT INTO
ex
INSERT INTO users (id, username, enabled)
VALUES (20, ‘Anthony Giuliano’, true);
PostgreSQL
list all the rows and columns from the users
table
SELECT
ex
SELECT * FROM users;
PostgreSQL
clause to add criteria to a SELECT statement so you can filter the results
WHERE
ex
SELECT *
FROM users
WHERE id = 20;
PostgreSQL
clause to sort the results of a SELECT query
ORDER BY
ex
SELECT *
FROM users
ORDER BY id;
SELECT *
FROM users
ORDER BY id DESC;
SELECT *
FROM users
ORDER BY enabled, id DESC;
PostgreSQL
command to alter records in the users
table
UPDATE
updates all records
UPDATE users
SET enabled = false;
updates a specific record specified by where clause UPDATE users
SET enabled = true
WHERE username = ‘John Smith’;
PostgreSQL
clause used with WHERE
to compare a string to a pattern
LIKE
ex
% is a wildcard character
SELECT *
FROM users
WHERE username LIKE ‘%II’;
PostgreSQL
functions applied to a column in order to remove whitespace
trim()
rtrim()
ltrim()
ex
SELECT *
FROM users
WHERE rtrim(username) LIKE ‘% II’;
PostgreSQL
command to delete rows from a table
DELETE
ex
DELETE FROM users
WHERE id = 20;
PostgreSQL
command to change the schema of a table
ALTER TABLE
ex
ALTER TABLE users
ADD COLUMN last_login TIMESTAMP NOT NULL DEFAULT NOW();
PostgreSQL
function that returns the current date and time
NOW()
PostgreSQL
clause to change the name of an existing column
RENAME COLUMN TO
ex
ALTER TABLE users
RENAME COLUMN username TO full_name;
PostgreSQL
clause to change the data type of an existing column
ALTER COLUMN TYPE
ex
ALTER TABLE users
ALTER COLUMN full_name TYPE VARCHAR(25);
PostgreSQL
clause to remove a column from an existing table
DROP COLUMN
ex
ALTER TABLE users
DROP COLUMN enabled;
PostgreSQL
clause to rename an existing table in your database
RENAME TO
ex
ALTER TABLE users
RENAME TO all_users;
PostgreSQL
command to delete an entire table from your database
DROP TABLE
ex
DROP TABLE all_users;
PostgreSQL
ERD (entity relationship diagram)
a graphical representation of the tables in a database and the relationships between them.
PostgreSQL
set up a One to One relationship between two tables
The primary key of the first table is both the foreign key and the primary key of the second table.
ex
Users
CREATE TABLE users (
id serial,
username varchar not null,
primary key (id) );
Addresses
CREATE TABLE addresses (
user_id int not null,
city varchar not null,
state varchar not null,
primary key (user_id),
CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES users(id) );
PostgreSQL
set up a One to Many relationship between two tables
The primary key of the ‘one’ table is the foreign key of the ‘many’ table.
ex
Books table
CREATE TABLE books (
id serial,
title varchar not null,
primary key (id) );
Reviews table
CREATE TABLE reviews (
id serial,
book_id int not null,
review_content varchar,
primary key (id),
foreign key (book_id) references books (id) on delete cascade );
PostgreSQL
an alias for NOW()
CURRENT_TIMESTAMP
PostgreSQL
set up a a Many to Many relationship between books and users
CREATE TABLE books_users (
user_id int not null,
book_id int not null,
checkout_date timestamp,
return_date timestamp,
primary key (user_id, book_id), – composite key
foreign key (user_id) references users (id) on update cascade,
foreign key (book_id) references books (id) on update cascade );
PostgreSQL
clause to ensure that child records in other tables are deleted
ON DELETE CASCADE
Add this clause when setting the foreign key field on the table
ex
CREATE TABLE reviews (
id serial,
book_id int not null,
user_id int not null,
review_content varchar,
rating int,
published_date timestamp default current_timestamp,
primary key (id),
foreign key (book_id) references books (id) on delete cascade,
foreign key (user_id) references users (id) on delete cascade );
PostgreSQL
syntax to make a column a foreign key
FOREIGN KEY (field) REFERENCES table (field)
ex
CREATE TABLE users_books (
book_id int NOT NULL,
FOREIGN KEY (book_id) REFERENCES books (id) ON DELETE CASCADE );
PostgreSQL
make a composite key on a join table
PRIMARY KEY (field1, field2)
ex
CREATE TABLE users_books (
book_id int NOT NULL,
user_id int NOT NULL,
PRIMARY KEY (book_id, user_id),
FOREIGN KEY (book_id) REFERENCES books (id) ON UPDATE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE );
PostgreSQL
set a unique
restriction on a field
UNIQUE (field)
ex
CREATE TABLE users (
email varchar,
UNIQUE (email) );
PostgreSQL
inner join syntax
SELECT users.*, addresses.*
FROM users INNER JOIN addresses
ON users.id = addresses.user_id;
An inner join connects two tables based on the equality of one field from each table. It returns records where the two tables intersect (i.e. only records that exist in both tables).
PostgreSQL
left join syntax
SELECT users.*, addresses.*
FROM users LEFT JOIN addresses
ON users.id = addresses.user_id;
A left join returns all matching records in table A based on certain conditions. with columns from table A and B.
PostgreSQL
cross join syntax
SELECT users.*, addresses.*
FROM users CROSS JOIN addresses;
SELECT *
FROM users CROSS JOIN addresses;
A cross join, or cartensian join, returns all records from both tables. There is no ON clause.
PostgreSQL
right join syntax
SELECT users.*, addresses.*
FROM users RIGHT JOIN addresses
ON users.id = addresses.user_id;
A right join returns all matching records in table B based on certain conditions. with columns from table A and B.
PostgreSQL
export records to CSV
COPY (query)
TO ‘path’
WITH CSV HEADER;
ex
COPY
( SELECT users.*, addresses.* FROM users INNER JOIN addresses ON users.id = addresses.user_id )
TO /absolute/path/to/export.csv
WITH CSV HEADER;
PostgreSQL
the difference between COPY and \copy
COPY is server side and therefore requires absolute file paths;
\copy allows you to specify relative filepaths by initiating copies from the client. COPY is faster.
PostgreSQL
import records from CSV
COPY table_name (field1, field2, field3) FROM ‘path/to/data.csv’ WITH (DELIMITER ‘delim’, HEADER 1, FILEFORMAT CSV);
ex
COPY collections (advance_id, date_booked, amount, management_fee) FROM ‘/users/anthonygiuliano/Desktop/collections_import.csv’ WITH (HEADER 1, FORMAT CSV, DELIMITER ‘,’)
PostgreSQL
combine criteria in a WHERE clause
AND / OR
ex
SELECT *
FROM users
WHERE username = ‘John Smith’ OR username = ‘Jane Smiley’;
ex
SELECT *
FROM books
WHERE title LIKE ‘%My%’ AND author = ‘John Mayer’;
PostgreSQL
function that combines columns and / or strings together into one field
CONCAT
ex
SELECT CONCAT(title, ‘ ‘, ‘by’, ‘ ‘, author) AS “Books By”
FROM books;
PostgreSQL
alias a column name in your results
AS
ex
SELECT count(id) AS enabled_count
FROM users
WHERE enabled = true;
PostgreSQL
filter out duplicate rows in a query
DISTINCT
ex
SELECT DISTINCT u.username
FROM users u
LEFT JOIN users_books ub ON u.id = ub.user_id;
PostgreSQL
cap the number of records returned by a select statement
LIMIT / OFFSET
ex
SELECT *
FROM users
LIMIT 10 OFFSET 10;
PostgreSQL
clause used with WHERE to return records that don’t exist in another set of records
NOT IN
ex
SELECT u.username
FROM users u
WHERE u.id NOT IN
( SELECT ub.user_id FROM users_books ub );
PostgreSQL
function that returns the length of a string
length()
ex
SELECT * FROM books WHERE length(author) = 0;
PostgreSQL
functions that aggregate record count, minimum and maximum values
count()
min()
max()
PostgreSQL
functions that return the current date, time and timestamp
current_date()
current_time()
now()
PostgreSQL
use count
to return the number of unique values in a column
COUNT(DISTINCT field)
ex
SELECT COUNT(DISTINCT description)
FROM transactions;
PostgreSQL
return the sums of various groups of records in one query
SUM, GROUP BY
ex
SELECT SUM(paid_out) AS paid_out_total, description
FROM transactions
GROUP BY description;
PostgreSQL
function to select subfields from date / time values
EXTRACT(SUBFIELD FROM date_field)
ex
SELECT SUM(paid_out), EXTRACT(MONTH FROM date)
FROM transactions
GROUP BY EXTRACT(MONTH FROM date);
PostgreSQL
function to convert various data types to formatted strings
TO_CHAR
ex
SELECT SUM(paid_out), TO_CHAR(date, ‘Month’)
FROM transactions
GROUP BY TO_CHAR(date, ‘Month’);
PostgreSQL
create a field whose value can be one of only a limited number of options
CREATE TYPE day AS ENUM(‘monday’, ‘tuesday’, ‘wednesday’, ‘thursday’, ‘friday’, ‘saturday’, ‘sunday’);
Then use like any other data type
CREATE TABLE messages(
id SERIAL,
day_of_week DAY DEFAULT NULL,
message VARCHAR NOT NULL,
PRIMARY KEY (id) );
PostgreSQL
three different kinds of INTEGER data types
SMALLINT: -32768 to 32767
INT: -2147483648 to 2147483647
BIGINT: -9223372036854775808 to 9223372036854775807
PostgreSQL
clause to ensure that an integer column accept only positive numbers
CHECK
CREATE TABLE people (
age SMALLINT CHECK (age > 0) );
PostgreSQL
create a column that contains decimals
NUMERIC / DECIMAL(total_digits, decimal_digits)
ex
CREATE TABLE decimal_values (
id SERIAL,
item VARCHAR NOT NULL,
value DECIMAL(13, 2) NOT NULL,
PRIMARY KEY (id) );
INSERT INTO decimal_values (item, value)
VALUES (‘Test Item’, 12.35);
INSERT INTO decimal_values (item, value)
VALUES (‘Test Item’, 12.355);
INSERT INTO decimal_values (item, value)
VALUES (‘Test Item’, 12.354);
SELECT * FROM decimal_values;
id | item | value
—-+———–+——-
1 | Test Item | 12.35
2 | Test Item | 12.36
3 | Test Item | 12.35
(3 rows)
PostgreSQL
create an index on a single column
CREATE INDEX ON table (field);
PostgreSQL
delete an existing index on a single column
DROP INDEX index_name
Get the index name by looking at \d table
PostgreSQL
brew services start postgresql
brew services stop postgresql
brew services restart postgresql
use Homebrew to start and stop the psql server
PostgreSQL
$ createdb dbname
create a new database from the command line
PostgreSQL
$ dropdb dbname
delete a database from the command line
PostgreSQL
$ pg_dump dbname > file.sql
backup or export a database from the command line
PostgreSQL
$ psql -d dbname < file.sql
restore a database from an sql file
PostgreSQL
$ psql dbname
open an existing database from the command line
PostgreSQL
\l
\list
print a list of current databases