SQL
- Records in a database can be searched and data can be manipulated using Structured Query Language (SQL)
- SQL statements can be written to query the data in the database and extract useful information
- SQL statements follow this structure:
- SELECT the fields you want to display
- FROM the table/tables containing the data you wish to search
- WHERE the search criteria
A Database Table Containing Movie Details
|
|
|
|
|
M23 |
Moana |
Family |
U |
8.1 |
M8 |
Shaun of the Dead |
Comedy |
18 |
8.7 |
M56 |
Die Hard |
Action |
18 |
8.4 |
M34 |
Big |
Family |
PG |
8.5 |
Example
SELECT Name, Rating
FROM Movie
WHERE Rating>8.4;
The results of this query would be:
|
|
Shaun of the Dead |
8.7 |
Big |
8.5 |
- The two fields - Name and Rating have been extracted from the Movie table and then the records have been filtered by Rating
- This example uses the > operator to search for records where the rating is greater than 8.4
- There are several other comparison operators which can be used to create the filter criteria in the WHERE line of a SQL query
SQL Comparison Operators
|
|
> |
Greater than |
>= |
Greater than or equal to |
< |
Less than |
<= |
Less than or equal to |
= |
Equal to |
<> |
Not equal to |
Example
SELECT Name,Rating
FROM Movie
WHERE Genre=”Family” AND Certificate=”U”;
The results of this query would be:
|
|
Moana |
8.1 |
- The two fields Name and Rating have been extracted from the Movie table and the records have been filtered by both Genre and Certificate
- This query uses the AND logical operator to include multiple criteria in the WHERE line of the SQL query
- Another logical operator which can be used in the WHERE statement is OR
- For example, WHERE Genre=”Comedy” OR Genre=”Family”
Worked example
A database table, Dogs2023, is used to keep a record of all dogs registered at a veterinary practice
|
|
|
|
|
DG12 |
Smokey |
Poodle |
12 |
M |
DG34 |
Harvey |
Springer Spaniel |
10 |
M |
DG48 |
Maisie |
Labradoodle |
3 |
F |
DG49 |
Maggie |
Labradoodle |
3 |
F |
DG88 |
Winston |
Bulldog |
7 |
M |
DG95 |
Shona |
Golden Retriever |
6 |
F |
Complete the structured query language (SQL) to return the name and breed of all Female dogs.
SELECT Name,Breed
________ Dogs2023
WHERE _______;
[2]
FROM [1]
Gender=”F” [1]
Write an SQL query to find out the name and breed of all dogs aged 10 years old or older
[4]
SELECT Name, Breed [1]
FROM Dogs2023 [1]
WHERE Age>=10; [2]