🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › SQL and PostgreSQL Database Development › Lesson 2
TEC-WEB46-04 · Lesson 2 · 13 clock hours · demo

Data Definition Language: Designing and Creating Tables

Objective. Students will create a multi-table database schema using correct DDL statements including CREATE TABLE, data type selection, and column constraints.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

What Is Data Definition Language?

Data Definition Language (DDL) is the subset of SQL that creates, modifies, and removes the structure of a database rather than its data. The three core DDL statements are CREATE, ALTER, and DROP. In PostgreSQL 16, every object you build—tables, indexes, sequences, schemas—begins with DDL. Understanding DDL before writing a single INSERT statement prevents costly redesigns later.

Planning a Schema Before You Type

A schema is the blueprint of your database: which tables exist, what columns each table holds, what data types those columns use, and how tables relate to one another. Before opening psql or pgAdmin, sketch the entities (nouns in your domain), their attributes (columns), and their relationships (foreign keys). For a bookstore you might identify three entities: authors, books, and orders. Mapping these on paper or in a simple diagram catches problems before bad DDL reaches a production server.

Choosing the Right Data Type

PostgreSQL offers a rich type system. Picking the wrong type wastes storage, breaks calculations, or silently corrupts data. Use these as starting defaults:

Avoid using TEXT for everything. It eliminates the type system's ability to catch errors at insertion time.

Writing CREATE TABLE

A `CREATE TABLE` statement names the table, lists columns with their types, and declares constraints inline or as table-level clauses.

```sql

CREATE TABLE authors (

author_id SERIAL PRIMARY KEY,

full_name VARCHAR(120) NOT NULL,

birth_date DATE,

UNIQUE (full_name)

);

```

Key points:

Common Column Constraints

| Constraint | Purpose |

|---|---|

| NOT NULL | Prevents NULL from being stored in the column |

| UNIQUE | Guarantees no two rows share the same value |

| DEFAULT | Supplies a value when none is provided on INSERT |

| CHECK | Rejects rows where a Boolean expression is false |

| PRIMARY KEY | Uniquely identifies each row; combines UNIQUE + NOT NULL |

| FOREIGN KEY | Enforces referential integrity between tables |

```sql

CREATE TABLE books (

book_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

title VARCHAR(255) NOT NULL,

price NUMERIC(10,2) NOT NULL CHECK (price >= 0),

published DATE NOT NULL,

author_id INTEGER NOT NULL

REFERENCES authors(author_id)

ON DELETE RESTRICT

);

```

`ON DELETE RESTRICT` prevents deleting an author who still has books, protecting referential integrity.

Modifying and Removing Tables

`ALTER TABLE` changes an existing table's structure without dropping it:

```sql

ALTER TABLE books ADD COLUMN in_stock BOOLEAN NOT NULL DEFAULT TRUE;

ALTER TABLE books ALTER COLUMN title TYPE TEXT;

ALTER TABLE books DROP COLUMN in_stock;

```

`DROP TABLE` permanently removes a table and all its data:

```sql

DROP TABLE books; -- fails if another table references it

DROP TABLE books CASCADE; -- also drops dependent objects

```

Use `CASCADE` with caution. In a shared or production environment, dropping a table is irreversible unless a backup exists. Always verify you are connected to the correct database before executing DROP.

Verifying Your Schema

In psql, `\d tablename` displays columns, types, and constraints. You can also query the information schema, which is portable across SQL databases:

```sql

SELECT column_name, data_type, is_nullable

FROM information_schema.columns

WHERE table_name = 'books';

```

Compare this output against your specification before submitting any DDL script. Automated grading in this course checks `\d` output directly.

Safety Practices for Database Work

DDL statements execute immediately and cannot be rolled back by default in many workflows. Follow these practices:

1. Work in a development or test database until the schema is verified. Never build new schemas directly against production data.

