A-Level Computer Science / Unit 8: Relational Databases and SQL

8.2.3 SQL DDL: Create Databases and Tables

πŸ”’ Lesson slides are available to signed-in users. Sign in

8.2.3 SQL DDL: Create Databases and Tables

Data Definition Language (DDL) creates or changes database structures. CREATE DATABASE and CREATE TABLE are SQL DDL commands.

By the end of this page, you should be able to:

  • define and use the key terms accurately;
  • explain how the idea works using a new example;
  • apply the idea to a database design or SQL task.

1. DDL changes structure

DDL defines database structures such as databases, tables and constraints. SQL is used for both DDL and DML. In this lesson, CREATE statements define where data will be stored and the fields it will contain.

2. Create a database

CREATE DATABASE followed by a name asks the DBMS to create a database. The next steps depend on the DBMS: the user may need to select that database before creating tables inside it.

3. Define fields with suitable types

CREATE TABLE names a table and lists its fields with data types. The syllabus types include CHARACTER, VARCHAR(n), BOOLEAN, INTEGER, REAL, DATE and TIME. Pick the type based on the values and operations required.

4. Declare a primary key

A primary key constraint identifies the field or combination that must be unique for each row. A composite key lists multiple fields together. Make sure the key reflects the intended unique record, not a value that can be shared.

Worked example

A workshop records: SessionID as INTEGER, Topic as VARCHAR(50), IsOnline as BOOLEAN, SessionDate as DATE, StartTime as TIME. SessionID can be declared the primary key.

Common mistake to avoid

Do not choose INTEGER for a value that needs leading zeroes or is not used in arithmetic, such as a postcode. Such a code is usually text.

Interactive check

Choose an answer, read the explanation, and continue to the next example.

Try it

Check your understanding

Question 1 of 3
Score: 0 / 3

Independent practice

Try this original question before opening the suggested response.

Write SQL to create database GardenLog and a Plant table with PlantID (INTEGER primary key), PlantName (VARCHAR(45)) and DateAdded (DATE). (5)

Suggested response
CREATE DATABASE GardenLog;

CREATE TABLE Plant (
  PlantID INTEGER,
  PlantName VARCHAR(45),
  DateAdded DATE,
  PRIMARY KEY (PlantID)
);

Answering clearly

Use the technical term, state what it does, and connect your explanation to the details in the question.