0% found this document useful (0 votes)
5 views

LearningTask4Document1 (2)

The document outlines a mission for FBI agents to use SQL queries to analyze a parking garage database in order to track down an international cybercriminal. It provides an introduction to database theory, basic SQL queries, and advanced queries tailored for the investigation. Key SQL concepts include selecting, filtering, sorting data, and using aggregate functions to identify suspicious activities related to car rentals.

Uploaded by

malebyelesedi20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

LearningTask4Document1 (2)

The document outlines a mission for FBI agents to use SQL queries to analyze a parking garage database in order to track down an international cybercriminal. It provides an introduction to database theory, basic SQL queries, and advanced queries tailored for the investigation. Key SQL concepts include selecting, filtering, sorting data, and using aggregate functions to identify suspicious activities related to car rentals.

Uploaded by

malebyelesedi20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

LEARNING TASK 3

DOCUMENT 1: SQL INTRO

Hacker Hunt

a. DataBaSe tHeOrY IntrODuctIOn .................................................................. 3


B. BaSIc SQL QuerIeS ........................................................................................... 6
B. aDvanceD QuerIeS fOr Hacker SearcH .................................................... 19

Page 1 of 20
FBI MISSION BRIEFING

Agents, listen up! An international cybercriminal is on the run, and intel suggests he
is hiding in our territory. Our only lead? A parking garage database that could hold the
key to his location.

Your mission: Use SQL queries to sift through the data, analyse parking records, and
track down the hacker’s identity. Look for suspicious patterns, cross-check the
evidence, and identify his mobile base of operations.

Time is of the essence. The FBI is counting on you. Good luck, agents!

Page 2 of 20
a. DataBaSe tHeOrY IntrODuctIOn

UNDERSTANDING TABLES

Have a look at the 3 tables below that form the RentMyParking database (used in
the IEB Final Prac paper of 2023):

Page 3 of 20
Looking at each of these tables, you need to understand the following:

• A row is called a record.


o For example, one car's information (model, colour, etc.) would be a record.

o A record is a set of values that describe an entity.

• A column is called a field.


o For example, the column labelled carRegistration is a field.

• The values in a column describe a specific attribute of an entity (e.g., the


registration of a car).

• A table (or relation) is a collection of records (also called tuples). All the data for
a specific entity (like cars, parking lots, etc.) is stored in a table.
• Rows are normally identified by a primary key.

• Definition of Primary Key: A primary key uniquely identifies a record. For


example, the registration number for a car is a primary key because each car will
have a unique registration number.

SQL Statements

We use SQL statements to display or manipulate data in tables. The most commonly
used SQL statements are:

• SELECT: Retrieve information from the database (DB).

• INSERT: Add new records to a table in the DB.

• UPDATE: Modify existing records in the DB.

• DELETE: Remove data from the DB.

Page 4 of 20
Format of SELECT Statements

When working with a table, the format is as follows:

SELECT TOP <x> DISTINCT <field1>, <field2>

FROM <table1>

WHERE <condition1> AND <condition2>

GROUP BY <field1>, <field2>

ORDER BY <field1>, <field2>

Operators to be used in conditions

Operator Description Example

>, <, >=, "greater than", "smaller than", "greater or equal


WHERE age >= 18
<= to", "smaller or equal to"

= "is equal to" (not ==) WHERE age = 21

<> "not equal to" (not !=) WHERE age <> 21

WHERE lastName
LIKE "matches" (used for pattern matching)
LIKE ‘J*’

WHERE handicap IS
IS NULL The field is empty (does not contain data)
NULL

Using literals

