# PostgreSQL

## Interactively create a user

(Is a shell command)

```
$ createuser --interactive --pwprompt
Enter name of role to add: <USER>
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n
```

## Create a database

(Is a shell command)

Also sets the owner

```
$ createdb -O <OWNER> <DBNAME>
```

## Commands for the psql shell

```
\l          list databases
\c <DB>     connect to a database
\dt         list tables
\d <TABLE>  describe table
\df         list functions
\dy         list trigger
```

## Find and kill query process

To get a list of all currently running query process (like `SHOW FULL PROCESSLIST` from MySQL) enter:

```sql
SELECT * FROM pg_stat_activity;
```

If you know the name of the database you can filter with it like so:

```sql
SELECT * FROM pg_stat_activity WHERE datname= '<database name>';
```

With the entry of the `pid` column you can terminate or kill the process:

```sql
SELECT pg_cancel_backend(<pid>);  # Stop gracefully
SELECT pg_terminate_backend(<pid>);  # Kill
```

## View locks

```sql
SELECT * FROM pg_locks;
```

