PostgreSQL Cheatsheet
Create a database
$ createdb sample_app_test
Create a database via psql
Drop a database
$ dropdb "sample_app_test"
Drop a database via psql
Run command on psql without logging in
$ psql -c "\l"
Connect to a database
Start psql with a database
$ psql sample_app_development
List all databases within psql
postgres=# \l
List all tables within a database
sample_app_development=# \d
Create a table
Insert a row
Insert a row (shorthand)
Update a row
Drop a row
Inner join
Inner join with alias
Aggregate functions
Tuple Variables/Alias
loans(loan_id, amount)
Find loans that are greater in amount than some loan in loans.
Why is the DISTINCT there? If DISTINCT isn’t used, for each pair of tuples such that l1.amount > l2.amount, l1.loan_id will appear. For example, let’s assume the following tuples exist in the table:
(1, 10.00)
(2, 20.43)
(3, 31.29)
Without DISTINCT, the second tuple will be returned once, and the third tuple will be returned twice. There is one pair such that the second tuple’s amount is greater than the other tuple’s amount. There are two pairs such that the third tuple’s amount is greater than the other tuple’s amount. Using DISTINCT removes all the redundant tuples.