Computer Science  ·  Level 6
Database Management
Chapter 3: Structured Query Language
📚 11 Topics
⚑ What you will be able to do

By the end of this chapter, you will be able to:

  • Apply Structured Query Language (SQL) correctly to manage and interact with databases.
  • Create a database from a validated Entity-Relationship (ER) model and query it using proper procedures.
  • Use SQL joins effectively to combine and retrieve data from multiple tables.
  • Define and manage database structures by applying data definition queries in SQL.
  • Create tables accurately using the SQL CREATE TABLE statement.
  • Enforce data rules by applying constraints within the CREATE TABLE statement.
  • Edit table schemas precisely using the SQL ALTER TABLE statement.
  • Safely remove tables when needed using the SQL DROP TABLE statement.
  • Modify and manipulate data correctly using SQL data manipulation statements.

Mastering these SQL skills will empower you to handle real-world databases confidently, making you a valuable asset in any data-driven workplace.

Structured Query Language (SQL) is a fundamental skill for computer science professionals in Kenya who work with databases, enabling them to manage and manipulate data efficiently. As organizations increasingly rely on digital data for decision-making, proficiency in SQL is essential for designing, querying, and maintaining databases that support business operations. This chapter explores SQL’s definition, its defining characteristics, and the core components that form the basis of database interactions in professional environments such as banks, universities, and government agencies.

3.1 SQL

SQL is the standard language used to communicate with relational database management systems (RDBMS). It allows users to perform a variety of operations including data retrieval, insertion, update, and deletion. Understanding SQL is crucial for computer science professionals in Kenya, especially when working with systems in sectors like finance, healthcare, and public administration, where accurate data handling is critical.

3.1.1 Definition

SQL stands for Structured Query Language, a specialized programming language designed for managing relational databases. It provides a standardized way to create, read, update, and delete data stored in tables, which are organized into rows and columns. Unlike general-purpose programming languages, SQL focuses exclusively on data manipulation and querying within database systems.

SQL emerged in the 1970s as a result of research on relational database models, and it has since become the universal language supported by most commercial and open-source database systems. In Kenya, institutions such as the Kenya Revenue Authority (KRA) and commercial banks rely heavily on SQL to manage large volumes of transactional data securely and efficiently.

Characteristics of SQL

  • Declarative Language: SQL is declarative, meaning users specify what data they want without detailing how to retrieve it. This simplifies database operations, allowing professionals to focus on data requirements rather than procedural details.

  • Non-Procedural Nature: Unlike procedural languages, SQL commands do not require specifying control flow. This facilitates quicker learning and application for database tasks such as querying customer records in a SACCO.

  • Portability: SQL commands are largely portable across different database systems, meaning that skills learned using MySQL or PostgreSQL can be applied in Microsoft SQL Server or Oracle environments with minimal adjustments.

  • Set-Based Operations: SQL works on sets of data rather than individual records, enabling efficient processing of large datasets, such as generating reports from a county government’s population database.

  • Extensibility: SQL supports extensions and procedural elements (like PL/SQL in Oracle), allowing developers to write complex logic while still leveraging standard querying capabilities.

3.1.2 Characteristics

SQL’s defining features enable it to serve as the backbone of data management in professional Kenyan contexts. These characteristics ensure that SQL remains versatile, powerful, and accessible to database administrators and developers.

Declarative Syntax

SQL focuses on what data is needed rather than how to obtain it, which means users write queries specifying the desired outcome. This contrasts with imperative programming languages and reduces the complexity of database interactions.

  • This approach allows professionals in financial institutions like Equity Bank to write queries extracting customer transaction histories without managing underlying data retrieval processes.

  • Declarative syntax improves productivity since less code is required to perform complex data operations.

Data Manipulation and Definition

SQL encompasses both Data Manipulation Language (DML) and Data Definition Language (DDL) components, allowing users to handle data content and database schema respectively.

  • DML commands such as SELECT, INSERT, UPDATE, and DELETE enable modification and retrieval of data records in tables.

  • DDL commands like CREATE, ALTER, and DROP allow database designers at universities to define or modify table structures and relationships.

