CSwithZain
WhatsApp Join a class

AS Level 9618 · Paper 1 · 8.3

Data Definition Language (DDL) and Data Manipulation Language (DML)

Building and querying a database with SQL. Read the notes, try the past-paper questions, then check the mark scheme.

Past papers from June 2021 to June 202629 questions · 187 marks

    In this subtopic

    • DDL: creating and changing a database and its tables
    • DML: adding, changing and deleting data
    • SELECT queries with criteria, sorting, grouping and joins

    8.3 · 1 of 23Book pages Contents

    SQL, DDL and DML

    Structured Query Language (SQL) is the industry standard language for working with relational databases. SQL is a declarative language: a program says what result it wants, not how to get it. This is the opposite of imperative programming, where a program gives the sequence of steps the computer must follow.

    SQL commands are split into groups. Two of them are in the syllabus:

    • Data Definition Language (DDL) has the commands that define and change a database and its parts, such as tables and relationships: CREATE DATABASE, CREATE TABLE and ALTER TABLE.
    • Data Manipulation Language (DML) has the commands that query the data and maintain it (insert, update and delete records): SELECT, INSERT INTO, UPDATE and DELETE FROM.

    DDL and DML in a DBMS

    • The DBMS carries out all creation and modification of the database structure using its DDL.
    • The DBMS carries out all queries and maintenance of the data using its DML.
    • SQL is the industry standard for both DDL and DML.

    SQL syntax. These rules apply to every SQL statement:

    • Statements are made of keywords such as CREATE, SELECT, INSERT and UPDATE. These are reserved words, so they must not be used as identifiers (the names of tables or fields).
    • Keywords are usually written in capital letters, which makes statements easier to read. However, SQL is not case sensitive.
    • Each statement ends with a semicolon. Some systems do not need it, but it is good practice to always include it.
    • Longer statements are usually written over several lines, which again makes them easier to read.

    For example, this statement selects the members whose surname is Jones:

    SELECT FirstName, LastName, Phone
    FROM Member
    WHERE LastName = 'Jones';

    A set of SQL statements written to do one job is called an SQL script.

    8.3 · 2 of 23Book page Contents

    CREATE DATABASE

    DDL is the part of SQL used to create or change the structure of a database. DDL commands only create the structure: they do not put any data into the database.

    To create a database, the syntax is:

    CREATE DATABASE databasename;

    For example, this creates the database for a sports club:

    CREATE DATABASE SportsClub;

    You cannot create a database with the same name as one that already exists. To create it again, the old version must first be deleted (dropped). Dropping a database deletes all of the data stored in it.

    8.3 · 3 of 23Book page Contents

    CREATE TABLE

    To create a table, the syntax is:

    CREATE TABLE tablename (field1 datatype, field2 datatype, ...);

    Each field definition is separated from the next by a comma. A statement can be written on one line, but it is much easier to read when split over several lines, as below. When you use several lines, do not forget the brackets and commas. Usually the first line has the opening bracket, and the last line has the matching closing bracket and the semicolon.

    This statement sets up the table that stores the details of the sports club members:

    CREATE TABLE Member (
        MemberId  CHAR(6),
        FirstName VARCHAR(30),
        LastName  VARCHAR(30),
        Phone     VARCHAR(15),
        PRIMARY KEY (MemberId));

    For each field you must give the field name and its data type. Some data types also need a length. The primary key is given by the keywords PRIMARY KEY followed by the field name (or names) in brackets.

    Practise this: past-paper questions

    Show 6 more

    8.3 · 4 of 23Book pages Contents

    Naming tables and fields

    As in most programming languages, there are rules about the identifiers that can be used for table and field names:

    • Names must begin with a letter.
    • Names can only contain letters, numbers and underscores.
    • Names cannot be SQL keywords (watch out for ORDER).
    • Names should not include spaces.

    Table names. A table is usually named after the entity it describes, and the name is usually singular, for example Customer, Booking or Appointment. Some developers start table names with tbl, for example tblCustomer, which makes it clear in program code that the name is a table.

    Field names should make their purpose clear, and it is good practice to follow one style. These notes use upper camel case, for example CustomerId.

    Each field should hold only a single item of data, because it is much easier for a computer to combine data than to split it. Instead of one field for a customer’s name, use a first name field and a surname field, and perhaps a title and other names too. Addresses are usually split into house name or number, street, town, county and postcode, often with an extra field for a village or other less common parts. Remember that people’s names often do not follow the pattern first name, space, last name, especially outside the English-speaking world, and addresses in other countries may have a very different format.

    The same field name can be used in different tables. For example, the Member and Instructor tables both have FirstName and LastName fields, and this causes no problem. Where a field name is ambiguous (it appears in more than one table), put the table name and a full stop in front of it in your SQL statements, for example Member.FirstName. This is good practice.

    8.3 · 5 of 23Book page Contents

    SQL data types

    Every field in a table is given one of these SQL data types:

    Data typeDescription
    CHARACTER or CHAR(n)A fixed-length string of n characters
    VARCHAR(n)A variable-length string of at most n characters
    BOOLEANTRUE or FALSE
    INTEGER or INTA whole number, positive or negative
    REALA number with a decimal part
    DATEA date
    TIMEA time, usually written HH:MM:SS

    Choosing a data type

    • An ID made of digits that can start with 0, such as 0123, is a CHAR or VARCHAR, not an INTEGER, because an integer would lose the leading zero.
    • Codes with letters, names and descriptions are CHAR (fixed length) or VARCHAR (length varies).
    • A field that only stores yes or no, or true or false, is a BOOLEAN.
    • Prices and amounts of money are REAL. Counts and quantities are INTEGER.

    Practise this: past-paper questions

    Show 6 more

    8.3 · 6 of 23Book page Contents

    Primary and foreign keys

    A primary key is set with the keywords PRIMARY KEY, followed by the field name in brackets. If the table has a composite primary key, put all of its fields inside the brackets, separated by commas:

    CREATE TABLE Certificate (
        MemberId       CHAR(6),
        CourseCode     CHAR(6),
        AssessmentDate DATE,
        InstructorId   INT,
        PRIMARY KEY (MemberId, CourseCode));

    A foreign key is a field whose values exist as the primary key of another table. It is set with FOREIGN KEY, the field name in brackets, then REFERENCES followed by the other table and its primary key field in brackets. The Certificate table has three foreign keys:

    CREATE TABLE Certificate (
        MemberId       CHAR(6),
        CourseCode     CHAR(6),
        AssessmentDate DATE,
        InstructorId   INT,
        PRIMARY KEY (MemberId, CourseCode),
        FOREIGN KEY (MemberId) REFERENCES Member (MemberId),
        FOREIGN KEY (CourseCode) REFERENCES Course (CourseCode),
        FOREIGN KEY (InstructorId) REFERENCES Instructor (InstructorId));

    Note A foreign key line must always name the table and field it refers to. FOREIGN KEY (MemberId) on its own is an error.

    Practise this: past-paper questions

    Show 8 more

    8.3 · 7 of 23Book page Contents

    Table constraints

    Table constraints are rules that data must follow to be accepted into a table. They are usually set up as part of a CREATE TABLE statement. These are the common ones:

    • NOT NULL makes sure a field cannot be left empty (null).
    • UNIQUE makes sure every value in a field is different.
    • PRIMARY KEY makes sure every record has a value in the field, and that the value is unique.
    • FOREIGN KEY sets up referential integrity: a record with a foreign key value can only be added if a record with the same primary key value exists in the other table. This makes sure the links between related tables are kept.
    • CHECK makes sure the values in a field meet a condition, for example that a field only accepts positive numbers.

    This new definition of the Instructor table uses NOT NULL, so an instructor record cannot be created without a first name and a last name:

    CREATE TABLE Instructor (
        InstructorId INT,
        FirstName    VARCHAR(30) NOT NULL,
        LastName     VARCHAR(30) NOT NULL,
        Email        VARCHAR(30),
        PRIMARY KEY (InstructorId));

    When an exam question asks you to include constraints (restrictions) on the data, NOT NULL on the fields that must always have a value, and the primary key, are the usual answers. The primary key can also be given on the field’s own line, for example StaffID INTEGER NOT NULL PRIMARY KEY,

    8.3 · 8 of 23Book page Contents

    ALTER TABLE

    ALTER TABLE changes the definition of a table that already exists. The most common change is to add a new field: give its name and data type after ADD.

    ALTER TABLE Course
    ADD StartDate DATE;

    More than one field can be added at once, separated by commas (this is the form mark schemes use; some DBMSs need the word ADD before each field):

    ALTER TABLE Member
    ADD DateJoined DATE, Junior BOOLEAN;

    ALTER TABLE can also add a primary key or a foreign key to a table that was created without one:

    ALTER TABLE Certificate
    ADD PRIMARY KEY (MemberId, CourseCode);
    
    ALTER TABLE Certificate
    ADD FOREIGN KEY (MemberId) REFERENCES Member (MemberId);

    8.3 · 9 of 23Book pages Contents

    INSERT INTO

    Users of any database need to add new data, update it to keep it correct, and delete it when it is no longer needed. SQL DML has commands for all three tasks.

    New records are added to a table with INSERT INTO. The syntax is:

    INSERT INTO table (field1, field2, ...)
    VALUES (value1, value2, ...);

    For example, the sports club has a new basketball course. This statement adds it to the Course table:

    INSERT INTO Course (CourseCode, Description, Fee)
    VALUES ('CR7531', 'Basketball', 25);

    When you insert records, the data must follow any constraints set in the table design. Some fields may not be left blank, or may only accept certain values, and a foreign key constraint may mean the DBMS checks another table for a matching primary key value.

    You must also think about data types. Here CourseCode and Description are text fields, so their values go in quote marks. Fee is a number, so it does not.

    More than one record can be added at a time, with a comma between each set of values. The sports club has taken on three more instructors for the basketball course. This statement adds them to the Instructor table:

    INSERT INTO Instructor (InstructorId, FirstName, LastName, Email)
    VALUES (6, 'Bailey', 'Campbell', 'cbailey@example.net'),
           (7, 'Jaden', 'Beckford', 'jaden.beckford@example.edu'),
           (8, 'Jasmine', 'Ansari', 'jansari@example.com');

    If you give a value for every field, in the same order as the fields in the table, the list of field names can be left out:

    INSERT INTO Course
    VALUES ('CR7531', 'Basketball', 25);

    8.3 · 10 of 23Book pages Contents

    UPDATE

    Records are changed with an UPDATE statement. The syntax is:

    UPDATE table
    SET field1 = value1, field2 = value2, ...
    WHERE criteria;

    For example, the sports club has decided to lower the price of one of its courses. This statement changes the fee for Tennis in the Course table from 30 to 25:

    UPDATE Course
    SET Fee = 25
    WHERE Description = 'Tennis';

    Think carefully about the criteria in the WHERE clause. The same result could have been achieved with:

    WHERE CourseCode = 'DG0011';

    If there were two courses with the description Tennis, this version would only change the fee of the course with the code DG0011, not both. Neither method is wrong: it depends on what you want to do. But to update the phone number of Abdel Patel, it would not be wise to use FirstName = 'Abdel' as the criteria, because there may be several members called Abdel and every one of them would get the new number.

    The WHERE clause in an UPDATE statement

    • The WHERE clause is optional, but if it is left out, every record in the table is updated.
    • You can only be sure of updating a single record if you select it by its primary key.
    • In practical work, test the criteria with a SELECT statement before you use them in an UPDATE.

    8.3 · 11 of 23Book page Contents

    DELETE FROM

    Records are deleted from a table with DELETE FROM. The syntax is:

    DELETE FROM table
    WHERE criteria;

    This statement deletes Joe Donald’s record from the Member table:

    DELETE FROM Member
    WHERE MemberId = '131092';

    The record to delete has been chosen by its primary key. If the criteria had been WHERE FirstName = 'Joe' AND LastName = 'Donald', every record that matched would be deleted. As with UPDATE, a DELETE FROM statement with no WHERE clause deletes every record in the table.

    8.3 · 12 of 23Book pages Contents

    The sports club sample data

    The SELECT examples in the rest of 8.3 use this sample data from the sports club database. Primary keys are underlined in a design; here they are the first field of each table, and Certificate has the composite primary key (MemberId, CourseCode).

    Member (MemberId, FirstName, LastName, Phone)

    MemberIdFirstNameLastNamePhone
    012010EmilyMarr01632 961743
    131092JoeDonald01632 960007
    132099AbdelPatel01632 967267
    145543PreciousJones01632 962816
    148765JackMarr01632 961743

    Course (CourseCode, Description, Fee)

    CourseCodeDescriptionFee
    DG0011Tennis30
    CR0001Kayaking100
    DG3002Swimming20
    SO0112Judo L120
    SP8701Judo L230
    CR0020Badminton20
    CR0014Climbing40

    Instructor (InstructorId, FirstName, LastName, Email)

    InstructorIdFirstNameLastNameEmail
    1SueJamessue.james@example.org
    2GretaGeuzeg.geuze@example.com
    3MohammedFranksm.franks@example.com
    4JayLintonJay12@example.net
    5SueRobbinssusan.robbins@example.net

    Certificate (MemberId, CourseCode, AssessmentDate, InstructorId)

    MemberIdCourseCodeAssessmentDateInstructorId
    145543DG001121/02/20191
    012010DG001121/02/20191
    132099DG300201/03/20192
    131092CR000115/04/20193
    132099CR000115/04/20193
    012010CR002015/04/20195
    132099SO011202/06/20194
    145543SO011202/06/20194
    148765SP870111/06/20192
    145543CR001401/07/20195

    Used later in

    8.3 · 13 of 23Book pages Contents

    SELECT ... FROM

    SELECT is used to extract data from a database. At its simplest, the syntax is:

    SELECT field1, field2, ...
    FROM table;

    SELECT is followed by a list of field (attribute) names, and FROM is followed by the name of the table the fields come from. For example:

    SELECT FirstName, LastName, Phone
    FROM Member;

    This gives the result below. The columns are in the order given in the field list, and the field names are the column headings.

    FirstNameLastNamePhone
    EmilyMarr01632 961743
    JoeDonald01632 960007
    AbdelPatel01632 967267
    PreciousJones01632 962816
    JackMarr01632 961743

    Keywords such as SELECT and FROM are written in capitals because it makes statements easier to read, even though SQL is not case sensitive. Put a semicolon at the end of the last line to finish the statement.

    Selecting every field. Instead of listing the fields, you can return every field with SELECT *. The Instructor table has the fields Instructor (InstructorId, FirstName, LastName, Email), and this query returns all of them:

    SELECT *
    FROM Instructor;
    InstructorIdFirstNameLastNameEmail
    1SueJamessue.james@example.org
    2GretaGeuzeg.geuze@example.com
    3MohammedFranksm.franks@example.com
    4JayLintonJay12@example.net
    5SueRobbinssusan.robbins@example.net

    Only use SELECT * when every field is needed. Extra data makes the results harder to work with. For example, when you search for a song on a music streaming service, you do not want to see every field stored about it, such as SongID, SongURL, MusicLabel and ReleasedDate.

    Practise this: past-paper questions

    Show 24 more

    8.3 · 14 of 23Book pages Contents

    Sorting with ORDER BY

    The results of a SELECT statement can be sorted by adding an ORDER BY clause:

    SELECT field1, field2, ...
    FROM table
    ORDER BY field(s) ASC|DESC;
    • Ascending order (ASC): from low to high, A to Z or 1 to 9.
    • Descending order (DESC): from high to low, Z to A or 9 to 1.

    Ascending order is the default, so ASC does not have to be written:

    SELECT MemberId, FirstName, LastName
    FROM Member
    ORDER BY LastName;
    MemberIdFirstNameLastName
    131092JoeDonald
    145543PreciousJones
    012010EmilyMarr
    148765JackMarr
    132099AbdelPatel

    Jack and Emily both have the surname Marr. SQL does not promise any order for records with equal values in the sort field. To be sure of the order, sort on a second field as well: ORDER BY LastName, FirstName puts Emily before Jack. A table can also be sorted by a field that is not in the list of selected fields.

    To sort in descending order, write DESC after the field name. This sorts by FirstName from Z to A:

    SELECT MemberId, FirstName, LastName
    FROM Member
    ORDER BY FirstName DESC;
    MemberIdFirstNameLastName
    145543PreciousJones
    131092JoeDonald
    148765JackMarr
    012010EmilyMarr
    132099AbdelPatel

    Used later in

    8.3 · 15 of 23Book pages Contents

    Choosing records with WHERE

    On a music service you rarely want every song in the database: perhaps only the songs by one artist, or on one album. A WHERE clause filters the records, so only those that meet the criteria are returned:

    SELECT field1, field2, ...
    FROM table
    WHERE selection-criteria;

    For example, a sports club member wants to know which courses cost less than £25:

    SELECT Description, Fee
    FROM Course
    WHERE Fee < 25;
    DescriptionFee
    Swimming20
    Judo L120
    Badminton20

    Think about the data type of each field in the criteria. Fee is stored as a number, so it is compared with a number, without quotes. Text fields need quotation marks:

    SELECT FirstName, LastName, Phone
    FROM Member
    WHERE LastName = 'Marr';
    FirstNameLastNamePhone
    EmilyMarr01632 961743
    JackMarr01632 961743

    The criteria after WHERE can be as complex as needed, and can combine several operators:

    OperatorMeaning
    =Equal to
    >Greater than
    <Less than
    >=Greater than or equal to
    <=Less than or equal to
    <>Not equal to

    For example, this query finds all the members who do not have the surname Marr:

    SELECT *
    FROM Member
    WHERE LastName <> 'Marr';
    MemberIdFirstNameLastNamePhone
    131092JoeDonald01632 960007
    132099AbdelPatel01632 967267
    145543PreciousJones01632 962816

    Practise this: past-paper questions

    Show 18 more

    8.3 · 16 of 23Book page Contents

    AND, OR and NOT

    Criteria can be joined with the logical operators AND, OR and NOT. Brackets can be used to force the order in which they are worked out, or just to make the statement easier to read.

    SELECT *
    FROM Member
    WHERE FirstName = 'Emily'
    AND LastName = 'Marr';
    MemberIdFirstNameLastNamePhone
    012010EmilyMarr01632 961743

    A common mistake is to write:

    WHERE CourseCode = 'DG0011' OR 'CR0001'

    The correct version is:

    WHERE CourseCode = 'DG0011' OR CourseCode = 'CR0001'

    The field name must be repeated in the second part. Without it, the second part is not a comparison at all, so the query gives the wrong records (often only the DG0011 ones) or an error.

    Note Use AND when a record must meet both conditions, and OR when it may meet either. "Members called Emily Marr" needs AND; "courses DG0011 or CR0001" needs OR.

    8.3 · 17 of 23Book page Contents

    LIKE and BETWEEN

    Two more keywords are useful in a WHERE clause:

    KeywordExampleResult on the sample data
    LIKEWHERE CourseCode LIKE 'SO%'SO0112 (Judo L1)
    BETWEENWHERE Fee BETWEEN 30 AND 50Tennis, Judo L2, Climbing

    LIKE matches text against a pattern made with wildcards. Check which wildcard symbols your DBMS uses. The most common are:

    • the percent sign %, which stands for zero, one or more characters
    • the underscore _, which stands for exactly one character

    So LIKE 'SO%' finds every code that starts with SO, and LIKE 'CR00_4' finds CR0014. Microsoft Access uses * instead of %, and mark schemes accept either. LIKE is how you count, for example, the courses whose code starts with CR:

    SELECT COUNT(CourseCode)
    FROM Course
    WHERE CourseCode LIKE 'CR%';

    On the sample data this gives 3 (CR0001, CR0020 and CR0014).

    BETWEEN selects values in a range, and includes both end values: Fee BETWEEN 30 AND 50 gives the courses that cost exactly 30 or exactly 50 as well as anything in between.

    8.3 · 18 of 23Book pages Contents

    Text, numbers and dates in criteria

    Text. A string value in the criteria must always be enclosed in quotation marks. Usually single or double quotes can be used, although single quotes are the standard:

    SELECT FirstName, LastName, Phone
    FROM Member
    WHERE LastName = 'Patel';

    If the string itself contains a quotation mark, it must be escaped by writing it twice. To find O’Brien, write:

    WHERE LastName = 'O''Brien'

    In an exam answer, just use double quotes around the string: WHERE LastName = "O'Brien".

    The text inside the quotation marks can be case sensitive (it depends on the DBMS), so match the case of the stored data exactly. In many systems WHERE LastName = 'jones' will not match a surname entered as Jones.

    Numbers. When data is stored as a number, give the value with no quotes:

    WHERE InstructorId = 3

    Fields for money are stored without a currency symbol. WHERE Fee > £5 gives the error "No such column: £5", because the DBMS thinks £5 is the name of a field. Write WHERE Fee > 5.

    Dates. In exam questions, write a date in the same format as the sample data, between single quotes or between # marks:

    WHERE AssessmentDate > '01/06/2019'
    
    WHERE AssessmentDate <= #31/12/2020#

    Take care with a range of dates. To select the dates in January 2020, write either of these:

    WHERE AssessmentDate >= '01/01/2020'
      AND AssessmentDate <= '31/01/2020'
    
    WHERE AssessmentDate
      BETWEEN '01/01/2020' AND '31/01/2020'

    In the first form, use >= and <=, not > and <, or you will miss the first and last days of the month.

    8.3 · 19 of 23Book pages Contents

    Selecting data from two tables

    Many queries need data from more than one table. The two tables must share a common field: a primary key in one table and the matching foreign key in the other. The syntax is:

    SELECT field1, field2, ...
    FROM table1, table2
    WHERE join-criteria;

    In the query below, each field name starts with its table name. This is not always needed, but it prevents problems with ambiguous field names: for example, Member and Instructor both have FirstName and LastName fields. The join criteria use MemberId, the primary key of Member, and MemberId, the foreign key in Certificate. Both fields are called MemberId, so here the table names are essential.

    SELECT Member.FirstName, Member.LastName,
           Certificate.CourseCode, Certificate.AssessmentDate
    FROM Member, Certificate
    WHERE Member.MemberId = Certificate.MemberId;
    FirstNameLastNameCourseCodeAssessmentDate
    PreciousJonesDG001121/02/2019
    EmilyMarrDG001121/02/2019
    AbdelPatelDG300201/03/2019
    JoeDonaldCR000115/04/2019
    AbdelPatelCR000115/04/2019
    EmilyMarrCR002015/04/2019
    AbdelPatelSO011202/06/2019
    PreciousJonesSO011202/06/2019
    JackMarrSP870111/06/2019
    PreciousJonesCR001401/07/2019

    Note In the syllabus, a query uses at most two tables.

    Practise this: past-paper questions

    Show 11 more

    Used later in

    8.3 · 20 of 23Book pages Contents

    INNER JOIN

    In a query that takes data from more than one table, you must always say how the tables are joined.

    The query in the last section makes what is called an INNER JOIN. It shows the details of every member who has one or more certificates. A member with no certificates would not appear in the results.

    Venn diagram titled Inner join: two overlapping circles labelled table1 and table2, with only the overlap shaded.
    An INNER JOIN returns only the records that match in both tables

    The Venn diagram shows how the tables are combined. Each table holds a set of records, with no repeats because each record has its own primary key. An INNER JOIN gives the intersection of the two sets: only the records that have a match in both tables.

    There is another way to write the same query:

    SELECT field1, field2, ...
    FROM table1
    INNER JOIN table2
    ON join-criteria;
    SELECT Member.FirstName, Member.LastName,
           Certificate.CourseCode, Certificate.AssessmentDate
    FROM Member
    INNER JOIN Certificate
    ON Member.MemberId = Certificate.MemberId;

    Both forms give exactly the same result, and both are accepted in the exam.

    Adding more criteria. Often you also need other selection criteria. This query (in the first form) selects the certificates that were awarded on or after 1 June 2019:

    SELECT Member.FirstName, Member.LastName,
           Certificate.CourseCode, Certificate.AssessmentDate
    FROM Member, Certificate
    WHERE Member.MemberId = Certificate.MemberId
    AND Certificate.AssessmentDate >= '01/06/2019';
    FirstNameLastNameCourseCodeAssessmentDate
    AbdelPatelSO011202/06/2019
    PreciousJonesSO011202/06/2019
    JackMarrSP870111/06/2019
    PreciousJonesCR001401/07/2019

    With INNER JOIN, the join goes after ON and the extra criteria go in a WHERE clause:

    SELECT Member.FirstName, Member.LastName,
           Certificate.CourseCode, Certificate.AssessmentDate
    FROM Member
    INNER JOIN Certificate
    ON Member.MemberId = Certificate.MemberId
    WHERE Certificate.AssessmentDate >= '01/06/2019';

    Practise this: past-paper questions

    Show 11 more

    8.3 · 21 of 23Book page Contents

    SUM, AVG and COUNT

    SQL can do calculations on the selected records. Three functions are in the syllabus:

    • SUM(field) adds up the values in a numeric field.
    • AVG(field) works out the mean of the values in a numeric field.
    • COUNT(field) counts how many records there are.
    SELECT AVG(Fee)
    FROM Course;

    This gives one value: 260 ÷ 7 = 37.14 (to 2 decimal places).

    SELECT SUM(Fee)
    FROM Course;

    This gives 260, the total of all seven course fees.

    Naming the result. A calculated column has no field name of its own. Exam questions often ask for "a suitable field name": give one with AS after the calculation. With a WHERE clause, only the records that meet the criteria are counted:

    SELECT COUNT(CourseCode) AS CheapCourses
    FROM Course
    WHERE Fee < 25;
    CheapCourses
    3

    The functions work on two tables too. This counts the certificates held by Precious Jones:

    SELECT COUNT(Certificate.CourseCode)
           AS Certificates
    FROM Member
    INNER JOIN Certificate
    ON Member.MemberId = Certificate.MemberId
    WHERE Member.FirstName = 'Precious'
    AND Member.LastName = 'Jones';
    Certificates
    3

    SUM or COUNT?

    • Use COUNT for "how many" or "the number of": it counts records.
    • Use SUM for "the total" of a quantity or an amount of money: it adds up the values.
    • SUM of a text field, such as SUM(LastName), is always wrong.

    Practise this: past-paper questions

    Show 20 more

    8.3 · 22 of 23Book page Contents

    GROUP BY

    GROUP BY puts the selected records into groups that have the same value in a field, and then works out SUM, AVG or COUNT once for each group. Use it when a question says "for each" or "of each".

    This query gives the number of certificates awarded for each course:

    SELECT CourseCode, COUNT(MemberId)
    FROM Certificate
    GROUP BY CourseCode;
    CourseCodeCOUNT(MemberId)
    CR00012
    CR00141
    CR00201
    DG00112
    DG30021
    SO01122
    SP87011

    The field you group by is usually also in the SELECT list, so you can see which group each total belongs to. Any other field in the SELECT list should be inside SUM, COUNT or AVG, or be a field that has only one value in each group, such as a member’s name when you group by MemberId (as in the worked example below). Add an ORDER BY clause if the groups must be in a particular order.

    The clauses always go in this order:

    SELECT ...
    FROM ...
    INNER JOIN ... ON ...
    WHERE ...
    GROUP BY ...
    ORDER BY ...;

    Worked example

    Write an SQL script to return the first name and last name of each member and the number of certificates they hold. The result must include a suitable field name for the number of certificates, and be in ascending order of last name.

    1. Step 1
      Select the two name fields and count a field from Certificate, naming the count with AS.
      SELECT Member.FirstName, Member.LastName,
             COUNT(Certificate.CourseCode) AS NumberOfCertificates
    2. Step 2
      The data is in two tables, so join them on the primary key and foreign key pair.
      FROM Member
      INNER JOIN Certificate
      ON Member.MemberId = Certificate.MemberId
    3. Step 3
      The question says "each member", so group by the member’s primary key.
      GROUP BY Member.MemberId
    4. Step 4
      Sort by last name. Emily and Jack are both Marr, so sort by first name as well to fix their order.
      ORDER BY Member.LastName, Member.FirstName;
    5. Step 5
      The result is Joe Donald 1, Precious Jones 3, Emily Marr 2, Jack Marr 1, Abdel Patel 3.
    FirstNameLastNameNumberOfCertificates
    JoeDonald1
    PreciousJones3
    EmilyMarr2
    JackMarr1
    AbdelPatel3

    Practise this: past-paper questions

    Show 5 more

    8.3 · 23 of 23Contents

    Reading and correcting SQL

    Exam questions also give you an SQL script and ask what it does, or ask you to find and correct its errors. Read it one clause at a time and check each line against the syntax in these notes.

    Errors to look for

    • A keyword spelt wrongly, such as CREATE DATA BASE or NONULL (they should be CREATE DATABASE and NOT NULL).
    • A missing comma at the end of a field definition, or a missing bracket.
    • PRIMARY KEY without brackets round the field name.
    • FOREIGN KEY without REFERENCES and the other table and field.
    • SUM used where COUNT is needed, or the other way round.
    • A join condition without table names, such as StudentID = StudentID.
    • OR used where both conditions must be true (AND).
    • A text value without quotation marks.

    Worked example 1. This script should create a Booking table for the sports club, with BookingId as the primary key and MemberId as a foreign key:

    01 CREATE TABLE Booking (
    02     BookingId INTEGER
    03     MemberId CHAR(6),
    04     BookingDate DATE,
    05     PRIMARY KEY BookingId,
    06     FOREIGN KEY (MemberId));

    Worked example 1

    Find the three errors in the script and correct them.

    1. Step 1
      Line 02 has no comma at the end.
      02     BookingId INTEGER,
    2. Step 2
      Line 05 needs brackets round the field name.
      05     PRIMARY KEY (BookingId),
    3. Step 3
      Line 06 must say which table and field the foreign key refers to.
      06     FOREIGN KEY (MemberId) REFERENCES Member (MemberId));

    Worked example 2. This query should return the number of certificates held by the member with the surname Jones:

    SELECT SUM(Certificate.CourseCode) AS Certificates
    FROM Member, Certificate
    WHERE MemberId = MemberId
    OR LastName = Jones;

    Worked example 2

    Find the four errors in the query and correct them.

    1. Step 1
      SUM should be COUNT, because the question asks for the number of certificates.
      SELECT COUNT(Certificate.CourseCode) AS Certificates
    2. Step 2
      The join condition needs the table names.
      WHERE Member.MemberId = Certificate.MemberId
    3. Step 3
      OR should be AND, because both conditions must be true.
      AND Member.LastName = 'Jones';
    4. Step 4
      Jones is text, so it needs quotation marks, as in step 3. The corrected query returns 3 (Precious Jones holds three certificates).

    8.3

    Concepts in 8.3

    Every idea explained in 8.3, and where else in the notes it is used.

    ConceptIn one lineAlso used in
    ALTER TABLEThe DDL statement that changes an existing table, for example to add a field or a key.only here
    ASGives a field or calculation a name (alias) in the results.only here
    AVGWorks out the mean of the values in a numeric field.8.3 GROUP BY
    BETWEENSelects values in a range, including both end values.only here
    COUNTCounts how many records there are.8.3 GROUP BY, 8.3 Reading and correcting SQL
    CREATE DATABASEThe DDL statement that creates a new database.8.3 Reading and correcting SQL
    CREATE TABLEThe DDL statement that defines a new table, its fields, data types and keys.8.3 SQL data types, 8.3 Primary and foreign keys, 8.3 Table constraints
    Data Definition Language (DDL)The SQL commands that create and change the structure of a database.8.3 CREATE DATABASE
    Data Manipulation Language (DML)The SQL commands that query, insert, update and delete data.8.3 INSERT INTO
    DELETE FROMThe DML statement that removes records from a table.only here
    GROUP BYGroups records with the same value so SUM, AVG or COUNT is worked out for each group.only here
    INNER JOINCombines two tables, returning only records that match on the join fields.8.3 Selecting data from two tables
    INSERT INTOThe DML statement that adds new records to a table.only here
    LIKEMatches text against a pattern with wildcards, such as LIKE 'SO%'.only here
    NOT NULLA constraint that stops a field being left empty.8.3 Reading and correcting SQL
    ORDER BYSorts the results in ascending (ASC) or descending (DESC) order.8.3 GROUP BY
    SELECTThe DML statement that returns chosen fields from a table.8.3 SQL, DDL and DML, 8.3 UPDATE, 8.3 The sports club sample data, 8.3 Sorting with ORDER BY, 8.3 Choosing records with WHERE, 8.3 GROUP BY
    SQL data typesCHARACTER, VARCHAR(n), BOOLEAN, INTEGER, REAL, DATE and TIME.only here
    SQL scriptA set of SQL statements written to do one job.8.3 GROUP BY, 8.3 Reading and correcting SQL
    Structured Query Language (SQL)The industry standard language for both DDL and DML in relational databases.8.1 Foreign key, 8.1 Referential integrity, 8.2 The developer interface, 8.2 The query processor, 8.3 CREATE DATABASE, 8.3 Naming tables and fields, 8.3 INSERT INTO, 8.3 SELECT ... FROM, 8.3 Sorting with ORDER BY, 8.3 SUM, AVG and COUNT
    SUMAdds up the values in a numeric field.8.3 GROUP BY, 8.3 Reading and correcting SQL
    table constraintsRules data must follow to be accepted in a table, such as NOT NULL.only here
    UPDATEThe DML statement that changes values in existing records.8.3 SQL, DDL and DML, 8.3 DELETE FROM
    WHERE clauseFilters the records so only those meeting the criteria are used.8.3 UPDATE, 8.3 DELETE FROM, 8.3 AND, OR and NOT, 8.3 LIKE and BETWEEN, 8.3 Selecting data from two tables, 8.3 INNER JOIN, 8.3 SUM, AVG and COUNT
    wildcardA symbol in a pattern: % for any characters, _ for one character.only here

    When you want more than reading

    The notes are the front door. The class is where it clicks.

    Join a class →Ask on WhatsApp