3.7.2 Structured Query Langauage (SQL)

Table of Contents

Fork me on GitHub

3.7.2_SQL_Main.png

1 Using SQL to Query a Relational Database

Learn It

  • Structured Query Language (SQL) is a language that was developed as a method for creating, selecting, inserting, editing(updating) and deleting tables, records and fields within a relational database.
  • Using SQL we can perform various operations on data in out database tables.
  • We can, for instance, SELECT, INSERT, DELETE and UPDATE tables, records and fields.
  • SQL is a standardized query language for requesting information from a database.
  • Query is another word for questioning the Database using search criteria.
  • The Customer, Orders and Books tables in the BookStore database will be used to demonstrate the main SQL statements.
  • The most commonly used SQL statements include:
    • SELECT
      • FROM
      • WHERE
      • ORDER BY
    • INSERT
    • UPDATE
    • DELETE

2 SQL Syntax - SELECT

Learn It: SELECT .. FROM .. WHERE

  • The SELECT statement is used to retrieve(Extract) a collection of fields from one or more tables in a database.
  • The syntax is:
  • SELECT will retrieve data(List of Fields) from one or more tables.
  • SELECT has optional keywords such as:
    • FROM to list the table(s) where the data is to be retrieved from.
    • WHERE to allow selection of data using search criteria.
    • ORDER BY lists the column(fields) that the results are to be sorted on, either Ascending or Descending(default is Ascending).
  • The asterisk (*) is also important in writing SQL statements, indicating that all columns(Fields) should be selected.

Learn It: Retrieving Data from a Relational Database

  • EXAMPLE 1: Let's look at our Customer table example.
*CustID Title Initial Surname Address City Phone DoB
C001 Mrs C Flowers 23 Rose Ave Bourne 01778 123456 01/11/69
C002 Mr J Eames 100 Dowe Rd Bourne 01778 654321 23/09/87
C003 Mr H Gull 34 High St Bourne 01778 657231 30/07/99
C004 Ms P Jones 89 Knight St Bourne 01778 856021 10/10/56
  • A valid SQL statement to select All People in the Customer table who was born between 01/01/1960 and 01/01/2000 and displaying the results in descending order of Surname would be:
SELECT *
       FROM Customer
       WHERE DoB BETWEEN #01/01/1960# AND #01/01/2000#
       ORDER BY Surname DESC;
  • This SQL query will return the following records:

3.7.2_DB_SQL1.png

  • EXAMPLE 2: In this example we will use the Books table to select BookID, Title, Genre, Rating and PublishDate with a rating of 5 or above or with a publish date after 1970 and displaying the results in ascending order of Title would be:
*BookID Title Author Genre PublishDate Rating
B123 Charlotte's Web E. B. White Fiction 01/01/1952 5
B456 David Copperfield Charles Dickens Fiction 10/12/1850 5
B789 How To: Randall Munroe Fiction 20/08/2019 4
C123 The Way of the Peaceful Warrior Dan Millman Spiritual 01/09/2000 5
SELECT BookID, Title, Genre, Rating, PublishDate
       FROM Books
       WHERE Rating > 5 OR PublishDate >= #01/01/1970#
       ORDER BY Title ASC;
  • This SQL query will return the following records:

3.7.2_DB_SQL2.png

Standard SQL Operators

  • The standard operators used in SQL are shown below.
Operator Function Example
= Equal to Title = "Mr"
<> Not equal to Title <> "Ms"
< Less than Rating < 5
> Greater than Rating > 2
<= Less than or equal to DoB <= #01/01/1970#
>= Greater than or equal to DoB >= #01/01/2000#
IN Equal to a value within a set of values Genre IN ("Fiction", "Non-Fiction" , "Spiritual")
BETWEEN …AND Within a range, including the two values which define the limits DoB BETWEEN #01/01/2018# AND #31/12/2019#
IS NULL Field does not contain a value DoB IS NULL
NOT Inverts truth Genre NOT IN ("Fiction", "Spiritual")
AND Both expressions must be true for the expression to be true Title = "Mr" AND DoB > #01/01/2000#
OR If either or both expressions ate true, then the expression is true Title = "Mrs" OR City = "Bourne"

Try It: SQL Zoo - SELECT

  • Try practising your SQL skills by working through the following SQL Select Stages 0 to 7:

Badge It: Structured Query Langauge (SQL) - Simple SQL Query

Silver: Carry out the following instructions:

  1. Write an SQL query to find the names and dates of birth of all people born on or before 1st January 1970. = (Hint: Use the <= operator)
  2. Draw a table to show the query results. Remember to display all fields in the records that satisfy the query criteria, use an asterisk(*) instead of specifying each field.
  • Upload to 3.7.2 Structured Query Language (SQL) - Simple SQL Statement: Silver on BourneToLearn

Learn It: Retrieving Data from Two or more Tables

  • The Book_Store database consists of three tables, with relational databases, we might want to select from multiple tables.
  • For example, we might want to find the names and phone numbers of people who had previously bought a book in 2020.
  • Using SQL, we can combine data from two or more tables by specifying which data the table is held in.
  • When more than one table is involved, SQL uses the syntax tablename.tablefield to specify the field. However, the table name is optional unless the field name appears in more than one table.

Customer Table:

*CustID Title Initial Surname Address City Phone DoB
C001 Mrs C Flowers 23 Rose Ave Bourne 01778 123456 01/11/69
C002 Mr J Eames 100 Dowe Rd Bourne 01778 654321 23/09/87
C003 Mr H Gull 34 High St Bourne 01778 657231 30/07/99
C004 Ms P Jones 89 Knight St Bourne 01778 856021 10/10/56