Transaction Control

SQL supports transaction management to ensure data integrity during multi-step operations, essential in environments where consistency is critical.

  • Commands such as BEGIN TRANSACTION, COMMIT, and ROLLBACK help maintain accurate records in scenarios like booking hotel reservations or processing loan applications at SACCOs.

  • This capability ensures that either all changes are applied successfully or none, protecting against partial updates that could corrupt data.

Data Integrity Enforcement

SQL supports constraints such as primary keys, foreign keys, unique constraints, and checks to enforce data validity.

  • For example, a county government database might use foreign key constraints to ensure that employee records always reference valid department entries.

  • These features prevent erroneous data entry and maintain relational consistency across tables.

Security and Access Control

SQL includes commands to define user roles, privileges, and permissions, enabling fine-grained control over who can access or modify data.

  • In banking systems, this ensures that tellers can only access customer account information relevant to their duties, while auditors have read-only access for compliance checks.

  • SQL’s security features are fundamental for protecting sensitive data in compliance with Kenya’s Data Protection Act.

3.1.3 Components

SQL’s functionality is organized into distinct components that collectively manage data definition, manipulation, control, and querying. Mastery of these components enables computer science professionals to design robust database applications.

Data Definition Language (DDL)

DDL commands define and modify database schema objects such as tables, indexes, and views.

  • CREATE: Defines new tables or database objects. For instance, a developer at a retail business might create a table to store product inventory details.

  • ALTER: Modifies existing table structures, such as adding new columns or changing data types, which is common during system upgrades.

  • DROP: Deletes tables or objects that are no longer needed, helping maintain database hygiene.

  • TRUNCATE: Removes all rows from a table quickly without logging individual row deletions, useful for clearing temporary data in test environments.

  • COMMENT: Adds descriptive text to database objects, aiding documentation and maintenance.

Data Manipulation Language (DML)

DML commands handle the management of data within tables.

  • SELECT: Retrieves data from one or more tables, supporting filtering, sorting, and aggregation. For example, a university registrar uses SELECT queries to generate student grade reports.

  • INSERT: Adds new rows of data into tables, such as entering new customer records in a SACCO database.

  • UPDATE: Modifies existing data, like changing the status of loan applications after approval.

  • DELETE: Removes records, for instance deleting outdated inventory entries in a supermarket database.

  • MERGE: Combines data from source tables into a target table, used in data warehousing scenarios.

Data Control Language (DCL)

DCL commands regulate access to data and database operations.

  • GRANT: Provides specific privileges to users or roles, such as allowing a bank clerk to update customer profiles.

  • REVOKE: Removes previously granted permissions, essential for maintaining security when users change roles.

  • DENY: Explicitly denies permissions, overriding granted privileges in some database systems.

  • These commands help institutions like county governments comply with data access policies.

Transaction Control Language (TCL)

TCL commands manage database transactions to ensure data consistency and integrity.

  • BEGIN TRANSACTION: Marks the start of a transaction block where multiple operations are treated as a single unit.

  • COMMIT: Saves all changes made during the transaction permanently to the database.

  • ROLLBACK: Reverts all changes made during the transaction if errors occur.

  • SAVEPOINT: Creates intermediate points within a transaction for partial rollbacks.

  • These commands are vital in financial applications such as loan disbursement systems to prevent data corruption.

Query Components and Clauses

SQL queries are constructed using various clauses that specify data retrieval conditions and manipulations.

  • FROM: Specifies the tables to query from.

  • WHERE: Filters rows based on conditions.

  • GROUP BY: Aggregates data by one or more columns.

  • HAVING: Filters groups based on aggregate conditions.

  • ORDER BY: Sorts the result set.

  • For example, a data analyst at a county health department might write a query using these clauses to analyze disease incidence by region and month.

Practice Questions

  1. Define Structured Query Language (SQL) and explain its role in database management systems. (5 marks)

  2. Describe five key characteristics of SQL that make it suitable for managing relational databases. (10 marks)

  3. Explain the main components of SQL and provide two examples of commands under each component. (15 marks)

  4. Discuss how transaction control commands in SQL contribute to data integrity, illustrating with an example from the banking sector. (10 marks)

