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;