September 28, 2022
When designing a table, consider the following steps:
A field should not contain several values of the same type of data
A table should not have multiple fields with the same data
Make the fields atomic, which means that they are the smallest piece of data that can’t or shouldn’t be divided further
Our tables are considered to be in first normal form (1NF) if both the following are true about the table:
However, we often can’t do a database with a single table. Often, when we normalize our initial table, additional table creation will be required
The DDL category of SQL statements offer the capability of creating, altering, and dropping (deleting) tables. ::::{.left} * CREATE TABLE - creates tables * ALTER TABLE - alters existing tables * DROP TABLE - removes an existing table ::::
CREATE TABLE tablename (
fieldname1 datatype constraints,
fieldname2 datatype constraints,
fieldname3 datatype constraints
)
CREATE TABLE tasks (
task_id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
start_date DATE,
due_date DATE,
status TINYINT NOT NULL,
priority TINYINT NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
Indicates that the field can be used as a unique identifer for rows in the table (automatically unique and not null)
Specifies that the value of a field must match the values appearing in some row of another table. This is how we can provide referential integrity between two related tables.
CREATE TABLE checklists (
todo_id INT AUTO_INCREMENT,
task_id INT,
todo VARCHAR(255) NOT NULL,
is_completed BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (todo_id , task_id),
FOREIGN KEY (task_id)
REFERENCES tasks (task_id)
ON UPDATE RESTRICT ON DELETE CASCADE
);
Makes certain value satisfies a boolean expression (must be true)
CREATE TABLE products (
id serial PRIMARY KEY,
name text,
price numeric CHECK (price > 0)
);
Specifies that the field may not contain a null value (a value must be specified for the field)
CREATE TABLE products (
id serial PRIMARY KEY,
name text NOT NULL,
price numeric CHECK (price > 0 )
);
Ensures that the data contained in the field is unique amongst all rows in the table
CREATE TABLE users (
id serial PRIMARY KEY,
username NOT NULL UNIQUE,
password NOT NULL
);