CIE AS & A Level Computer Science, section 8.3 (Data Definition Language (DDL) and Data Manipulation Language (DML))
DDL and DML
- Data Definition Language (DDL) is used to create and change the structure of the database (databases, tables, keys).
- Data Manipulation Language (DML) is used to query and change the data in the tables.
Both are part of Structured Query Language (SQL), the industry standard.
Creating a database and tables
CREATE DATABASE Library;
CREATE TABLE Member (
MemberID INTEGER,
Name VARCHAR(30),
Year INTEGER,
PRIMARY KEY (MemberID)
);
CREATE TABLE Loan (
LoanID INTEGER,
MemberID INTEGER,
BookID INTEGER,
DateOut DATE,
PRIMARY KEY (LoanID),
FOREIGN KEY (MemberID) REFERENCES Member(MemberID)
);
Data types
| Type | Used for |
|---|---|
CHARACTER |
a single character (or fixed length text) |
VARCHAR(n) |
variable-length text of up to characters |
BOOLEAN |
TRUE or FALSE |
INTEGER |
whole numbers |
REAL |
numbers with decimals |
DATE |
a date |
TIME |
a time |
Changing a table
ALTER TABLE Member ADD Email VARCHAR(50);
ALTER TABLE Member ADD PRIMARY KEY (MemberID);
ALTER TABLE Loan ADD FOREIGN KEY (BookID) REFERENCES Book(BookID);
Notes
- Statements end with a semicolon.
- A foreign key refers to the primary key of another table, which must already exist.
- Choose data types to suit the data: a name as
VARCHAR, a price asREAL, a date asDATE.
Common mistake: creating a table that refers to another table before that table exists. Create the referenced table first. Also, use VARCHAR(n) (text) for postcodes and phone numbers, not INTEGER, because leading zeros matter.
Exam tip: write the statement carefully: CREATE TABLE, each field with a type, then PRIMARY KEY (field) and FOREIGN KEY (field) REFERENCES Table(field). Check brackets and commas.
Check yourself
What does DDL stand for and what is it used for?
Data Definition Language, used to create and change the structure of the database.
Which SQL data type would you use for a price?
REAL.
Write the SQL to add a column Email of up to 50 characters to a table Member.
ALTER TABLE Member ADD Email VARCHAR(50);