PostgreSQL Cheat Sheet

Some things to note about SQL:

  • All SQL statements end in a semicolon.

  • You can separate statements into separate lines, for readability, as long as you declare the end with a semicolon.

  • Capitalizing commands is optional, but highly recommended for readability.

  • Need help, or more explanations? Try the tutorials at PG Exercises or Schemaverse.

PSQL Commands

\list           - list all available databases
\dt             - list all tables in the current database
\d+ tablename   - look at a table's structure
\connect testdb - connect to database (specify name)
\c testdb       - connect to database (shorthand)
\conninfo       - check connection info
\?              - all psql commands
\help           - all PostgreSQL commands
\q              - quit

SQL Commands

Create a database

Create a table

INSERT data into a table

SELECT data from a table

Select all columns (with wildcard)

SELECT specific columns

Select distinct values from a column

Selecting using WHERE

SELECT using a WHERE clause

NOT EQUAL

LIKE (usually uses a wildcard, '%')

ILIKE (case insensitive)

ORDER BY

AND/OR

IN/NOT IN

LIMIT (returns the first rows)

Example: Limit the query results by returning the first 3 results.

LIMIT + OFFSET

Example: Return results 4-6

Select an aggregate

COUNT

MAX/MIN values

UPDATE data in a table

ALTER table columns and constraints

--

DELETE data from a table

DROP a table

JOINing Tables

SQL Joins

It's good to know the differences between JOINs, but you'll usually use plain JOIN, which performs an INNER JOIN by default.

GROUP BY

Last updated