---
title: Useful Postgres / PSQL Commands
description: List of often used commands when working with PostgreSQL OR SQL in general
date: 2020-01-29
tags: PostgreSQL
source: https://brianchildress.co/blog/useful-postgres-psql-commands
---

# Useful Postgres / PSQL Commands

### From the Command Line:

_Connecting to a Postgres server_

```sh
psql -h < host > -U < username >
```

_Connect to Database (Once connected to server)_
```sh
\c < database name >
```

_Read File into Database_
```sh
psql -h < host > -U < username > -f < filename >
```

#### Listing Commands

_List Databases_
```sh
\l
```

_List Tables_
```sh
\dt
```

_Query all tables in DB_
```sh
SELECT * FROM INFORMATION_SCHEMA.TABLES
```

_Get row for for a table_

```sql
SELECT COUNT(*) FROM <table name>;
```

_Get a random row from a table_

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

_Delete all data from table_

```sql
TRUNCATE TABLE <table name(s)>;
```

_Delete all data from table **AND** reset the auto-increment id_

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