Database Systems

SQL

SQL

Table of Contents

SQL

Table creation

CREATE TABLE Account (
    AccountID smallint auto_increment, # surrogate key: DB auto-increments
    AccountName varchar(100), NOT NULL, # mandatory value
    OutstandingBalance DECIMAL(10, 2) NOT NULL,
    CustomerID smallint NOT NULL, 
    AccountType enum('Personal', 'Company') NOT NULL, # enumerations
    PRIMARY KEY (CustomerID),   # specify primary key
    FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID) # specify foreign key
                     ON DELETE RESTRICT
                     ON UPDATE CASCADE
);

Insertion

Selection

MySQL style SELECT selected keywords

SELECT [ALL | DISTINCT] select_expr [, select_expr ...]

[WHERE where_condition]

[GROUP BY col_name | expr } [ASC | DESC], ...]

[HAVING where_condition ]

[ORDER BY col_name | expr | position } [ASC | DESC], ...]

[LIMIT offset ,] row_count | row_count OFFSET offset}]

Aggregation

e.g. count customers

SELECT COUNT(CustomerID)
FROM Customer;

e.g. average balance per customer

SELECT AVG(OutstandingBalance)
FROM Account
GROUP BY CustomerID;

Group by, having

Joins


Edit this page.