S22 · Computer Studies II · Grade 11 · ages 16–17
SQL
Structured Query Language
Grade 11 · 3.4 Structured Query Language (SQL)CBE strandFree · works offline
▶ Start the interactive lessonThe full lesson adds narration, an interactive mission and a 10-question bank, and the quiz explains any mistakes.
What SQL is
SQL (Structured Query Language) is the standard language for working with relational databases. Many DBMSs use it, each with small differences: MySQL, PostgreSQL, SQLite, Oracle and Microsoft SQL Server. SQL statements are grouped by job: DDL defines structure, DML changes data, and DQL asks questions.
DDL: defining structure
CREATE TABLE students (adm INT PRIMARY KEY, name VARCHAR(50), grade INT); builds a new table. ALTER TABLE changes it, for example to add a column. DROP TABLE deletes a whole table and all its data. Use DROP with great care: there is no undo.
DML: changing data
INSERT INTO students VALUES (1021, 'Amani', 11); adds a row. UPDATE students SET grade = 12 WHERE adm = 1021; changes matching rows. DELETE FROM students WHERE adm = 1021; removes them. Always include WHERE with UPDATE and DELETE; without it, every row changes or disappears.
DQL: asking questions
SELECT name, grade FROM students; lists those columns for every row. SELECT * picks all columns. WHERE filters rows (WHERE grade = 11), ORDER BY sorts (ORDER BY name), and GROUP BY groups rows for summaries, such as SELECT grade, COUNT(*) FROM students GROUP BY grade; which counts the students in each grade.
Relationships in SQL
A FOREIGN KEY constraint links tables, so the database refuses a student whose class_id doesn't exist. A JOIN combines related tables in one query: SELECT students.name, classes.teacher FROM students JOIN classes ON students.class_id = classes.id; shows each student with their class teacher.
Key points
- SQL is the standard language for relational databases.
- DDL defines structure: create, alter and drop.
- DML changes data: insert, update and delete.
- DQL asks questions with select.
- Always use where with update and delete, or every row is affected.
- order by sorts results; group by makes summaries like counts.
- A join combines related tables in one query.
Try it for real: Query a database
- If you can, open a free online SQL editor (search for "SQLite online"), create a students table, insert five students, and select those in grade 11.
- Write a query that counts how many students are in each grade.