Skip to content

SQL Cheat Sheet

Postgress

Connect to Database

HOST="host-url.com"
PORT=5432
USER="username"
DATABASE="employees"

PGPASSWORD='<enter password> psql -h $HOST -p $PORT -U $USER -d $DATABASE

List all Databases

\l

Connect to database

\c <database_name>

Show current database

SELECT current_database();

Create database

CREATE DATABASE <database_name> WITH OWNER <username>;

Drop database

DROP DATABASE IF EXISTS <database_name>;

Rename database

ALTER DATABASE <old_name> RENAME TO <new_name>;

Show version

SHOW SERVER_VERSION;

Show system status

\conninfo

Show environmental variables

SHOW ALL;

List users

SELECT rolname FROM pg_roles;

Show current user

SELECT current_user;

Show current user's permissions

\du

Show all tables in database

\dt

Describe table

\d <table>  

Describe table with details

\d+ <table> 

List tables from current schema

\dt 

Use pg_dump to backup a database

HOST="host-url.com"
PORT=5432
USER="username"
DATABASE="employees"

pg_dump --schema-only -U $USER -d $DATABASE -h $HOST -p $PORT  > pgdump_file.sql