DEV Community

Cover image for Postgresql Cheat Sheet
Kaemon Lovendahl
Kaemon Lovendahl

Posted on

Postgresql Cheat Sheet

General Commands:

  1. Connection
psql -h localhost -d johto -U silver
Enter fullscreen mode Exit fullscreen mode

Prompt: Password for user silver: (Enter your password and press enter)

  1. List Databases
\l
Enter fullscreen mode Exit fullscreen mode

Prompt:

                              List of databases
   Name    |  Owner   | Encoding | Collate | Ctype |   Access privileges
-----------+----------+----------+---------+-------+-----------------------
 johto     | myuser   | UTF8     | C.UTF-8 | C.UTF-8 |
 hoenn     | postgres | UTF8     | C.UTF-8 | C.UTF-8 |
 postgres  | postgres | UTF8     | C.UTF-8 | C.UTF-8 | =c/postgres          +
           |          |          |         |         | postgres=CTc/postgres
 template1 | postgres | UTF8     | C.UTF-8 | C.UTF-8 | =c/postgres          +
           |          |          |         |         | postgres=CTc/postgres
(4 rows)
Enter fullscreen mode Exit fullscreen mode
  1. List Tables
\dt
Enter fullscreen mode Exit fullscreen mode

Prompt:

          List of relations
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | user | table | silver
(1 row)
Enter fullscreen mode Exit fullscreen mode

User and Role Management:

  1. Create User
CREATE USER silver WITH PASSWORD 'totodileRulez';
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE ROLE

  1. Grant Privileges
GRANT ALL PRIVILEGES ON DATABASE johto TO silver;
Enter fullscreen mode Exit fullscreen mode

Prompt: GRANT

  1. Create Role
CREATE ROLE trainer WITH LOGIN PASSWORD 'totodileRulez';
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE ROLE


Database Actions:

  1. Create Database
CREATE DATABASE johto;
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE DATABASE

  1. Drop Database
DROP DATABASE johto;
Enter fullscreen mode Exit fullscreen mode

Prompt: DROP DATABASE


Query Methods:

  1. Select All
SELECT * FROM pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 id |   name   
----+----------
  1 | Teddiursa
  2 | Sunkern
(2 rows)
Enter fullscreen mode Exit fullscreen mode
  1. Where Clause
SELECT * FROM pokemon WHERE name = 'Espeon';
Enter fullscreen mode Exit fullscreen mode

Prompt:

 id |   name   
----+----------
  1 | Espeon
(1 row)
Enter fullscreen mode Exit fullscreen mode

Complex Commands:

  1. Join Tables
SELECT * FROM pokemon INNER JOIN moves ON pokemon.id = moves.pokemon_id;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 pokemon_id | name    | move_id | move  
------------+---------+---------+----------
       1 | Teddiursa|        1 | Tackle
       2 | Sunkern |        2 | Vine Whip
(2 rows)
Enter fullscreen mode Exit fullscreen mode

More Query Methods:

  1. Max
SELECT MAX(level) FROM pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 max
-----
  100
(1 row)
Enter fullscreen mode Exit fullscreen mode
  1. Min
SELECT MIN(level) FROM pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 min
-----
  1
(1 row)
Enter fullscreen mode Exit fullscreen mode
  1. Avg
SELECT AVG(level) FROM pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

        avg
---------------------
 50.5000000000000000
(1 row)
Enter fullscreen mode Exit fullscreen mode
  1. Sum
SELECT SUM(level) FROM pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 sum
-----
 101
(1 row)
Enter fullscreen mode Exit fullscreen mode
  1. Group By
SELECT COUNT(*), type FROM pokemon GROUP BY type;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 count |   type   
-------+-------------
    2 | Dark
    3 | Steel
(2 rows)
Enter fullscreen mode Exit fullscreen mode
  1. Order By
SELECT * FROM pokemon ORDER BY level DESC;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 id |   name    | level | type 
----+-----------+-----+---------
  1 | Unown|  100 | Psychic
  3 | Snubbul|  33 | Fairy
  2 | Ursaring|  1 | Normal
(3 rows)
Enter fullscreen mode Exit fullscreen mode

More Complex Commands:

  1. Subquery
SELECT * FROM (SELECT * FROM pokemon ORDER BY level DESC LIMIT 2) AS subquery;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 id |   name    | level | type 
----+-----------+-----+---------
  1 | Chikorita |  100 | Grass
  3 | Cyndaquil |  33 | Fire