The rest of this chapter
🔒

Create a free account to open more of this chapter.

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒3.2 Data Definition Queries

Data definition queries in Structured Query Language (SQL) are essential for creating, modifying, and deleting database structures such as tables, indexes, and schemas. In the Kenyan context, software developers and database administrators working in instituti…

🔒3.3 Demonstration of CREATE TABLE Statement

In Kenyan computer science environments, mastery of the CREATE TABLE statement is fundamental for database design and implementation. Whether developing applications for financial institutions like KCB, managing patient records at county hospitals, or supporti…

🔒3.4 Demonstration of CREATE TABLE constraints

In database management, constraints are critical rules applied to table columns to enforce data integrity and consistency. In Kenya's growing tech sector, from fintech startups to university research databases, understanding how to apply constraints during tab…

🔒3.5 Editing table schema using SQL ALTER statement

In Kenyan computer science practice, databases often require updates to reflect evolving business or technical needs. The SQL ALTER statement is essential for modifying an existing table's structure without losing stored data, enabling adjustments such as addi…

🔒3.6 Dropping table using SQL DROP TABLE statement

In the context of database management for computer science professionals in Kenya, the ability to remove obsolete or redundant database tables is crucial to maintaining an efficient and organized data environment. The SQL DROP TABLE statement is a powerful com…

🔒3.7 Data manipulation query statements

Data manipulation is fundamental in managing and interacting with databases. The core SQL statements that facilitate this are INSERT, SELECT, UPDATE, and DELETE. These statements allow computer science professionals to add new data, retrieve existing data, mod…

🔒3.8 Data Manipulation Query Statements

Data manipulation query statements are essential tools for computer science professionals working with relational databases in Kenya. These statements enable efficient retrieval, insertion, deletion, and updating of data within database tables, critical for ap…

🔒3.9 SQL Joins

In the realm of database management, especially for Computer Science professionals in Kenya, mastering SQL joins is essential for combining data from multiple tables efficiently. Many business and government applications rely on relational databases where data…

🔒3.10 Create and Query a Database from a Validated ER Model

Database creation from an Entity-Relationship (ER) model is a critical skill for database designers and developers. In Kenya’s IT sector, professionals often start with ER diagrams to model real-world business processes before implementing databases for organi…

🔒3.11 Creating a Simple Join

In database management, combining data from multiple tables is essential for comprehensive analysis and reporting. This process is achieved through joins in Structured Query Language (SQL). For Kenyan computer science professionals working in sectors like bank…

Chapter Summary

This chapter introduced Structured Query Language, commonly known as SQL, defining it as the standard language used for managing and manipulating relational databases. The discussion covered its key characteristics and essential components that enable users to define, manipulate, and control data effectively. Data definition queries were explored in detail, focusing on the CREATE, DROP, and ALTER statements, which are fundamental for creating tables, removing them, and modifying their structure. The chapter provided a demonstration of the CREATE TABLE statement and explained various table constraints such as PRIMARY KEY, FOREIGN KEY, NOT NULL, CHECK, UNIQUE, and DEFAULT, which enforce data integrity. Editing table schemas using the ALTER statement was examined through examples of adding, dropping, and modifying attributes. The DROP TABLE statement was also covered as a means to delete entire tables from the database. Data manipulation query statements including INSERT, SELECT, UPDATE, and DELETE were explained with practical detail on how to retrieve, insert, update, and delete records. Finally, the concept of SQL joins was introduced, defining what joins are and describing their types, followed by exercises on creating and querying databases from validated ER models and constructing simple join queries.

Self-Assessment

🔒 PDFDownload this self-assessment, with answers

A. Written Assessment

  1. What does SQL stand for and what is its primary purpose in database management? (2 marks)
  2. List and explain three key characteristics of SQL that make it suitable for managing relational databases. (3 marks)
🔒20 more in this section.

Chapter Examination Questions

🔒 PDFDownload these examination questions, with worked answers