2. Use transactions where supported: wrap DDL in `BEGIN; … COMMIT;` so you can `ROLLBACK` if something goes wrong within the same session.

3. Keep DDL scripts in version control (Git). Treat schema changes like code changes—review before applying.

4. Back up before DROP or destructive ALTER. In a professional environment, confirm a current backup exists before any destructive DDL.

These habits form the professional baseline expected in every workplace that handles database infrastructure.

Key terms10

DDL (Data Definition Language)The subset of SQL statements—CREATE, ALTER, DROP—that define or modify the structure of database objects rather than the data they contain.
SchemaThe overall structural blueprint of a database, describing tables, columns, data types, constraints, and relationships.
Primary KeyA column or combination of columns that uniquely identifies every row in a table; PostgreSQL enforces NOT NULL and UNIQUE automatically.
Foreign KeyA column whose values must match an existing value in a referenced table's primary key, enforcing referential integrity between tables.
NUMERIC(precision, scale)A PostgreSQL data type that stores exact decimal numbers; precision is the total number of significant digits, scale is digits after the decimal point.
TIMESTAMPTZA PostgreSQL data type that stores a date and time along with time-zone information, internally normalized to UTC.
CHECK ConstraintA column or table constraint that rejects any row where a specified Boolean expression evaluates to false, enforcing business rules at the database level.
information_schemaA set of read-only views defined by the SQL standard that describe the structure of the current database, including tables, columns, and constraints.
JSONBA PostgreSQL data type that stores JSON data in a decomposed binary format, enabling efficient indexing and querying of semi-structured data.
CASCADEAn option on DROP TABLE or a foreign key action that automatically extends a destructive operation to dependent objects or rows.
In class: Instructor live-codes a bookstore database schema; students follow along in psql, then independently recreate the schema from memory and compare output of \\d tablename against a reference. · Students select appropriate PostgreSQL data types (INTEGER, NUMERIC, VARCHAR, TEXT, BOOLEAN, DATE, TIMESTAMPTZ, UUID, JSONB) for 20 described columns on a worksheet, justifying each choice. · Students write DDL scripts to CREATE, ALTER, and DROP tables for a provided entity list, adding NOT NULL, UNIQUE, DEFAULT, CHECK, PRIMARY KEY, and FOREIGN KEY constraints, then verify schema correctness using information_schema queries.
Materials: PostgreSQL 16 Documentation (Data Types chapter, DDL chapter), psql, pgAdmin, VS Code with SQLTools extension, constraint worksheet, instructor schema reference script
Check: Students submit a .sql DDL script that executes without errors and matches a provided schema specification; pass = schema creates all tables with all required constraints, verified by automated \d output comparison.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Database fundamentals / data type selection
1. A bookstore table must store the retail price of a book so that arithmetic totals are always exact to the cent. Which PostgreSQL data type is the best choice?
DDL statements
2. Which DDL statement is used to add a new column to an existing PostgreSQL table without destroying the table's data?
DDL statements / referential integrity
3. A developer runs DROP TABLE orders CASCADE; in PostgreSQL. What additional effect does CASCADE have beyond removing the orders table?
Column constraints / DDL behavior
4. A column defined as NOT NULL with a DEFAULT value of 0 receives an INSERT statement that omits that column entirely. What value is stored?
PostgreSQL tooling / schema inspection
5. Which psql meta-command displays the column names, data types, and constraints for a specific table?
Foreign key constraints / referential integrity
6. A books table has a FOREIGN KEY on author_id that references authors(author_id) ON DELETE RESTRICT. An attempt is made to delete a row from authors that is referenced by three rows in books. What happens?
Data type selection / distributed systems concepts
7. A developer needs a primary key column whose values must be globally unique across multiple distributed systems, not just within a single database. Which data type is most appropriate?
Column constraints / data integrity
8. A table named products is created with the constraint CHECK (price >= 0). A developer tries to insert a row with price = -5.00. What is the result?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.