Books Table:

*BookID Title Author Genre PublishDate Rating
B123 Charlotte's Web E. B. White Fiction 01/01/1952 5
B456 David Copperfield Charles Dickens Fiction 10/12/1850 5
B789 How To: Randall Munroe Fiction 20/08/2019 4
C123 The Way of the Peaceful Warrior Dan Millman Spiritual 01/09/2000 5

Orders Table:

*OrderID CustID BookID OrderDate
O1 C003 B123 15/04/2020
O2 C002 B456 07/02/2019
O3 C001 B789 26/03/2020
O4 C004 C123 01/07/2020
  • EXAMPLE 1: We will write an SQL query to find the Title, Initial, Surname and Phone number of each person, together with the date customer bought a book during 2020.
  • We need to query the tables Customer and Orders to find the matching OrderDate >= 01/01/2020. These two tables are linked by a primary key CustID in the Customer table and a foreign key CustID in the Orders table. This kind of query is called inner join.
SELECT Customer.Title, Initial, Surname, Phone, Orders.CustID, OrderDate
      FROM Customer INNER JOIN Orders ON Customer.[CustID] = Orders.[CustID]
      WHERE Orders.OrderDate >= #1/1/2020#;      
      ORDER BY Surname ASC
  • This SQL query will return the following three records:

3.7.2_DB_SQL3.png

Badge It: Structured Query Langauge (SQL) - SQL to Query two tables

Gold: Carry out the following instructions:

  1. Write an SQL statement to retrieve the title and genre of the books owned by Mr Eames.
  2. Try and write an SQL Statement that will retrieve all the books by the author Dan Millman and show the title and surname of the customer who owns a copy.
  • Upload to 3.7.2 Structured Query Language (SQL) - SQL Statement two tables: Silver on BourneToLearn

3 SQL Syntax - INSERT

Learn It: Insert a new record

  • Example 1: To insert a new record into an existing table we use the SQL INSERT INTO statement. The syntax is:
INSERT INTO tableName (column1, column2,...)
VALUES (value1, value2,...)
  • For example, to insert a record for a new customer, Mrs T Rush, 78 Oak Ave, Peterborough, 01733873194, 19/04/1974
INSERT INTO Customer(CustID, Title, Initial, Surname, Address, City, Phone, DoB)
       VALUES(C005, "Mrs", "T", "Rush", "78 Oak Ave", "Pboro", "01733873194", "19/04/1974");
  • Example 2: To insert a record for a new book, C456, You Care Too Much, Carl Vernon, Self Help, 4, 07/01/2019:
INSERT INTO Books(BookID, Title, Author, Genre, Rating, PublishDate)
        VALUES(C456, "You Care Too Much", "Self Help", "4", "07/01/2019");

4 SQL Syntax - UPDATE

Learn It: Update an existing record

  • To update an existing record's attribute(s) that meeting a specified condition, we use the SQL UPDATE statement. The syntax is:
UPDATE tableName
SET column1 = value1, column2 = value2, ...
WHERE column = value
  • Example: Update the record of CustID C001, Mrs Flowers, who has changed her address to 63 River Way, and her phone number to 01778 886210.
UPDATE Customer
       SET Address = "63 River Way", Phone = "01778 886210"
       WHERE CustID = "C001"

5 SQL Syntax - DELETE

Learn It: Delete an existing record

  • To delete an existing record from a table that meeting a specified condition, we use the SQL DELETE statement. The syntax is:
DELETE FROM tablename
WHERE column = value
  • Example: Delete the record for CustID C004, Ms, P, Jones.
DELETE FROM Customer
WHERE CustID = C004

Try It: SQL Zoo - INSERT…UPDATE…DELETE

  • Try practising your SQL skills by working through the following SQL Insert and Delete Stages 1 to 7:

Badge It: Structured Query Langauge (SQL) - SQL Exam Questions

Platinum: Answer the following exam questions:

  • A relational database is being developed to store information about the games that are available to play at a games café and the advance bookings that have been made for those games. Each game has a unique name.
    • The database contains two tables: Game and Booking.
    • The database is currently being tested by the person who has developed it so the database tables only contain a small amount of data that is being used for testing.
    • The contents of the tables are shown below.

3.7.2_DB_Plat_Game_Booking.png

  1. State the field in the Booking table that is a foreign key? (1 Mark)
  2. State the most suitable data type to use for the Complexity field. (1 Mark)
  3. Due to a change in layout at a games café, the game table with an ID of 2 is no longer suitable for games that can have more than four players. The manager needs to find out the customer, date and time of all bookings made for the game table with an ID of 2 that are for a game that can have more than four players.
    • a) Write an SQL query that could be used to find this information for the manager. The results should be shown in date order. (6 Marks)
  4. The LengthOfGame field shows the average amount of time it takes to play a game in minutes. A query to add 10 minutes to the length of time taken for all games that have a Complexity of more than three is shown below:
UPDATE Game
SET LengthOfGame = LengthOfGame + 9
WHERE Complexity <= 3
  • a) The query contains two errors.
  • b) Refine the query to correct the errors.
  • Upload to 3.7.2 Structured Query Language (SQL) - SQL Exam Questions: Platinum on BourneToLearn

6 Extension Exam Questions

Try It

  • Try these examination questions on SQL.

8.jpg

Validate