SECTION A (40 Marks) - Answer ALL Questions

  1. Define Structured Query Language (SQL) and explain its primary purpose in database management systems. (4 marks)
  2. List and explain four key characteristics of SQL that make it suitable for managing relational databases. (4 marks)
🔒18 more in this section.

Chapter Practical Activities

Practical 1: Create and Manipulate a Student Database Using SQL

Computer Science · Level 6
Database Management
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Create a database named StudentDB with two tables stDetails and stMarks, each with specified fields, and perform SQL insertions, updates, and queries as per instructions.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Functional computer installed with MS SQL ServerPlain A4 paper
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Functional computer installed with MS SQL Server1 Pc per Candidate
2Plain A4 paper2 Pcs per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Create Database and Tables
Launched MS SQL Server correctly
(Award 2 marks or zero)
2
Created database named StudentDB
(Award 1 mark for correct database name)
1
Created table stDetails with fields: stID (Primary Key), stName, stGender, stCourse
(Award 1 mark each for correct table name and correct fields)
2
Created table stMarks with fields: stID (Foreign Key), subject, marks
(Award 2 marks for correct table and fields including foreign key)
2
Sub-Total7
TASK 2: Insert Records and Update Tables
Inserted at least 5 records into stDetails with valid data
(Award 2 marks for complete and valid insertions)
2
Inserted at least 10 records into stMarks with valid subject and marks data linked to stDetails
(Award 2 marks for complete and valid insertions)
2
Added a 'total' column to stMarks table
(Award 1 mark for successful ALTER TABLE statement)
1
Added an 'average' column to stMarks table
(Award 1 mark for successful ALTER TABLE statement)
1
Calculated total marks per student and updated 'total' field
(Award 2 marks for correct SQL update with sum aggregation)
2
Calculated average marks per student and updated 'average' field
(Award 2 marks for correct SQL update with average aggregation)
2
Sub-Total10
TASK 3: Query Data
Extracted list of male students enrolled in 'Computer Science' course
(Award 2 marks for correct SELECT with WHERE conditions)
2
Extracted list of students scoring above 75 marks in 'Mathematics'
(Award 2 marks for correct SELECT with JOIN and WHERE conditions)
2
Extracted students with average marks below 50
(Award 2 marks for correct use of WHERE on average field)
2
Created an index on stID field in stDetails table
(Award 1 mark for correct CREATE INDEX statement)
1
Sub-Total7
PRODUCT CHECKLIST
Database StudentDB exists with correctly structured tables stDetails and stMarks
(Award 3 marks for correct table structures and relationships)
3
Tables populated with at least the minimum required valid records
(Award 3 marks for completeness and correctness of inserted data)
3
Total and average fields correctly calculated and updated in stMarks table
(Award 4 marks for accuracy of calculations and stored values)
4
SQL queries return correct and expected results as per task requirements
(Award 5 marks for correct query outputs)
5
Index on stID field created and functional
(Award 3 marks for correct index creation and functionality)
3
Sub-Total18
GRAND TOTAL42
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)

Practical 2: Create and Query a Student Database Using SQL

