Useful Postgres / PSQL Commands

Jan 29, 2020 min read

From the Command Line:

Connecting to a Postgres server

psql -h < host > -U < username >

Connect to Database (Once connected to server)

\c < database name >

Read File into Database

psql -h < host > -U < username > -f < filename >

Listing Commands

List Databases

\l

List Tables

\dt

Query all tables in DB

SELECT * FROM INFORMATION_SCHEMA.TABLES

Get row for for a table

SELECT COUNT(*) FROM <table name>;

Get a random row from a table

SELECT * FROM <table name> OFFSET floor(random() * (SELECT COUNT(*) FROM <table name>)) LIMIT 1;

Delete all data from table

TRUNCATE TABLE <table name(s)>;

Delete all data from table AND reset the auto-increment id

TRUNCATE TABLE <table name(s)> RESTART IDENTITY;