• Text must be included in quotes (") or ('), e.g., WHERE Colour= “red".

• Dates should be enclosed in ##, e.g., WHERE StartDate = #22/02/2008#.

• Numbers should not have any quotes, e.g., WHERE parkingID = 5.

• Boolean values use yes/true or no/false, e.g., WHERE PremiumParking =


yes or WHERE PremiumParking = true.
Page 5 of 20
B. BaSIc SQL QuerIeS
Try doing the queries listed below. Each query contains a question, the SQL that will
answer that question and the first 3 rows of the output you should expect. When using a
SqlBrowser program the output might not show all the fields at the same time. You might
need to scroll to the right.

1. Using * for Selecting All Columns

The * symbol is used to select all columns from a table. To view all car details:

SQL Syntax:

SELECT *
FROM tblCars;

2. Selecting Specific Columns

To retrieve specific details (e.g., car registration and owner), we specify the columns
to be selected.

SQL Syntax:

SELECT CarRegistration, Owner


FROM tblCars;

Page 6 of 20
3. Using AS to Rename Columns

Use AS to assign a new name to a column. Let’s rename CarRegistration to


LicensePlate and Owner to CarOwner.

SQL Syntax:

SELECT CarRegistration AS LicensePlate, Owner AS CarOwner


FROM tblCars;

4. Filtering Data with WHERE

Use the WHERE clause to filter records based on conditions. For instance, find all
red cars.

SQL Syntax:

SELECT *
FROM tblCars
WHERE Colour = 'Red';

Page 7 of 20
5. Using LIKE for Pattern Matching Example 1

The LIKE keyword helps us search for patterns within text fields. Let’s find all cars
whose registration starts with "BBC".

SQL Syntax:

SELECT CarRegistration, Owner


FROM tblCars
WHERE CarRegistration LIKE 'BBC*';

6. Using LIKE for Pattern Matching Example 2

The LIKE keyword helps us search for patterns within text fields. Let’s find all cars
whose registration ends with "NC".

SQL Syntax:

SELECT CarRegistration, Owner


FROM tblCars
WHERE CarRegistration LIKE ‘*NC’;

Page 8 of 20
7. Using LIKE for Pattern Matching Example 3

The LIKE keyword helps us search for patterns within text fields. Let’s find all cars
whose model includes the word "Rover".

SQL Syntax:

SELECT CarRegistration, Owner


FROM tblCars
WHERE Model LIKE ‘*ROVER*’;

8. Sorting Data with ORDER BY

You can sort the data by specific columns. Let’s sort by owner name.

SQL Syntax:

SELECT CarRegistration, Owner


FROM tblCars
ORDER BY Owner;

Page 9 of 20
9. Sorting Data in Descending Order

For descending order sorting, use DESC. Let’s sort the parking start dates from most
recent to oldest.

SQL Syntax:

SELECT CarRegistration, ParkingID, StartDate


FROM tblRentedParkings
ORDER BY StartDate DESC;

10. Sorting Data in Order for Multiple Fields

Let’s first sort the parking start dates according to the ParkingID field and then from
most recent to oldest as well.

SQL Syntax:

SELECT CarRegistration, ParkingID, StartDate


FROM tblRentedParkings
ORDER BY ParkingID, StartDate DESC;

Page 10 of 20
11. Counting Rows with COUNT()

The COUNT() function is used to count how many records meet a specific condition.

SQL Syntax:

SELECT COUNT(*) AS NumberOfCars


FROM tblRentedParkings
WHERE ParkingID = 5;

12. Using NOW() to Get the Current Date and Time

The NOW() function retrieves the current date and time. Let’s find all cars rented
before the current date.

SQL Syntax:

SELECT CarRegistration, StartDate


FROM tblRentedParkings
WHERE StartDate <= NOW();

Page 11 of 20
13. Using DISTINCT to Remove Duplicates

The DISTINCT keyword removes duplicates. Let’s get a list of unique car colors.

SQL Syntax:

SELECT DISTINCT Colour


FROM tblCars;

14. Using BETWEEN to Filter Data within a Range

The BETWEEN keyword is used for filtering records within a range. For example, we
want to find cars rented between January 1st, 2023, and June 30th, 2023.

SQL Syntax:

SELECT CarRegistration, StartDate


FROM tblRentedParkings
WHERE StartDate BETWEEN #2023-01-01# AND #2023-06-30#;

Page 12 of 20
15. Using TOP to Limit Results

The TOP keyword allows limiting the number of rows returned. For example, let’s get
the top 5 most recent car rentals.

SQL Syntax:

SELECT TOP 5 CarRegistration


FROM tblRentedParkings
ORDER BY StartDate DESC;

16. Using AVG() to Calculate the Average

The AVG() function calculates the average value of a numeric field. Let’s calculate
the average daily rate of parking spots.

SQL Syntax:

SELECT AVG(DailyRate) AS AverageRate


FROM tblParkings;

Page 13 of 20
17. Using SUM() to Calculate the Total

The SUM() function adds up all the values in a numeric column. Let’s find the total
daily rate for premium parking spots.

SQL Syntax:

SELECT SUM(DailyRate) AS TotalPremiumRate


FROM tblParkings
WHERE PremiumParking = Yes;

18. Using MIN() to Find the Minimum Value

The MIN() function returns the smallest value in a column. Let’s find the minimum
daily parking rate.

SQL Syntax:

SELECT MIN(DailyRate) AS MinimumRate


FROM tblParkings;

Page 14 of 20
19. Using MAX() to Find the Maximum Value
The MAX() function returns the largest value in a column. Let’s find the maximum
daily parking rate.

SQL Syntax:

SELECT MAX(DailyRate) AS MaximumRate


FROM tblParkings;

20. Grouping Data Using GROUP BY


Let's say you want to group the cars by their colour and count how many cars of
each colour are in the database. You can use GROUP BY to group the records by a
specific field and then apply an aggregate function (like COUNT) to summarize the
data.

SQL Syntax:

SELECT Colour, COUNT(CarRegistration) AS NumberOfCars


FROM tblCars
GROUP BY Colour;

Explanation:
• Colour: This is the field we're grouping by.
• COUNT(CarRegistration): This counts how many cars are there for each
color.
• AS NumberOfCars: This gives a name to the resulting column, so instead of
displaying COUNT(CarRegistration), it will show NumberOfCars.
This query will return a list of colors with the number of cars in each color, grouped
accordingly.

Page 15 of 20
21. Finding the Number of Cars Per Parking Spot

We can use GROUP BY to group data and count cars in each parking spot.

SQL Syntax:

SELECT ParkingID, COUNT(*) AS NumberOfCars


FROM tblRentedParkings
GROUP BY ParkingID;

22. Adding a Criteria to a Group By.

We have a table called tblRentedParkings, which contains information about car


rentals for parking spots. The columns in the table are:
• CarRegistration: The car's license plate number.
• ParkingID: The parking spot ID where the car was parked.
• StartDate: The date when the car entered the parking lot.
• EndDate: The date when the car left the parking lot.

We must know how many cars were parked in each parking spot for more than 10
days. Use the GROUP BY clause to group the data by ParkingID and the HAVING
clause to filter the results where the number of days parked is greater than 2.

SQL Syntax:

SELECT ParkingID, COUNT(CarRegistration) AS TotalCars


FROM tblRentedParkings
GROUP BY ParkingID
HAVING COUNT(CarRegistration) > 2;

Page 16 of 20
Explanation:
1. SELECT ParkingID, COUNT(CarRegistration) AS TotalCars:
o We are selecting two columns:
▪ ParkingID: The parking spot where the car was parked.
▪ COUNT(CarRegistration): The number of cars that used that
parking spot. We are counting how many cars parked in each
parking spot.
2. FROM tblRentedParkings:
o We are pulling data from the tblRentedParkings table.
3. GROUP BY ParkingID:
o We are grouping the data by ParkingID, which means we will get the
results for each unique parking spot.
4. HAVING COUNT(CarRegistration) > 2:
o After grouping the data, we use the HAVING clause to filter out parking
spots where fewer than 2 cars used that parking spot.
o The HAVING clause is used after GROUP BY to apply conditions on
aggregated data (like COUNT in this case). So, this query will only
show parking spots where more than 2 cars have parked.
o

Key Takeaways:
• GROUP BY is used to group data based on a specific column (like
ParkingID).
• HAVING is used to filter the grouped data after it has been aggregated (like
counting the number of cars). It allows you to set conditions on the grouped
results. We do not use WHERE to add criteria to a GROUP BY function.

Page 17 of 20
23. Extract the day from a DATE field
You can use DAY(), MONTH(), and YEAR() functions to extract specific parts of a
date. Let’s say we want to see the days when cars parked in the parking lot.

SQL Syntax:

SELECT CarRegistration, ParkingID, StartDate, DAY(StartDate) AS Day


FROM tblRentedParkings;

24. Calculate the Number of Days a Car Stayed in a Parking Spot

Here’s how you would write the query to calculate the duration of each parking stay
in days.

SQL Syntax:

SELECT CarRegistration, ParkingID, StartDate, EndDate, DATEDIFF(“d”, StartDate,


EndDate) AS Duration
FROM tblRentedParkings;

Explanation:
• DATEDIFF(“d”, StartDate, EndDate) calculates the number of days the car
stayed in the parking spot.
• “d” specifies that the difference should be calculated in days. This could also
be “m” or “y”.
• StartDate and EndDate are the dates we are comparing.

Page 18 of 20
B. aDvanceD QuerIeS fOr Hacker SearcH

Mission Briefing:

Now that you know the basics of SQL, you can start using your knowledge to look for
suspicious activities in the Parking data.

25. Find Cars That Stayed in a Parking Lot Unusually Long

Find cars that stayed in a parking lot for more than 15 days.

SQL Syntax:

SELECT CarRegistration, ParkingID, StartDate, EndDate, DATEDIFF(“d”, StartDate,


EndDate) AS Duration
FROM tblRentedParkings
WHERE DATEDIFF(“d”, StartDate, EndDate) > 15;

26. Find Cars That Used Multiple Parking Lots in a Short Time

Find cars that used more than two parking lots in a short period.

SQL Syntax:

SELECT CarRegistration, COUNT(ParkingID) AS NumberOfParkingLots


FROM tblRentedParkings
GROUP BY CarRegistration
HAVING COUNT(ParkingID) > 2;

Page 19 of 20
27. Find Cars That Have No Recorded Exit

Check if there are cars that entered a parking lot but have no recorded exit.

SQL Syntax:

SELECT CarRegistration, ParkingID, StartDate


FROM tblRentedParkings
WHERE EndDate IS NULL;

28. Find Cars That Visited the Same Parking Lot Multiple Times in a Short
Period

See if any cars visited the same parking spot more than once.

SQL Syntax:

SELECT CarRegistration, ParkingID, COUNT(*) AS VisitCount


FROM tblRentedParkings
GROUP BY CarRegistration, ParkingID

29. Find the Last Known Parking Spot of a Specific Car

Decide who you think is the most suspicious owner and check his/her registration
number to determine their last known parking location.

SQL Syntax:

SELECT top 1 CarRegistration, ParkingID, StartDate, EndDate


FROM tblRentedParkings
WHERE CarRegistration = 'ENTER SUSPICIOUS REGISTRATION NUMBER'
ORDER BY EndDate DESC

Page 20 of 20

You might also like