You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Beyond querying data with SELECT, SQL provides statements to modify data and define table structures. These are part of the Data Manipulation Language (DML) and Data Definition Language (DDL).
DDL statements define the structure of the database. The most important DDL statement at A-Level is CREATE TABLE.
CREATE TABLE TableName (
Column1 DataType CONSTRAINT,
Column2 DataType CONSTRAINT,
...
PRIMARY KEY (Column1)
);
CREATE TABLE Students (
StudentID INTEGER PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
Surname VARCHAR(50) NOT NULL,
DateOfBirth DATE,
Email VARCHAR(100) UNIQUE,
FormGroup VARCHAR(5)
);
| Data Type | Description |
|---|---|
| INTEGER / INT | Whole numbers |
| VARCHAR(n) | Variable-length text up to n characters |
| CHAR(n) | Fixed-length text of exactly n characters |
| DATE | Date value (YYYY-MM-DD) |
| FLOAT / REAL | Decimal numbers |
| BOOLEAN | TRUE or FALSE |
| TEXT | Large text blocks |
| Constraint | Effect |
|---|---|
| PRIMARY KEY | Uniquely identifies each row; cannot be NULL |
| NOT NULL | The field must contain a value |
| UNIQUE | No two rows can have the same value in this field |
| FOREIGN KEY | References the primary key of another table |
| DEFAULT | Sets a default value if none is provided |
| CHECK | Validates data against a condition |
CREATE TABLE Grades (
GradeID INTEGER PRIMARY KEY,
StudentID INTEGER NOT NULL,
Subject VARCHAR(50) NOT NULL,
Score INTEGER CHECK (Score >= 0 AND Score <= 100),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);
INSERT INTO Students (StudentID, FirstName, Surname, DateOfBirth, Email, FormGroup)
VALUES (1004, 'David', 'Williams', '2007-11-05', 'david@school.com', '10A');
Key points:
Inserting multiple rows:
INSERT INTO Students (StudentID, FirstName, Surname, DateOfBirth, FormGroup)
VALUES
(1005, 'Eve', 'Brown', '2007-06-20', '10B'),
(1006, 'Frank', 'Taylor', '2008-02-14', '10A');
UPDATE Students
SET FormGroup = '10C'
WHERE StudentID = 1004;
Key points:
UPDATE Students
SET Email = 'david.w@school.com', FormGroup = '10B'
WHERE StudentID = 1004;
Dangerous — updating all rows:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.