UNIT 2 • MODULE 3 • LESSON 12
In Lesson 11 you split the mas band’s orders into three linked tables. Now you will talk to them. SQL (Structured Query Language) is the language every relational DBMS understands, from MySQL on a website to SQL Server in a bank. You tell the database what you want, not how to find it, which is why SQL is a declarative language (recap: Programming Paradigms Compared). This lesson covers the five kinds of statement in the syllabus, then how a real application connects to a database.
What you will learn
- How to write SELECT, INSERT, UPDATE and DELETE statements.
- How an INNER JOIN combines rows from two tables using a primary key and a foreign key.
- The difference between a query string built in an application and a stored procedure.
- How an application connects to a database, directly or through a web service.
Part 1: The database
All examples use the mas band database from Lesson 11 (simplified):
Masquerader(MasID, FirstName, LastName, Phone) Section(SectionCode, SectionName, Price) CostumeOrder(OrderNo, MasID, SectionCode, Size)
Part 2: SELECT
SELECT reads data. The general shape is:
SELECT column1, column2 FROM table WHERE condition ORDER BY column;
SELECT *means every column.WHEREkeeps only rows that match. Conditions use=,<>(not equal),<,>,<=,>=, and can be joined withANDorOR. Text values go in single quotes; numbers do not.ORDER BYsorts the result, ascending by default orDESCfor descending.
SELECT SectionName, Price FROM Section WHERE Price > 700 ORDER BY Price DESC;
This returns Wings (1200) then Jewel (950).
Part 3: INSERT, UPDATE and DELETE
INSERT INTO Section
(SectionCode, SectionName, Price)
VALUES ('FR', 'Fire', 800);
UPDATE Section
SET Price = 1000
WHERE SectionCode = 'JW';
DELETE FROM CostumeOrder
WHERE OrderNo = 1005;
Always give UPDATE and DELETE a WHERE clause. Without one, every row is changed or deleted. Most DBMSs will also refuse an INSERT whose primary key already exists, or whose foreign key does not match (referential integrity).
Part 4: INNER JOIN
The data you want is often spread across tables. An INNER JOIN pairs each row of one table with the rows of another where a condition is true, usually where the foreign key equals the primary key. Rows with no match are left out.
SELECT FirstName, SectionName FROM CostumeOrder INNER JOIN Masquerader ON CostumeOrder.MasID = Masquerader.MasID INNER JOIN Section ON CostumeOrder.SectionCode = Section.SectionCode WHERE Size = 'M';
Read it from the middle out: start with the orders, attach the masquerader whose MasID matches, attach the section whose code matches, then keep the size M rows. When a column name is in both tables, write it as Table.Column.
A method for any join question
- List the columns the question wants, and which table each is in.
- List the columns needed for the condition, and their tables.
- Start FROM one table and INNER JOIN each other table ON its primary key = the matching foreign key.
- Add WHERE for the condition, and ORDER BY if a sort is asked for.
Part 5: SQL lab
Type SQL into the box and press Run. The lab supports SELECT (with INNER JOIN, WHERE with AND, and ORDER BY), INSERT, UPDATE and DELETE on the three tables shown below the box. Complete the five tasks; they tick off automatically.
Try it 1SQL lab: the mas band database
Tables now
Part 6: Query strings and stored procedures
An application can send SQL to the DBMS in two ways.
A query string built in the application
The program glues the SQL together as text, including values the user typed, and sends the whole string. Here is a C sketch that only builds and prints the string; no database library or server is needed:
#include <stdio.h>
static void show(const char *name)
{
char q[160];
snprintf(q, sizeof q,
"SELECT Phone\nFROM Masquerader\n"
"WHERE LastName = '%s';", name);
printf("%s\n\n", q);
}
int main(void)
{
show("Ali");
show("x' OR '1' = '1");
return 0;
}
Output:
SELECT Phone FROM Masquerader WHERE LastName = 'Ali'; SELECT Phone FROM Masquerader WHERE LastName = 'x' OR '1' = '1';
The second call shows the danger. A user typed a name containing a quote and some SQL, and the query now matches every row. This is SQL injection, one of the most common ways websites are attacked. Query strings are quick to write but must never paste raw user input; parameterised queries, where the driver sends values separately from the SQL, avoid the problem.
A stored procedure
A stored procedure is a named block of SQL saved inside the database itself. The application calls it by name and passes parameters:
CREATE PROCEDURE PhoneByName
(IN pName VARCHAR(40))
BEGIN
SELECT Phone FROM Masquerader
WHERE LastName = pName;
END
CALL PhoneByName('Ali');
| Query string in the app | Stored procedure | |
| Where the SQL lives | In the application code | In the database |
| Security | Risk of SQL injection if input is pasted in; app needs rights on the tables | Parameters are values, not code; users can be given rights to run the procedure only |
| Speed | SQL is sent and checked each time | Stored and often pre-compiled by the DBMS; less network traffic |
| Maintenance | Change means updating and redeploying every app | Change once in the database; every app benefits |
| Flexibility and portability | Easy to build any query; standard SQL works on many DBMSs | Written in the DBMS’s own dialect, so harder to move between MySQL and SQL Server |
Part 7: Connecting an application to a database
A program in C, Java, Python or PHP does not read the database files itself. It goes through the DBMS:
- Driver or connector: a library that speaks the DBMS’s network protocol, such as MySQL Connector, ODBC or JDBC.
- Connection string: says which server, which database, and the user account to use. Credentials are kept in a protected settings file, never written into code that others can see.
- Open, query, read, close: the program opens a connection, sends a query or CALL, reads the rows of the result set one by one, and closes the connection.
Web services
App or web page | 1 request (e.g. HTTPS) v Web service / API | 2 connect with a driver | and run SQL or CALL v DBMS (MySQL, SQL Server) | 3 result set v Web service -> JSON -> App
Phone apps and web pages usually do not connect to the database directly. They send an HTTPS request to a web service (an API) on a server. The web service checks the request, runs the SQL or stored procedure, and sends back the results, often as JSON text. This keeps the database hidden behind a firewall, lets many kinds of client share one database, and means database passwords never leave the server.
Internal Assessment note: if your Unit 2 project stores data, a small relational schema with keys, a few well-tested SQL statements and a clear note on how your program connects to the database is a strong design section.
Part 8: Common mistakes
- Missing quotes or extra quotes. Text values need single quotes:
'Ali'. Numbers do not:1005. - Forgetting the join condition. Without
ON, every row pairs with every other row. - Ambiguous columns. Write
Masquerader.MasIDwhen two joined tables both have MasID. - UPDATE or DELETE without WHERE. Every row is affected.
- Using a column from a table you did not join. Every table you use must appear in FROM or INNER JOIN.
Try it 2SQL drill
Pick a mode. "Clause" asks for the missing keyword. "Rows" asks how many rows a query returns from the lab’s starting data.
Summary
| Statement | Pattern |
| SELECT | SELECT cols FROM t WHERE cond ORDER BY col; |
| INSERT | INSERT INTO t (cols) VALUES (vals); |
| UPDATE | UPDATE t SET col = val WHERE cond; |
| DELETE | DELETE FROM t WHERE cond; |
| INNER JOIN | FROM a INNER JOIN b ON a.fk = b.pk |
| Query string | SQL built in the app; watch for injection. |
| Stored procedure | Named SQL in the database, called with parameters. |
| Web service | App sends HTTPS request; server runs SQL and returns JSON. |
Review questions
1. Write SQL to list the names and prices of all sections, cheapest first.
Show answer
SELECT SectionName, Price FROM Section ORDER BY Price;
2. Write SQL to add masquerader M05, Aaliyah Mohammed, phone 868-555-0111.
Show answer
INSERT INTO Masquerader (MasID, FirstName, LastName, Phone) VALUES ('M05', 'Aaliyah', 'Mohammed', '868-555-0111');
3. Write SQL to change order 1004 to size M.
Show answer
UPDATE CostumeOrder SET Size = 'M' WHERE OrderNo = 1004;
4. Write SQL to list the order number and last name for every order in the Sailor section (code SL).
Show answer
SELECT OrderNo, LastName FROM CostumeOrder INNER JOIN Masquerader ON CostumeOrder.MasID = Masquerader.MasID WHERE SectionCode = 'SL';
5. What does an INNER JOIN leave out?
Show answer
Rows in either table that have no matching row in the other, according to the ON condition.
6. Give two advantages of stored procedures over query strings built in an application.
Show answer
Better security (parameters prevent injection; users can run the procedure without table rights); less network traffic and often faster; change once in the database for every app.
7. What is SQL injection?
Show answer
An attack where input containing SQL is pasted into a query string so that it changes the meaning of the query, for example to return or delete every row.
8. Why do mobile apps usually reach a database through a web service?
Show answer
The database stays hidden behind a firewall; passwords stay on the server; the service can check every request; many different clients can share one interface.
Homework
- Complete all five lab tasks without using "Show a model answer".
- Write a query that lists each masquerader’s first name with the price of each costume they ordered (two joins).
- Rewrite one of your queries as a stored procedure with a parameter.
- Draw the path of a "show my orders" request from a phone app to the database and back, labelling each step.
Mastery quiz: SQL and Connecting to a Database
This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.
Mastery quiz: Writing SQL and Connecting an Application to a Database
Your course badges: loading saved progress…
View badges
No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.
Saved in this browser on this device. Clearing browser data may remove your badges.
Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.
Exam tips
Specimen Unit 2 Paper 02 (2021), Question 6(c). You are given a three-table schema and asked for a query that returns some people’s details based on a value stored in another table. Method: use the join method in Part 4. Find which table holds the columns to output and which holds the condition; join them through the linking table on primary key = foreign key; put the condition in WHERE with the text value in single quotes. Practise with the lab database: "the first and last names of everyone who ordered a Jewel costume" needs Masquerader joined to CostumeOrder with WHERE SectionCode = 'JW'.
Marks for SQL. Examiners look for the right columns, every needed table joined on the correct keys, and a correct condition. Write each clause on its own line so a small slip does not hide the rest of your answer.
More worked answers are on the CS Solutions page.
Previous: Unit 2 • Module 3 • Lesson 11 – Flat Files, Relational Databases and Keys. Next: this is the last lesson in the CAPE Computer Science course. Return to the CAPE CS Lesson List or the CAPE Computer Science course page. A Curriculum Map page is coming soon.
Syllabus link: CAPE Computer Science (CXC A19/U2/21), Operating Systems and Computer Networks (Unit 2, Module 3). Specific Objective 6: explain how data storage and retrieval have changed over time (simple SQL: SELECT, INSERT, inner join, UPDATE, DELETE; query strings versus stored procedures; connecting an application to a database, including web services).
Video search terms
Search YouTube for: "SQL inner join explained", "stored procedure vs query", "SQL injection explained simply".
Try it 3Quick quiz
Tap an answer. All eight questions are self-checks on this lesson.
Updates
2026/12/01
- First version of the lesson.
© 2026 islandclass.org
