Description

SQL (Structured Query Language) is the standard language for creating and manipulating databases. All RDBMSs (MySQL, MS Access, Oracle, Sybase, PostgreSQL, SQL Server) use SQL as their standard database language.

History of SQL

  • 1970: Dr. E. F. "Ted" Codd of IBM, the father of relational databases, describes the relational model.
  • 1974: Structured Query Language appears.
  • 1978: IBM develops Codd's ideas and releases System/R.
  • 1986: IBM develops the first relational prototype; SQL is standardized by ANSI. The first commercial relational database comes from Relational Software, later Oracle.

SQL Rules and Process

  • SQL is not case sensitive; keywords are conventionally written in uppercase.
  • A statement can span one or several text lines.
  • SQL is based on tuple relational calculus and relational algebra.
  • When a command runs, the RDBMS determines the best way to carry it out. The components involved include the optimization engine, query engine and query dispatcher.

Why Use SQL? Advantages

  • Access data in an RDBMS, describe data, define and manipulate data.
  • Create and drop databases and tables; create views, functions and stored procedures.
  • Set permissions on tables, procedures and views.
  • Advantages: high speed, well-defined standards, portability, interactive language, multiple data views.

Types of SQL

TypeNamePurpose
DDLData Definition LanguageCreate and change structures (CREATE, ALTER, DROP, TRUNCATE)
DMLData Manipulation LanguageChange data (INSERT, UPDATE, DELETE)
DCLData Control LanguagePermissions (GRANT, REVOKE)
TCLTransaction Control LanguageTransactions (BEGIN, COMMIT, ROLLBACK)
DQLData Query LanguageRetrieve data (SELECT)

Part I: Data Definition Language (DDL)

DDL commands create, modify and drop database objects: CREATE, DROP, ALTER, TRUNCATE.

CREATE TABLE

CREATE TABLE account (
    user_id    serial PRIMARY KEY,
    username   VARCHAR(50)  UNIQUE NOT NULL,
    password   VARCHAR(50)  NOT NULL,
    email      VARCHAR(355) UNIQUE NOT NULL,
    created_on TIMESTAMP    NOT NULL,
    last_login TIMESTAMP
);

CREATE TABLE role (
    role_id   serial PRIMARY KEY,
    role_name VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE account_role (
    user_id    integer NOT NULL,
    role_id    integer NOT NULL,
    grant_date timestamp,
    PRIMARY KEY (user_id, role_id),
    FOREIGN KEY (role_id) REFERENCES role (role_id),
    FOREIGN KEY (user_id) REFERENCES account (user_id)
);

Column Constraints

  • NOT NULL: the value cannot be NULL.
  • UNIQUE: values must be unique across the table. In PostgreSQL a column may still hold many NULLs, because each NULL is treated as distinct.
  • PRIMARY KEY: combination of NOT NULL and UNIQUE. One column can use a column-level constraint; multiple columns require a table-level constraint.
  • REFERENCES: the value must exist in a column of another table (foreign key).

Table Constraints

  • UNIQUE (column_list)
  • PRIMARY KEY (column_list)
  • FOREIGN KEY (...) REFERENCES ...

ALTER TABLE

Changes the structure of an existing table. Supported actions include adding, dropping and renaming a column, changing a column's data type, setting a default value, and renaming the table.

-- Add a foreign key that was forgotten
ALTER TABLE account_role
ADD CONSTRAINT constraint_fkey
FOREIGN KEY (user_id) REFERENCES account (user_id);

-- Drop a column
ALTER TABLE account DROP COLUMN email;

DROP TABLE

Removes the table and its data completely.

DROP TABLE [IF EXISTS] table_name [CASCADE | RESTRICT];

TRUNCATE TABLE

Removes all rows quickly. DELETE without a condition is inefficient on large tables.

TRUNCATE TABLE table_name;
TRUNCATE TABLE table_name1, table_name2;  -- several tables at once

Part II: PostgreSQL Data Types

  • Boolean: true, false, NULL (keyword boolean or bool)
  • Character: char, varchar, text
  • Numeric: integers and floating-point numbers
  • Temporal: date, time, timestamp, timestamptz, interval
  • UUID: universally unique identifiers
  • Array: arrays of strings, numbers, etc.
  • JSON: JSON data; hstore: key-value pairs
  • Special types: network addresses, geometric data

Numeric Types

  • Integers: smallint, integer, bigint (plus auto-incrementing serial types).
  • Floating point:
  • float(n): precision at least n, up to 8 bytes
  • real / float4: 4-byte floating-point number; float8: 8-byte
  • numeric(p, s): exact number with p digits, s of them after the decimal point
CREATE TABLE products (
    id    serial PRIMARY KEY,
    price numeric(5, 2)   -- up to 999.99
);

Temporal Types

TypeStores
DATEDate only
TIMETime of day
TIMESTAMPDate and time
TIMESTAMPTZTimestamp with time zone
INTERVALA period of time

Part III: Data Manipulation Language (DML)

The primary DML commands are INSERT, UPDATE and DELETE.

INSERT

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

-- Multiple rows in one statement
INSERT INTO table_name (column_list)
VALUES (value_list_1),
       (value_list_2),
       (value_list_n);

-- Return the inserted rows
INSERT INTO table_name (column_list)
VALUES (...), (...)
RETURNING *;

UPDATE

UPDATE table_name
SET column1 = value1,
    column2 = value2
WHERE condition;

Without WHERE, all rows are updated.

DELETE

DELETE FROM table_name WHERE condition;               -- selected rows
DELETE FROM table_name WHERE condition RETURNING *;   -- return deleted rows
DELETE FROM table_name;                               -- all rows

Conclusion

DDL defines the structure of the database, DML changes its data, and PostgreSQL's rich set of data types and constraints keeps that data valid.