By the end of this chapter, you will be able to:
Mastering these skills means you can build secure, reliable databases that keep data safe and support real-world business needs.
Creating and managing secure databases is fundamental for cyber security professionals in Kenya, especially given the growing reliance on digital data across sectors such as banking, healthcare, and government services. This chapter focuses on practical skills for creating and querying databases using MySQL, a widely adopted relational database management system. Mastery of SQL (Structured Query Language) is essential for securely accessing and manipulating data, enabling professionals to safeguard sensitive information effectively. Understanding SQL categories, designing statements, and executing queries lays the foundation for robust database security and operational efficiency.
Querying a database is the process of requesting specific data from a database system using a query language. In Kenya's cyber security environment, correctly querying databases supports the detection of anomalies, audit trails, and enforcement of access controls. MySQL is a popular choice for relational databases due to its open-source nature and extensive support for SQL standards, making it a key tool for cyber security analysts and database administrators.
SQL statements are commands used to interact with databases. They fall into distinct categories based on their functions, each vital for database management and security.
DDL statements define or modify database structures such as tables and indexes. Key commands include CREATE, ALTER, and DROP. For example, in a county government office managing citizen records, DDL commands create tables to store personal details securely and alter them when additional fields are required, such as biometric data.
DML statements manipulate data within existing tables. These include SELECT, INSERT, UPDATE, and DELETE. In a hospital setting, DML commands retrieve patient records, insert new treatment data, update medication information, or delete outdated entries while ensuring audit compliance.
DCL manages permissions and controls access to data. Commands like GRANT and REVOKE assign or remove user privileges. For instance, a financial institution uses DCL to restrict sensitive data access only to authorized staff, preventing insider threats.
TCL handles transactions ensuring data integrity. Commands such as COMMIT, ROLLBACK, and SAVEPOINT manage changes as atomic units. In retail companies, TCL ensures that stock updates and sales records are consistent even if a system failure occurs mid-transaction.
Although often grouped under DML, DQL specifically refers to SELECT statements that query data. Cyber security professionals use DQL extensively to monitor logs and extract relevant information for threat analysis.
Designing SQL statements involves constructing commands that accurately and securely perform database operations. Good design prevents SQL injection attacks, optimizes performance, and ensures data integrity.
SQL statements should follow a logical structure to enhance readability and debugging. For example, a SELECT statement typically orders clauses as SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. Proper indentation and capitalization conventions help maintain standards in collaborative environments like government IT departments.
SQL queries are specific commands designed to retrieve or manipulate data. Designing effective queries requires understanding the data model and intended results.
Efficient queries reduce server load and improve response times, crucial for real-time cyber security monitoring. Indexing relevant columns and avoiding unnecessary columns in SELECT statements are common optimization techniques. For example, the Kenya Revenue Authority (KRA) optimizes tax data queries to quickly detect anomalies.
Executing SQL statements involves interacting with the database engine to retrieve or modify data. Cyber security professionals must ensure queries are accurate, efficient, and secure.
sql
SELECT user_id, login_time, ip_address
FROM activity_logs
WHERE login_time > '2024-01-01 00:00:00'
ORDER BY login_time DESC;
sql
UPDATE members
SET password_hash = SHA2(CONCAT(salt, password), 256)
WHERE last_password_update < '2023-01-01';
This chapter focused on querying a database using MySQL, beginning with an understanding of the different categories of SQL statements and their distinct roles in database management. It then explored the design of SQL statements, emphasizing the importance of constructing accurate and efficient commands to interact with data. The chapter progressed to the design of SQL queries, highlighting how to retrieve specific information by structuring queries to meet particular data requirements. Finally, practical use of SQL statements was covered, demonstrating how to execute queries to extract and manipulate data within a database environment. Mastery of these skills enables effective communication with databases, ensuring data can be accessed and managed securely and efficiently.
Employees where the department is 'Finance'. (4 marks) WHERE clause in SQL queries. (3 marks) TempData from the database? (2 marks) JOIN operation work in SQL? Provide an example scenario relevant to a Kenyan bank. (4 marks) Clients table who live in Nairobi. (4 marks) INNER JOIN and LEFT JOIN with respect to query results. (4 marks) SELECT * FROM Employees WHERE department = 'Finance'; retrieves all employees in the Finance department. UPDATE statement modifies existing data in a database. WHERE clause filters records to return only those that meet specified conditions, improving query precision. DROP TABLE TempData; removes the entire table and its data from the database. JOIN operation combines rows from two or more tables based on related columns. For example, a Kenyan bank can join Accounts and Customers tables on CustomerID to retrieve customer account details. SELECT COUNT(*) FROM Clients WHERE city = 'Nairobi'; counts clients residing in Nairobi. INNER JOIN returns only matching rows from both tables; LEFT JOIN returns all rows from the left table and matching rows from the right, filling NULLs where no match exists. Question 1 key points:
- DCL statements like GRANT and REVOKE enforce user permissions, limiting unauthorized access.
- DDL controls structural changes, preventing accidental or malicious schema alterations.
- TCL ensures transactional integrity, avoiding partial updates that can compromise data consistency.
- Understanding these categories helps cybersecurity professionals apply precise controls to safeguard data.
Question 2 key points:
- Efficient queries reduce processing time, lowering exposure to denial-of-service risks.
- Well-designed queries minimize excessive data retrieval, reducing attack surface.
- Proper indexing and query optimization prevent system bottlenecks, enhancing resilience.
- Secure query design includes input validation and parameterization to prevent injection attacks.
The Central Bank of Kenya is upgrading its customer transaction database to improve query efficiency and security.
Tasks:
a) Identify and categorize the SQL statements that the database administrators should use to create and secure the new database schema. (5 marks)
b) Design a SQL query to retrieve all transactions above Ksh 100,000 for customers based in Mombasa. (5 marks)
c) Explain how using parameterized queries in this context can prevent SQL injection attacks. (5 marks)
a) The administrators should use DDL statements such as CREATE TABLE and ALTER TABLE to define and modify schema. DCL statements like GRANT and REVOKE will control user permissions. TCL commands such as COMMIT and ROLLBACK will manage transaction integrity. Recognizing these categories ensures proper database structure and access control.
b) A suitable query would be:
SELECT * FROM Transactions WHERE amount > 100000 AND customer_city = 'Mombasa';
This query filters transactions exceeding Ksh 100,000 for customers located in Mombasa, enabling focused data retrieval.
c) Parameterized queries separate SQL code from user input, preventing attackers from injecting malicious commands. In the banking context, this protects sensitive transaction data by ensuring inputs such as customer identifiers or amounts do not alter the query logic, thereby safeguarding against SQL injection exploits.
Question 11 (Compulsory - 20 marks)
At Equity Bank, the IT security team is tasked with creating and querying a customer transactions database securely.
a) Design SQL statements to create tables for Customers and Transactions, including appropriate data types and primary keys. (10 marks)
b) Write SQL queries to:
i. Retrieve all transactions for a specific customer with CustomerID 12345.
ii. Calculate the total transaction amount for CustomerID 12345. (10 marks)
Question 12 (20 marks)
Explain how SQL injection attacks can be mitigated when querying databases in public sector institutions such as the Kenya Revenue Authority (KRA). Illustrate your answer with examples of secure SQL query design.
Question 13 (20 marks)
Discuss the process of designing complex SQL queries involving multiple tables using JOIN operations. Use examples relevant to a county government payroll database to explain INNER JOIN, LEFT JOIN, and FULL OUTER JOIN.
Question 14 (20 marks)
You are tasked with querying a hospital database to generate a report of patients admitted in the last 30 days with their attending doctors and treatment status.
a) Outline the SQL query design steps for this task.
b) Provide a sample SQL query implementing these requirements.
Question 11
a) CREATE TABLE Customers (CustomerID INT PRIMARY KEY, Name VARCHAR(100), Email VARCHAR(100), PhoneNumber VARCHAR(15));
CREATE TABLE Transactions (TransactionID INT PRIMARY KEY, CustomerID INT, Amount DECIMAL(10,2), TransactionDate DATE, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
b) i. SELECT * FROM Transactions WHERE CustomerID = 12345;
ii. SELECT SUM(Amount) FROM Transactions WHERE CustomerID = 12345;
Question 12
SQL injection can be mitigated by using parameterized queries or prepared statements that separate SQL code from user inputs, preventing attackers from injecting malicious SQL. For example, using placeholders in queries and binding user inputs securely ensures that inputs are treated as data only. Additionally, input validation and least privilege access reduce risks.
Question 13
Designing complex queries requires understanding relationships between tables and choosing appropriate JOINs:
- INNER JOIN returns records with matching keys in both tables, e.g., joining employee and payroll tables to list employees with pay records.
- LEFT JOIN returns all records from the left table and matching ones from the right table, useful to show all employees including those without payroll entries.
- FULL OUTER JOIN returns all records from both tables, including unmatched records on either side, helpful in audit reporting.
Question 14
a) Steps:
1. Identify relevant tables: Patients, Admissions, Doctors, Treatments.
2. Determine join conditions based on foreign keys, e.g., PatientID, DoctorID.
3. Use WHERE clause to filter admissions within the last 30 days using date functions.
4. Select required fields: patient details, doctor names, treatment status.
5. Test query for accuracy and performance.
b) Sample query:
SELECT p.PatientName, d.DoctorName, t.TreatmentStatus, a.AdmissionDate
FROM Admissions a
INNER JOIN Patients p ON a.PatientID = p.PatientID
INNER JOIN Doctors d ON a.DoctorID = d.DoctorID
INNER JOIN Treatments t ON a.AdmissionID = t.AdmissionID
WHERE a.AdmissionDate >= CURDATE() - INTERVAL 30 DAY;
Type: Individual
| Tools & Equipment | Materials |
|---|---|
| Pen | List of 16 SQL statements printed on A4 sheets |
| Assessment answer sheet |
| S/N | Item | Quantity |
|---|---|---|
| 1 | List of 16 SQL statements printed on A4 sheets | 1 set per Candidate |
| 2 | Assessment answer sheet | 1 per Candidate |
| 3 | Pen | 1 per Candidate |
| Items to be Evaluated | Marks Available | Marks Obtained | Comments |
|---|---|---|---|
| TASK 1: Identification and Classification of SQL Statements | |||
| Candidate reads and understands each SQL statement (Award 1 mark for correctly identifying understanding of half the statements, 2 marks for all) | 2 | ||
| Candidate correctly classifies SQL statements into DDL category (Award 1 mark for each correct classification, max 4 marks) | 4 | ||
| Candidate correctly classifies SQL statements into DML category (Award 1 mark for each correct classification, max 4 marks) | 4 | ||
| Candidate correctly classifies SQL statements into DCL category (Award 1 mark for each correct classification, max 3 marks) | 3 | ||
| Candidate correctly classifies SQL statements into TCL category (Award 1 mark for each correct classification, max 3 marks) | 3 | ||
| Sub-Total | 16 | ||
| PRODUCT CHECKLIST | |||
| All 16 SQL statements correctly classified into exactly one category each (Award 4 marks if all statements correctly placed; zero if any misclassified) | 4 | ||
| Sub-Total | 4 | ||
| GRAND TOTAL | 20 | ||
Type: Individual
| Tools & Equipment | Materials |
|---|---|
| Computer with SQL database management system installed | Access to sample database schema documentation |
| Keyboard and Mouse | Notepad and Pen |
| S/N | Item | Quantity |
|---|---|---|
| 1 | Computer with SQL database management system installed (e.g. MySQL Workbench or MS SQL Server Management Studio) | 1 Pc per Candidate |
| 2 | Access to sample database schema documentation | 1 set per Candidate |
| 3 | Keyboard and Mouse | 1 set per Candidate |
| 4 | Notepad and Pen | 1 set per Candidate |
| Items to be Evaluated | Marks Available | Marks Obtained | Comments |
|---|---|---|---|
| TASK 1: Create and Save Database | |||
| Opened SQL database management system and created database named SecureDB (Award 1 mark for correctly creating and saving the database named SecureDB) | 1 | ||
| Sub-Total | 1 | ||
| TASK 2: Create Tables Customers and Transactions | |||
| Typed field names correctly for Customers table including CustomerID (PK), FullName, Email, Phone (Award 1 mark for each correct field name and datatype in Customers table, max 4 marks) | 4 | ||
| Typed field names correctly for Transactions table including TransactionID (PK), CustomerID (FK), Amount, TransactionDate (Award 1 mark for each correct field name and datatype in Transactions table, max 4 marks) | 4 | ||
| Set primary keys for both tables and foreign key constraint from Transactions.CustomerID to Customers.CustomerID (Award 2 marks for correctly setting PKs and FK relationship) | 2 | ||
| Sub-Total | 10 | ||
| TASK 3: Write Insert Statements | |||
| Wrote correct SQL INSERT statement to add at least two records into Customers table (Award 1.5 marks per correct insert statement, max 3 marks) | 3 | ||
| Wrote correct SQL INSERT statement to add at least two records into Transactions table referencing existing CustomerIDs (Award 1.5 marks per correct insert statement, max 3 marks) | 3 | ||
| Sub-Total | 6 | ||
| TASK 4: Write Update and Delete Statements | |||
| Wrote correct SQL UPDATE statement to modify a customer’s phone number (Award 2 marks for correct update syntax and execution) | 2 | ||
| Wrote correct SQL DELETE statement to remove a transaction record by TransactionID (Award 2 marks for correct delete syntax and execution) | 2 | ||
| Sub-Total | 4 | ||
| TASK 5: Secure Database with Password | |||
| Applied password encryption or set database user password as per system capabilities (Award 2 marks for correctly securing the database with password) | 2 | ||
| Sub-Total | 2 | ||
| PRODUCT CHECKLIST | |||
| Database SecureDB exists with Customers and Transactions tables created correctly with proper field names, keys, and relationships (Award 5 marks if database and tables exist and match specifications exactly) | 5 | ||
| At least two records inserted into each table with correct data referencing and data integrity maintained (Award 4 marks for correctness and referential integrity of inserted data) | 4 | ||
| Update and delete operations executed successfully and affected correct records (Award 3 marks if update and delete statements executed correctly) | 3 | ||
| Database is password protected or encrypted as required (Award 3 marks if database is secured with password) | 3 | ||
| Sub-Total | 15 | ||
| GRAND TOTAL | 38 | ||
At the start of this chapter we promised you would be able to:
Tick each one you can genuinely do.
So, are you there yet?
You're competent when you can confidently do 50% or more of what this chapter promised.
Sign in to record how you're doing.