knowledge/technology/applications/development/Postgres.md
2024-09-30 10:22:19 +02:00

7 KiB

obj website repo
application https://www.postgresql.org https://git.postgresql.org/gitweb/?p=postgresql.git

Postgres

PostgreSQL is an advanced, open-source, object-relational database management system. It is renowned for its scalability, reliability, and compliance with the SQL standard. PostgreSQL supports both SQL (relational) and JSON (non-relational) querying, making it highly versatile.

Extensions

PostgreSQL can be extended via extensions:

psql

psql is a terminal-based front end to PostgreSQL. It allows users to interact with PostgreSQL databases by executing SQL queries, managing database objects, and performing administrative tasks.

To start psql, open your terminal or command prompt and type:

psql

Connecting to a Database

You can specify the database name, user, host, and port when launching psql:

psql -d database_name -U username -h hostname -p port

Alternatively, you can use environment variables:

export PGDATABASE=mydb
export PGUSER=myuser
export PGPASSWORD=mypassword
export PGHOST=localhost
export PGPORT=5432

psql

Listing Databases and Tables

  • List Databases:

    \l
    
  • List Tables in the Current Database:

    \dt
    
  • List All Schemas:

    \dn
    

Creating and Dropping Databases/Tables

  • Create a Database:

    CREATE DATABASE mydb;
    
  • Drop a Database:

    DROP DATABASE mydb;
    
  • Create a Table:

    CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        username VARCHAR(50) NOT NULL,
        email VARCHAR(100) NOT NULL
    );
    
  • Drop a Table:

    DROP TABLE users;
    

Running SQL Queries

Execute standard SQL commands to interact with your data.

Example: Inserting Data

INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com');

Example: Querying Data

SELECT * FROM users;

Example: Updating Data

UPDATE users SET email = 'john.doe@example.com' WHERE username = 'john_doe';

Example: Deleting Data

DELETE FROM users WHERE username = 'john_doe';

Meta-Commands

psql provides a set of meta-commands (prefixed with \) that facilitate various tasks.

Common Meta-Commands

  • Help on Meta-Commands:

    \?
    
  • Help on SQL Commands:

    \h
    
  • Describe a Table:

    \d table_name
    
  • List All Tables, Views, and Sequences:

    \dt
    
  • List All Indexes:

    \di
    
  • Exit psql:

    \q
    

Data Types

1. Numeric Types

  • Small Integer Types
    • SMALLINT (2 bytes): Range from -32,768 to +32,767
  • Integer Types
    • INTEGER or INT (4 bytes): Range from -2,147,483,648 to +2,147,483,647
  • Big Integer Types
    • BIGINT (8 bytes): Range from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
  • Decimal/Exact Types
    • DECIMAL or NUMERIC (variable size): User-defined precision and scale
  • Floating-Point Types
    • REAL (4 bytes): Single precision floating-point number
    • DOUBLE PRECISION (8 bytes): Double precision floating-point number
  • Serial Types (Auto-Incrementing)
    • SERIAL (4 bytes): Auto-incrementing integer (small range)
    • BIGSERIAL (8 bytes): Auto-incrementing integer (large range)
    • SMALLSERIAL (2 bytes): Auto-incrementing integer (smaller range)

2. Monetary Type

  • MONEY: Stores currency amounts with a fixed fractional precision

3. Character Types

  • Fixed-Length Strings
    • CHAR(n) or CHARACTER(n): Fixed length (padded with spaces)
  • Variable-Length Strings
    • VARCHAR(n) or CHARACTER VARYING(n): Variable length with a limit
  • Text
    • TEXT: Variable length with no specific limit

4. Binary Data Types

  • Binary Large Object
    • BYTEA: Stores binary strings (byte arrays)

5. Date/Time Types

  • Date and Time
    • DATE: Calendar date (year, month, day)
    • TIME (no time zone): Time of day (without time zone)
    • TIMETZ (with time zone): Time of day (with time zone)
    • TIMESTAMP (no time zone): Date and time without time zone
    • TIMESTAMPTZ (with time zone): Date and time with time zone
  • Intervals
    • INTERVAL: Time span (e.g., days, months, hours)

6. Boolean Type

  • BOOLEAN: Stores TRUE, FALSE, or NULL

7. UUID Type

  • UUID: Stores Universally Unique Identifiers (128-bit values)

8. Enumerated Types

  • ENUM: User-defined enumerated type (a static set of values)

9. Geometric Types

  • POINT: Stores a geometric point (x, y)
  • LINE: Infinite line
  • LSEG: Line segment
  • BOX: Rectangular box
  • PATH: Geometric path (multiple points)
  • POLYGON: Closed geometric figure
  • CIRCLE: Circle

10. Network Address Types

  • CIDR: IPv4 or IPv6 network block
  • INET: IPv4 or IPv6 address
  • MACADDR: MAC address
  • MACADDR8: MAC address (EUI-64 format)

11. Bit String Types

  • Fixed-Length Bit Strings
    • BIT(n): Fixed-length bit string
  • Variable-Length Bit Strings
    • BIT VARYING(n): Variable-length bit string

12. Text Search Types

  • TSVECTOR: Text search document
  • TSQUERY: Text search query

13. JSON Types

  • JSON: Textual JSON data
  • JSONB: Binary JSON data (more efficient for indexing)

14. Array Types

  • ARRAY: Allows any data type to be stored as an array (e.g., INTEGER[], TEXT[])

15. Range Types

  • INT4RANGE: Range of INTEGER
  • INT8RANGE: Range of BIGINT
  • NUMRANGE: Range of NUMERIC
  • TSRANGE: Range of TIMESTAMP WITHOUT TIME ZONE
  • TSTZRANGE: Range of TIMESTAMP WITH TIME ZONE
  • DATERANGE: Range of DATE

16. Composite Types

  • User-defined types that consist of multiple fields of various types

17. Object Identifier Types (OID)

  • OID: Object identifier (used internally by PostgreSQL)
  • REGCLASS, REGPROC, REGTYPE: Special types for referencing classes, procedures, and types by OID or name

18. Pseudo-Types

  • ANY: Accepts any data type
  • ANYARRAY: Accepts any array data type
  • ANYELEMENT: Represents any type of element
  • ANYENUM: Accepts any ENUM type
  • ANYNONARRAY: Any non-array type
  • VOID: No data (used with functions that return no value)
  • TRIGGER: Used in triggers
  • LANGUAGE_HANDLER: Used internally for language support

Docker-Compose

services:
  postgres:
    image: postgres:17
    container_name: postgres
    environment:
      POSTGRES_USER: myuser
      POSTGRES_PASSWORD: mypassword
      POSTGRES_DB: mydb
    ports:
      - "5432:5432"
    volumes:
      - ./postgres:/var/lib/postgresql/data
    restart: always