Computer Science · Level 6
Database Management
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Create a database named StudentDB with tables StudentDetails and StudentScores, each with specified fields, and perform SQL queries to extract required information.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Functional computer installed with MS SQL ServerPlain A4 paper
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Functional computer installed with MS SQL Server1 Pc per Candidate
2Plain A4 paper2 Sheets per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Database and Tables Creation
Launched MS SQL Server correctly
(Award 2 marks or zero)
2
Created database named StudentDB
(Award 3 marks or zero)
3
Created table StudentDetails with fields StudentID (Primary Key), FirstName, LastName, Gender, and Class
(Award 4 marks or zero)
4
Created table StudentScores with fields ScoreID (Primary Key), StudentID (Foreign Key), Subject, and Score
(Award 4 marks or zero)
4
Sub-Total13
TASK 2: Data Insertion
Inserted at least 5 records into StudentDetails table
(Award 1 mark per correct record, max 4)
4
Inserted at least 10 records into StudentScores table with valid StudentID references
(Award 1 mark per correct record, max 5)
5
Sub-Total9
TASK 3: SQL Querying
Extracted list of male students in Class 3A
(Award 3 marks or zero)
3
Extracted list of students who scored more than 70 in Mathematics
(Award 3 marks or zero)
3
Extracted average score per subject from StudentScores
(Award 4 marks or zero)
4
Created a view named HighScorers for students scoring above 80 in any subject
(Award 4 marks or zero)
4
Sub-Total14
PRODUCT CHECKLIST
Database structure correctly created with required tables and fields
(Award 6 marks or zero)
6
Data accurately inserted with valid records and referential integrity
(Award 6 marks or zero)
6
SQL queries executed correctly producing accurate results
(Award 6 marks or zero)
6
Sub-Total18
GRAND TOTAL54
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)
🔒

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒Create and Query a Student Database Demonstrating SQL CharacteristicsPractical 3
🔒Create and Manipulate Database Components Using SQLPractical 4
🔒Create and manage database tables using data definition queriesPractical 5
🔒Create a Student Database with Tables and Records Using SQLPractical 6
🔒Drop Table Using SQL in a Student DatabasePractical 7
🔒Alter a Database Table Structure Using SQL ALTER StatementPractical 8
🔒Demonstrate creation of a Students database with CREATE TABLE statementsPractical 9
🔒Create a Students Table with Proper SQL ConstraintsPractical 10
🔒Create a Database with Primary Key ConstraintsPractical 11
🔒Create a Database with Foreign Key Constraint for Employee and Department TablesPractical 12
🔒Create and manage a NOT NULL constrained database tablePractical 13
🔒Create and Query a Student Database Using SQLPractical 14
🔒Create and manage a UNIQUE database with UNIQUE constraintsPractical 15
🔒Create and manage a student database using SQLPractical 16
🔒Editing Table Schema Using SQL ALTER StatementPractical 17
🔒Adding an attribute to a student database tablePractical 18
🔒Dropping an attribute from a database table using SQLPractical 19
🔒Modify Attribute Domain in Customer DatabasePractical 20
🔒Dropping a table using SQL DROP TABLE statementPractical 21
🔒Data Manipulation Queries on Student DatabasePractical 22
🔒Insert records into Customers and Orders tables in SalesDBPractical 23
🔒SQL SELECT Queries on Student DatabasePractical 24
🔒Update records in a student databasePractical 25
🔒Delete Specific Records from Student DatabasePractical 26
🔒Data Manipulation Query Statements on Student Records DatabasePractical 27
🔒Retrieve patient records using SQL SELECT statementsPractical 28
🔒Insertion of Records into Student Database Using INSERT INTO StatementsPractical 29
🔒Deleting Records Using DELETE Statement in Student DatabasePractical 30
🔒Update Student Records Using SQL UPDATE SET StatementPractical 31
🔒Create and Query Database Using SQL JoinsPractical 32
🔒Definition and Implementation of a Join in SQLPractical 33
🔒Perform SQL queries demonstrating types of joinsPractical 34
🔒Create and Query a Student Database from a Validated ER ModelPractical 35
🔒Create a simple SQL join query to combine employee and department dataPractical 36
Flashcards 20 cards Study deck ▾
Question
1

↻ Tap card to reveal answer
🔒

18 more in this section.

Create a free account
Test Yourself 19 questions Start quiz ▾
0%
0 / 2
🔒

17 more in this section.

Create a free account
Am I competent?

At the start of this chapter we promised you would be able to:

  • Apply Structured Query Language (SQL) correctly to manage and interact with databases.
  • Create a database from a validated Entity-Relationship (ER) model and query it using proper procedures.
  • Use SQL joins effectively to combine and retrieve data from multiple tables.
  • Define and manage database structures by applying data definition queries in SQL.
  • Create tables accurately using the SQL CREATE TABLE statement.
  • Enforce data rules by applying constraints within the CREATE TABLE statement.
  • Edit table schemas precisely using the SQL ALTER TABLE statement.
  • Safely remove tables when needed using the SQL DROP TABLE statement.
  • Modify and manipulate data correctly using SQL data manipulation statements.

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.