(2 rows)
Enter fullscreen mode Exit fullscreen mode
  1. Create Index
CREATE INDEX idx_pokemon_level ON pokemon(level);
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE INDEX

  1. Create View
CREATE VIEW high_level_pokemon AS SELECT * FROM pokemon WHERE level > 50;
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE VIEW

  1. Select from View
SELECT * FROM high_level_pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 id |   name    | level | type 
----+-----------+-----+---------
  1 | Totodile  |  100 | Water
(1 row)
Enter fullscreen mode Exit fullscreen mode

More Query Methods:

  1. Select Distinct
SELECT DISTINCT type FROM pokemon;
Enter fullscreen mode Exit fullscreen mode

Prompt:

  type  
-----------
 Grass
 Fire
(2 rows)
Enter fullscreen mode Exit fullscreen mode
  1. Like Operator
SELECT * FROM pokemon WHERE name LIKE '%quil%';
Enter fullscreen mode Exit fullscreen mode

Prompt:

 id |   name    | level | type 
----+-----------+-----+---------
  1 | Cyndaquil |  100 | Fire
  2 | Quilava |  1 | Fire
(2 rows)
Enter fullscreen mode Exit fullscreen mode

Advanced Complex Commands:

  1. Right Join
SELECT * FROM moves RIGHT JOIN pokemon ON pokemon.id = moves.pokemon_id;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 pokemon_id | name  | move_id | move  
------------+-------+---------+----------
       1 | Chikorita|        1 | Tackle
       2 | Bayleef |        2 | Vine Whip
       3 | Cyndaquil |     NULL | NULL
(3 rows)
Enter fullscreen mode Exit fullscreen mode
  1. Full Outer Join
SELECT * FROM moves FULL OUTER JOIN pokemon ON pokemon.id = moves.pokemon_id;
Enter fullscreen mode Exit fullscreen mode

Prompt:

 pokemon_id | name  | move_id | move  
------------+-------+---------+----------
       1 | Chikorita|        1 | Tackle
       2 | Bayleef |        2 | Vine Whip
       3 | Cyndaquil |     NULL | NULL
(3 rows)
Enter fullscreen mode Exit fullscreen mode
  1. Self Join
SELECT A.name, B.name FROM pokemon A, pokemon B WHERE A.type = B.type AND A.name != B.name;
Enter fullscreen mode Exit fullscreen mode
   name    |   name   
-----------+----------
 Chikorita| Bayleef 
 Bayleef | Chikorita
(2 rows)
Enter fullscreen mode Exit fullscreen mode

Function and Procedures:

  1. Creating Functions
CREATE FUNCTION increase_level(integer, integer) RETURNS integer AS $$
BEGIN
   RETURN $1 + $2;
END;
$$ LANGUAGE plpgsql;
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE FUNCTION

  1. Calling Functions
SELECT increase_level(1, 2);
Enter fullscreen mode Exit fullscreen mode

Prompt:

 increase_level 
----------------
              3
(1 row)
Enter fullscreen mode Exit fullscreen mode
  1. Creating Procedures
CREATE PROCEDURE archive_old_pokemon() AS $$
BEGIN
   DELETE FROM pokemon WHERE level < 10;
END;
$$ LANGUAGE plpgsql;
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE PROCEDURE

  1. Calling Procedures
CALL archive_old_pokemon();
Enter fullscreen mode Exit fullscreen mode

Prompt: CALL

  1. Creating Triggers
CREATE TRIGGER check_level_before_insert 
BEFORE INSERT ON pokemon 
FOR EACH ROW 
WHEN (NEW.level > 100) 
DO 
$$ 
BEGIN 
   RAISE EXCEPTION 'Level cannot be more than 100'; 
END; 
$$ LANGUAGE plpgsql;
Enter fullscreen mode Exit fullscreen mode

Prompt: CREATE TRIGGER


Error Handling:

PostgreSQL returns errors with specific SQLSTATE values. When an error occurs, an exception is thrown with an associated SQLSTATE value.

For example, if you attempt to create a table that already exists:

CREATE TABLE pokemon(id SERIAL PRIMARY KEY, name VARCHAR(100));
Enter fullscreen mode Exit fullscreen mode

You might get an error like:

ERROR:  relation "pokemon" already exists
Enter fullscreen mode Exit fullscreen mode

In this case, you would need to either drop the existing table or change the name of the table you are trying to create.

Top comments (0)