0% found this document useful (0 votes)
24 views93 pages

Week 6 and On

This document provides an introduction to SQL and its various commands, covering topics such as managing table structures, retrieving data with SELECT statements, and understanding joins and relationships in databases. It outlines the purpose of SQL, its benefits, and practical use cases across different industries. Additionally, it includes syntax examples and best practices for creating, altering, and querying databases effectively.

Uploaded by

gpam0120
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)
24 views93 pages

Week 6 and On

This document provides an introduction to SQL and its various commands, covering topics such as managing table structures, retrieving data with SELECT statements, and understanding joins and relationships in databases. It outlines the purpose of SQL, its benefits, and practical use cases across different industries. Additionally, it includes syntax examples and best practices for creating, altering, and querying databases effectively.

Uploaded by

gpam0120
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/ 93

Introduction to Database Systems

Week 6-8

Eng. Ayoub Abid


MASTERING SQL
COMMANDS
Outline
Module 1 : Introduction to SQL Module 6 : Working with Strings
• String Functions
Module 2 : Managing Table Structures
• Creating Tables Module 7 : Advanced Data Retrieval
• Altering Tables • Aggregations and Grouping
• Dropping Tables • Subqueries and Nested Queries
• Window Functions
Module 3 : Retrieving Data with SELECT
• Basic SELECT Statements Module 8 : Controlling Access and Transactions
• Filtering Results • User Permissions
• Sorting Data • Transactions
• Locks
Module 4 : Joins and Relationships
• Understanding Type of Joins Module 9: Performance Optimization
• Indexing
Module 5 : Manipulating Data • Query Optimization
• Adding New Data with INSERT
• Updating Existing Data with UPDATE
• Deleting Data with DELETE
MODULE 1:
INTRODUCTION
TO SQL
What is SQL?
• SQL stands for Structured Query Language.
• It is a standardized programming language used for managing and querying relational
databases.
• Developed in the 1970s, SQL has become the backbone of database management and is
widely used across industries.
Purpose of SQL:
• To interact with databases for creating, reading, updating, and deleting data (CRUD
operations).
• To retrieve specific insights from data through complex queries and aggregations.
Use Cases:
• Business Applications: Analyze customer data, track sales, and optimize operations.
• Web Development: Power backend databases for dynamic websites (e.g., e-commerce
platforms).
• Data Science and Analytics: Extract, clean, and transform data for insights.
• Mobile Applications: Store and sync data for apps like messaging and social media.
Benefits of Using SQL:
1.Simplicity: Easy-to-learn syntax, even for beginners.
2.Flexibility: Works with small datasets and enterprise-scale databases.
3.Standardization: Compatible with most relational database systems (e.g., MySQL,
PostgreSQL).
4.Efficiency: Optimized for handling large datasets and complex queries.
Database Components
• Table:
⚬ A table is a collection of data organized into rows and columns, much like a
spreadsheet.
⚬ Each table in a database represents a specific type of data (e.g., customers, orders).
• Row:
⚬ Also known as a record, a row represents a single, unique entry in a table.
⚬ Example: A single customer’s data in a customers table.
• Column:
⚬ Columns define the attributes or fields of a table.
⚬ Example: In a customers table, columns might include customer_id, first_name, email.
• Schema:
⚬ A schema is the blueprint or structure of a database, outlining the organization of
tables, columns, and their relationships.
⚬ It provides context for how data is stored and accessed.
• Relationships:
⚬ Databases often link tables using relationships:
i. One-to-One: A single record in one table corresponds to a single record in another.
ii. One-to-Many: A single record in one table is linked to multiple records in another.
iii. Many-to-Many: Multiple records in one table are linked to multiple records in
another through an intermediary table.
Key Attribute

Entity A Attribute

1 Derived
Attribute

Relationship

N Weak
Key Attribute
1
Associative
Entity Weak Entity
Multi value
attribute
1

N 1
Weak
Entity B Relationship Entity C
Creating a Database in SQL
•Syntax:
CREATE DATABASE database_name;

•Example:
CREATE DATABASE Customers;

•Creates a new database named customers.

Selecting a Database to Work With


•Syntax: USE database_name;

•Switches the active database to database_name.


•Ensures all subsequent SQL operations are performed within the selected database.
•Example:
USE Customers;
Takeaways from Module 1
• SQL is a universal language for managing and querying relational databases.

• Understanding core database concepts like tables, rows, columns, schemas, and
relationships is essential.

• CREATE DATBASE is the command used to create the database.

• USE is the key command to select which database should the commands be run on.
MODULE 2:
MANAGING
TABLE
STRUCTURES
Why Manage Table Structures?

• Tables are the backbone of relational databases,


storing all data in rows and columns.

• Proper table management ensures:


⚬ Data is organized effectively.
⚬ Constraints enforce data integrity.
⚬ The structure can adapt to changing
requirements.
Defining New Tables with CREATE TABLE
Purpose: CREATE TABLE defines a new table in the database.
Syntax:
CREATE TABLE table_name (
column1 data_type constraint,
column2 data_type constraint,
...
);

Data Types:
• INT: Integer numbers.
• VARCHAR(n): Text with up to n characters.
• DATE: Date values.
• BOOLEAN: True/false values.
• Constraints:
⚬ PRIMARY KEY: Ensures unique identification of rows.
⚬ NOT NULL: Prevents empty values in a column.
⚬ UNIQUE: Ensures all values in a column are unique.
Defining New Tables with CREATE TABLE

Example:
Create an ‘employees’ table:

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50),
department VARCHAR(50),
hire_date DATE
);

Defines a table with constraints to ensure data integrity.


Adding Constraints for Data Integrity
Primary Key:
• Uniquely identifies each row.
• Can be a single column or a combination of columns.
Example: CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT NOT NULL,
order_date DATE
);

Composite Primary Key: CREATE TABLE order_items (


order_id INT,
product_id INT,
quantity INT,
PRIMARY KEY (order_id, product_id)
);

CREATE TABLE users (


Unique Constraint: username VARCHAR(50) UNIQUE,
email VARCHAR(100) UNIQUE
);
Modifying Table Structures with ALTER TABLE
Use ALTER TABLE to make structural changes without recreating the
table.

Syntax:
Add a column:
ALTER TABLE table_name ADD column_name data_type;

Modify a column:
ALTER TABLE table_name MODIFY column_name new_data_type;

Drop a column:
ALTER TABLE table_name DROP COLUMN column_name;
Examples:
Add a salary column to employees:

ALTER TABLE employees ADD salary INT;

Modify department to allow 100 characters:

ALTER TABLE employees MODIFY department


VARCHAR(100);

Remove the hire_date column:


ALTER TABLE employees DROP COLUMN hire_date;

Note: Not all SQL dialects support dropping columns.


Removing Tables with DROP TABLE
Use DROP TABLE to permanently delete a table and its data.
Syntax:
DROP TABLE table_name;

Examples:
Delete the old_data table:

DROP TABLE old_data;

WARNING!!!
Irreversible Action: Once executed, the table and its data
cannot be recovered.
Always double-check before using DROP TABLE.
When to Use Table Management Commands

Creating Tables:
• Designing new databases.
• Adding new features to an existing system.
• Altering Tables:
⚬ Adapting to changes in requirements (e.g., new fields, different
data types).
• Dropping Tables:
⚬ Removing obsolete tables to declutter the database.

Best Practices:
• Use clear, descriptive names for tables and columns.
• Document structural changes for team collaboration.
Takeaways from module 2
• Creating Tables:
⚬ Use CREATE TABLE to define structure, data types, and constraints.
⚬ Primary keys and constraints ensure data integrity.

• Altering Tables:
⚬ Use ALTER TABLE to add, modify, or remove columns as needed.

• Dropping Tables:
⚬ Use DROP TABLE cautiously to delete tables permanently.

• Practical Tips:
⚬ Always back up critical tables before making structural changes.
⚬ Test changes on a development database before applying them in
production.
MODULE 3:
RETRIEVING
DATA WITH
SELECT
What is the SELECT Statement?
• The SELECT statement is the most commonly used command in SQL.
• It is used to retrieve data from one or more tables in a database.
• Data retrieved can be customized by specifying columns, filtering rows,
and sorting results.

Basic Syntax:

SELECT column1, column2


FROM table_name;
Retrieving Specific Columns
• You can specify one or more columns to retrieve instead of fetching all
columns (SELECT *).
• This reduces data load and improves query performance.

SELECT first_name, last_name


Example: FROM employees;

This retrieves the first_name and last_name of all


employees.

If you want all columns, use SELECT *, but this is not recommended
unless necessary.
Using (AS) for Readability

• Use AS to assign a temporary name (alias) to columns or tables.


• Aliases make results more readable, especially for calculated fields or
joins.

Syntax: SELECT column_name AS “alias_name”


FROM table_name;

Example:
SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;

• Outputs column headers as "First Name" and "Last Name".


• Enclose temporary names in quotes for names with spaces.
Filtering Results Using WHERE

• The WHERE clause filters rows based on conditions.


• Common operators:
⚬ =: Equal to.
⚬ > or <: Greater or less than.
⚬ LIKE: Pattern matching with % (wildcards).
⚬ IN: Matches values in a list.
Syntax:

SELECT column1
FROM table_name
WHERE condition;
Examples:
SELECT first_name
Equality Check: FROM employees
WHERE department = 'IT';

Retrieves first names of employees in the IT department.

Pattern Matching:
SELECT product_name
FROM products
WHERE product_name LIKE 'A%';

Retrieves products whose names start with "A".

SELECT last_name
Using IN Operator: FROM customers
WHERE city IN ('Tripoli',
'Sabha');

Retrieves customers from Tripoli or Sabha.


Slide 6: Sorting Data with ORDER BY

• Use ORDER BY to sort the results of a query.


• Specify the column(s) to sort by and the order:
⚬ ASC: Ascending (default).
⚬ DESC: Descending.

Syntax:
SELECT column1
FROM table_name
ORDER BY column1 [ASC|DESC];
Examples:
SELECT first_name
• Default (Ascending) Order: FROM employees
ORDER BY first_name;

• Descending Order: SELECT salary


FROM employees
ORDER BY salary DESC;

• Sorting can be applied to multiple columns by separating


them with
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary, first_name DESC;
Eliminating Duplicates with DISTINCT

• Use DISTINCT to fetch unique values from a column.

Syntax: SELECT DISTINCT column1


FROM table_name;

Example: SELECT DISTINCT city


FROM customers;

• Retrieves a list of unique cities from the customers' table.

Helps identify distinct entries in a dataset.


Summarizing Data with Aggregate Functions

• SQL provides built-in functions to calculate


summaries:
⚬ COUNT(): Number of rows.
⚬ SUM(): Total of a numeric column.
⚬ AVG(): Average value.
⚬ MAX()/MIN(): Maximum or minimum value.

• Syntax: SELECT [FUNCTION](column_name)


FROM table_name;
Examples:

SELECT COUNT(*)
• Count Rows:
FROM orders;

⚬ Counts total orders in the orders table.

• Find Maximum Salary: SELECT MAX(salary)


FROM employees;

• Calculate Average Price: SELECT AVG(price)


FROM products;
Combining Multiple Conditions

• Combine multiple conditions using logical operators:


⚬ AND: All conditions must be true.
⚬ OR: At least one condition must be true.
⚬ NOT: Negates a condition.

• Syntax:

SELECT column1
FROM table_name
WHERE condition_1 [OPERATOR] condition_2 ;
Combining Multiple Conditions
SELECT first_name
• Using AND: FROM employees
WHERE department = 'HR' AND salary > 50000;

⚬ Retrieves HR employees earning more than 50,000.

• Using OR: SELECT product_name


FROM products
WHERE category = 'Electronics' OR price < 100;

• Using NOT: SELECT last_name


FROM customers
WHERE NOT city = 'Tripoli';

⚬ Retrieves customers not from Tripoli.


Takeaways from Module 3
• Basic SELECT Statements:
⚬ The SELECT command retrieves data from specific columns or all columns in a
table.
⚬ Use aliases (AS) to improve readability, especially for complex or calculated fields.
• Filtering Results:
⚬ Use the WHERE clause to filter rows based on conditions like =, >, <, LIKE, and IN.
⚬ Combine conditions with AND, OR, and NOT for more advanced filtering.
• Sorting Data:
⚬ Use ORDER BY to sort results in ascending (ASC) or descending (DESC) order.
⚬ Sorting can be applied to multiple columns for fine-tuned ordering.
• Advanced Retrieval Techniques:
⚬ Use DISTINCT to remove duplicate values from the results.
⚬ Aggregate functions like COUNT, SUM, AVG, MAX, and MIN allow for summary-
level insights.
• Efficiency in Query Writing:
⚬ Retrieve only the required data to optimize performance (avoid SELECT * unless
necessary).
⚬ Combining filtering, sorting, and functions can simplify complex data extraction
tasks.
Table-B Table-A

MODULE 4:
JOINS AND
RELATIONSHIPS
What Are Joins?

• Joins allow the combination of rows from two or more


tables based on related columns.
• Essential for relational databases where data is stored
across multiple tables.

• Key use cases:


⚬ Retrieving related data (e.g., customers and their
orders).
⚬ Analyzing data across departments or entities.
Inner Join (INNER JOIN):
Overview of Join Types • Retrieves matching records
from two tables based on a
condition.

Outer Joins:
• LEFT JOIN: All rows from
the left table and matching
rows from the right table.
• RIGHT JOIN: All rows from
Inner Join Left Join
the right table and
matching rows from the
left table.
• FULL JOIN: All rows from
both tables, with
unmatched rows filled with
NULL.

Full Outer Join Right Join


Inner Joins
Definition: Combines rows from two tables where there is a
match in both tables.

Syntax:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Inner Joins Example:
Combine customers and orders to find
customers with orders

customers orders SELECT customers.customer_id, customers.name,


orders.order_id
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id;

Explanation:
Retrieves only those rows where
customer_id exists in both tables.
Outer Joins
Definition: An Outer Join combines rows from two tables,
returning matched rows as well as unmatched rows from one
or both tables.

Syntax:

SELECT columns
FROM table1 [LEFT|RIGHT|FULL] OUTER JOIN table2
ON table1.column = table2.column;
LEFT OUTER JOIN All rows from the left table and matching
rows from the right.
Example:
Retrieve all employees along with their
department names, including the ones that
employees departments
do not belong to any department.

SELECT employees.employee_id, employees.name,


departments.department_name
FROM employees
LEFT JOIN departments
ON employees.department_id = departments.department_id;

Explanation:
Includes employees without departments
(unmatched rows have NULL).
RIGHT OUTER JOIN All rows from the right table and matching
rows from the right.

Example:
Retrieve all customers along with their
employees departments
orders, including customers that do not have
any orders.
SELECT orders.order_id, orders.date, customers.name
FROM orders
RIGHT JOIN customers
ON orders.customer_id = customers.customer_id;

Explanation:
Includes customers with no orders.
Combines all rows from both tables.
FULL OUTER JOIN
Example:
Retrieve all students and their enrolled
courses, including students not enrolled in
students courses
any course and courses with no students
enrolled.

SELECT students.student_id, students.name,


courses.course_name
FROM students
FULL OUTER JOIN courses
ON students.course_id = courses.course_id;

Explanation:
• The query retrieves all students along
with the courses they are enrolled in.
Simplify with Aliases
Aliases give short names to tables or columns for better
readability.
Syntax:

SELECT e.name, d.department_name


FROM employees AS e
INNER JOIN departments AS d
ON e.department_id = d.department_id;

Benefit:
Simplifies long queries, especially with multiple joins.
Takeaways from module 4
• Inner Joins:
⚬ Match records from two tables based on a condition.

• Outer Joins:
⚬ Include unmatched rows (LEFT, RIGHT, FULL).

• Using Aliases:
⚬ Simplify complex queries with short table names.

• Practical Importance:
⚬ Retrieve meaningful insights by connecting related data.

• Best Practices:
⚬ Understand table relationships before using joins.
⚬ Use aliases for clarity in multi-table queries.
MODULE 5:
MANIPULATING
DATA
What is Data Manipulation?
• Data manipulation involves changing the contents of a
database to reflect updates, corrections, or deletions.

• Three key commands:

⚬ INSERT: Adds new data to tables.


⚬ UPDATE: Modifies existing data.
⚬ DELETE: Removes data from tables.

• These commands interact directly with table rows and


columns, making careful usage crucial.
The INSERT Command

• Use INSERT to add one or more rows to a table.


• Supports inserting complete or partial data (for
specific columns).
• Handles missing values with NULL.

• Syntax:

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...);
Examples:
Inserting a Single Row:
INSERT INTO employees (first_name, last_name, department)
VALUES ('Ahmed', 'Mohammed', 'IT');

Adds a new employee to the IT department.

Inserting Multiple Rows:


INSERT INTO products (product_name, price)
VALUES ('Laptop', 1500), ('Tablet', 800);

Adds two products to the products table.

Handling NULL Values:


INSERT INTO customers (name, email)
VALUES ('Ali', NULL);

Leaves the email column empty for "Alice".


The UPDATE Command
• Use UPDATE to modify existing records in a table.

• Always pair with a WHERE clause to target specific rows


(or update all rows deliberately).

• Syntax:

UPDATE table_name SET column1 = value1, column2 = value2


WHERE condition;
Examples:
Updating Specific Rows:
UPDATE employees SET salary = 60000
WHERE employee_id = 101;

Updates the salary for the employee with ID 101.

Updating Multiple Columns:


UPDATE products SET price = 1200, stock = 50
WHERE product_name = 'Laptop';

Updates the price and stock for the "Laptop" product.

Updating All Rows:

UPDATE employees SET department = 'General';

Assigns "General" as the department for all employees (use cautiously!).


The DELETE Command
• Use DELETE to remove records from a table.
• Pair with a WHERE clause to delete specific rows.
• Omitting WHERE deletes all rows in the table.

• Syntax:
DELETE FROM table_name
WHERE condition;
Examples:
Deleting Specific Rows:
DELETE FROM customers
WHERE city = 'Misrata';

Removes all customers located in Los Angeles.

Deleting All Rows:

DELETE FROM orders;

Deletes all orders (table structure remains intact).

Important Note!!:
Always review the WHERE clause carefully to avoid accidental data loss.
The Impact of Omitting WHERE
INSERT: Not applicable; missing WHERE simply adds data.

UPDATE: Updates all rows in the table.


UPDATE employees
SET department = 'General';

Assigns "General" to the department column for every row.

DELETE: Deletes all rows in the table.


DELETE FROM employees;

Erases all employee records, leaving an empty table.

Best Practice:
Always use WHERE unless intentionally targeting the entire table.
MODULE 6:
WORKING WITH
STRINGS
Why Work with Strings in SQL?
• Text fields are common in databases (e.g., names,
addresses, descriptions).

• String functions enable:


⚬ Formatting and cleaning data.
⚬ Extracting relevant information.
⚬ Enhancing readability for reports and outputs.

• Common use cases:


⚬ Standardizing names (e.g., title case).
⚬ Removing unwanted characters.
⚬ Combining fields into a single output.
Combining Strings with CONCAT or ||
Concatenation joins two or more strings into one.
Syntax:
CONCAT(string1, string2, ...);

Examples:
Combine first and last names:

SELECT CONCAT(first_name, ' ', last_name) AS full_name


FROM employees;
Extracting Substrings with SUBSTRING or SUBSTR

• Extracts a portion of a string based on position and


length.
• Syntax:

SUBSTRING(string FROM start FOR length);

SUBSTR(string, start, length);


Examples:
Extract the first three letters of a name:
SELECT SUBSTRING(first_name FROM 1 FOR 3) AS short_name
FROM employees;

Output: Joh for John.

Retrieves the first five characters of email addresses.

SELECT SUBSTR(email, 1, 5)
AS domain_prefix FROM users;
Changing Case with UPPER and LOWER
UPPER: Converts all characters to uppercase.
LOWER: Converts all characters to lowercase.

Examples:
Standardizing email addresses:
SELECT LOWER(email) AS email_lower
FROM users;

Formatting names:
SELECT UPPER(last_name) AS last_name_caps
FROM employees;

Practical Tip:
Use UPPER or LOWER to ensure case consistency, especially for searches.
Removing Extra Spaces and Characters
TRIM: Removes spaces or specified characters from both ends of a string.
LTRIM and RTRIM: Remove spaces or characters from the left or right side only.

Syntax: TRIM([characters FROM] string);

RTRIM(string); LTRIM(string);

Examples:
Remove leading/trailing spaces:
SELECT TRIM(' John ') AS trimmed_name;

Output: John.

Remove specific characters:


SELECT TRIM('-' FROM '-Product-') AS clean_product_name;

Output: Product.
Replacing Substrings with REPLACE
Replaces all occurrences of a substring within a string.
Syntax: REPLACE(string, old_substring, new_substring);

Examples:
Replace domain names in emails:
SELECT REPLACE(email, 'old_domain.com', 'new_domain.com')
AS updated_email FROM users;

Fix formatting issues:


SELECT REPLACE(address, 'St.', 'Street') AS full_address
FROM locations;
Applying String Functions in Real Scenarios
Formatting Names for Reports:

SELECT CONCAT(UPPER(SUBSTR(first_name, 1, 1)),


LOWER(SUBSTR(first_name, 2))) AS formatted_name
FROM employees;

Converts john to John.

Cleaning Data:
SELECT TRIM(' ' FROM phone_number) AS
clean_phone FROM customers;

Removes unnecessary spaces around phone numbers.

Preparing Reports: SELECT CONCAT(first_name, ' ', last_name, ' - ',


UPPER(department)) AS report_line
FROM employees;

Outputs: Ali Mohammed - IT.


Takeaways from module 6
• Core String Functions:
⚬ CONCAT or ||: Combine strings.
⚬ SUBSTRING or SUBSTR: Extract substrings.
⚬ UPPER, LOWER: Change case.
⚬ TRIM, LTRIM, RTRIM: Remove unwanted spaces or characters.
⚬ REPLACE: Replace parts of a string.

• Practical Applications:
⚬ Standardizing data formats.
⚬ Extracting meaningful information from text fields.
⚬ Cleaning and transforming data for reports.

• Practice Tip:
⚬ Experiment with combining string functions for complex
transformations.
MODULE 7:
ADVANCED
DATA RETRIEVAL
Introduction to Aggregations and Grouping

• Aggregations allow calculations over a set of rows, such as


totals, averages, and counts.
• Grouping organizes data into subsets for aggregated
calculations.

• Key Functions for Aggregation:


⚬ COUNT(): Count rows.
⚬ SUM(): Total sum.
⚬ AVG(): Average value.
⚬ MAX() and MIN(): Maximum and minimum values.
Using GROUP BY

Definition: GROUP BY organizes rows into groups based on


specified columns.

Syntax: SELECT column1,


AGGREGATE_FUNCTION(column2)
FROM table_name
GROUP BY column1;
Key Note:
• Every column in the SELECT clause must either be in the
GROUP BY clause or an aggregate function.
Example
Example 1: Calculate total sales per product:

SELECT product_id, SUM(sales) AS total_sales


FROM sales_data
GROUP BY product_id;

Explanation: Groups all rows with the same product_id and calculates the total sales for
each group.

Example 2: Count employees per department:

SELECT department_id, COUNT(employee_id) AS employee_count


FROM employees
GROUP BY department_id;
Using HAVING for Group Filtering
Definition: HAVING filters grouped data, unlike WHERE, which filters individual rows.

Syntax:
SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table_name
GROUP BY column1
HAVING condition;

Example: Find products with total sales greater than 1000:


SELECT product_id, SUM(sales) AS total_sales
FROM sales_data
GROUP BY product_id
HAVING SUM(sales) > 1000;

Comparison:
WHERE filters rows before grouping.
HAVING filters groups after aggregation.
Subqueries: Queries within Queries
• Definition: A subquery is a query embedded within another
query.

• Use Cases:
⚬ Fetch data based on results from another query.
⚬ Perform advanced filtering and calculations.

• Types of Subqueries:
⚬ Single-row Subqueries: Returns one value.
⚬ Multi-row Subqueries: Returns a list of values.
⚬ Correlated Subqueries: Dependent on the outer query.
Examples

Example 1: Find employees earning above the average salary:


SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Example 2: Get customers with orders in the last month:

SELECT customer_id, name


FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE
order_date > '2024-01-01');

Explanation:
The subquery calculates average salary or recent orders, and the outer query uses
these results.
Introduction to Window Functions
• Definition: Window functions perform calculations across a subset of
rows related to the current row.
• Key Use Cases:
⚬ Cumulative totals.
⚬ Ranking rows.
⚬ Moving averages.
• Syntax:

SELECT column1, WINDOW_FUNCTION(column2)


OVER (PARTITION BY column3 ORDER BY column4)
FROM table_name;
Examples
Example 1: Calculate the running total of sales:

SELECT product_id, sales, SUM(sales) OVER


(PARTITION BY product_id ORDER BY date) AS
running_total
FROM sales_data;

Example 2: Rank employees by salary within departments:

SELECT department_id, name, salary, RANK() OVER


(PARTITION BY department_id ORDER BY salary
DESC) AS rank
FROM employees;

Explanation:
• PARTITION BY: Groups rows (like GROUP BY for window functions).
• ORDER BY: Determines calculation order within partitions.
Takeaways for module 7
• Aggregations and Grouping:
⚬ Use GROUP BY to summarize data into meaningful groups.
⚬ Filter groups using HAVING.

• Subqueries:
⚬ Solve complex problems by embedding one query inside another.
⚬ Use for advanced filtering and dynamic conditions.

• Window Functions:
⚬ Perform calculations across a "window" of rows without grouping.
⚬ Commonly used for rankings, running totals, and moving averages.

• Real-World Impact:
⚬ Aggregate and analyze data for reports.
⚬ Perform in-depth data exploration and transformation.

• Best Practices:
⚬ Understand the difference between WHERE and HAVING.
⚬ Optimize subqueries for performance.
⚬ Use window functions where grouping isn’t applicable.
MODULE 8:
CONTROLLING
ACCESS AND
TRANSACTIONS
Why Access Control Matters

• Definition: Access control restricts database operations to


authorized users.

• Importance:
⚬ Protect sensitive data.
⚬ Prevent unauthorized modifications.
⚬ Ensure accountability by assigning roles.
⚬ Access Control in Practice:
⚬ Assign roles to database users (e.g., admin, analyst,
viewer).
⚬ Limit specific actions (e.g., read-only access).
Granting and Revoking Permissions
Granting Permissions:
Use the GRANT command to provide specific rights.

Syntax:

GRANT privilege ON table_name TO user_name;

Example: Allow SELECT on the employees table for user John:

GRANT SELECT ON employees TO Ali;


Granting and Revoking Permissions
Revoking Permissions:
Use the REVOKE command to remove specific rights.

Syntax:

REVOKE privilege ON table_name FROM user_name;

Example: Revoke INSERT on the orders table from user Khadija:

REVOKE INSERT ON orders FROM Khadija;


Common Privileges:

• SELECT: Read data.

• INSERT: Add new data.

• UPDATE: Modify data.

• DELETE: Remove data.


Introduction to Transactions

• Definition: A transaction is a sequence of database


operations that are treated as a single unit.

• Key Properties (ACID):


⚬ Atomicity: All operations succeed or fail together.
⚬ Consistency: Ensures data remains valid.
⚬ Isolation: Transactions don’t interfere with each other.
⚬ Durability: Committed changes are permanent.
Transaction Control Commands
Commands:
• BEGIN or START TRANSACTION: Starts a transaction.
• COMMIT: Saves changes.
• ROLLBACK: Undoes changes since the transaction began.

Syntax:

-- Start the transaction


BEGIN TRANSACTION;
-- Execute SQL statements
SQL Statement 1;
SQL Statement 2; ...
-- Commit the transaction if all statements are successful
COMMIT;
-- Rollback the transaction if any statement fails
ROLLBACK;
Examples
Example1: Updating salaries within a transaction:

BEGIN;
UPDATE employees SET salary = salary * 1.10 WHERE
department = 'Sales';
COMMIT; -- Saves the changes

Example 2: Rolling back changes:

BEGIN;
DELETE FROM orders WHERE order_date < '2020-01-01';
ROLLBACK; -- Undoes the deletion

Key Note:
Use transactions to handle critical operations, ensuring data consistency.
Understanding Locks
Definition: Locks prevent simultaneous access to data to ensure integrity during
transactions.

Types of Locks:
Table Locks: Lock entire tables during operations.
Row Locks: Lock specific rows being modified.

Common Commands:
LOCK TABLES: Prevent other operations on the table.

LOCK TABLES table_name READ; -- or WRITE

UNLOCK TABLES: Release locks.


UNLOCK TABLES;
Example
Locking a table for writing:

LOCK TABLES employees WRITE;


UPDATE employees SET salary = 5000 WHERE id = 1;
UNLOCK TABLES;

Key Note:
Use locks carefully to avoid deadlocks or performance issues.
Takeaways for module 8
• User Permissions:
⚬ Use GRANT and REVOKE to control access effectively.
• Transactions:
⚬ Ensure data integrity with BEGIN, COMMIT, and ROLLBACK.
⚬ Transactions are essential for critical, multi-step operations.
• Locks:
⚬ Use locks to manage concurrent access and avoid data
conflicts.
⚬ Always release locks with UNLOCK TABLES to prevent issues.
• Best Practices:
⚬ Regularly audit permissions for security.
⚬ Use transactions for complex updates to avoid partial
changes.
⚬ Avoid unnecessary locks to minimize performance overhead.
MODULE 9:
PERFORMANCE
OPTIMIZATION
Why Optimize Performance?
• Definition: Performance optimization involves techniques to
ensure database operations run efficiently, even with large
datasets.

• Benefits:
⚬ Reduces query execution time.
⚬ Improves user experience in applications.
⚬ Saves system resources.

• Key Areas of Focus:


⚬ Indexing for faster lookups.
⚬ Writing efficient SQL commands.
⚬ Avoiding unnecessary operations.
What Is Indexing?
• Definition: An index is a database object that improves the
speed of data retrieval.

• How It Works:
⚬ Similar to an index in a book.
⚬ Maps column values to their locations in the table.

• Types of Indexes:
⚬ Primary Index: Automatically created on the primary
key.
⚬ Unique Index: Ensures no duplicate values in a column.
⚬ Composite Index: Covers multiple columns.
Creating Indexes
Syntax:

CREATE INDEX index_name ON table_name (column_name);

Example: Create an index on the last_name column of the employees


table:

CREATE INDEX idx_last_name ON employees (last_name);

Dropping an Index:
DROP INDEX index_name ON table_name;
Writing Efficient SQL Commands
Key Strategies:

• Select Only What You Need:


⚬ Avoid SELECT * unless necessary.
⚬ Specify only required columns.

• Use WHERE Clauses:


⚬ Filter data to reduce the number of rows processed.

• Limit Results:
⚬ Use LIMIT or TOP to fetch only a subset of data.

• Avoid Calculations in WHERE Clauses:


⚬ Move calculations outside the query for better performance.
Mistakes That Slow Down Queries
• Overusing SELECT :
⚬ Fetches unnecessary columns, increasing data transfer time.
• Solution: Specify needed columns.

• Neglecting Indexes:
⚬ Failing to use indexes leads to slower searches.
• Solution: Create indexes on frequently searched columns.

• Using Functions on Indexed Columns:


⚬ Applying functions disables the index.
⚬ Example:
■ -- Avoid this:
SELECT * FROM employees WHERE UPPER(last_name) = 'DOE';

■ -- Use this:
SELECT * FROM employees WHERE last_name = 'Doe';
Mistakes That Slow Down Queries

• Fetching Excessive Data:


⚬ Large result sets increase memory usage.
• Solution: Use pagination with LIMIT.

• Ignoring Joins Optimization:


⚬ Improper joins can lead to slow queries.
• Solution: Use appropriate join types and conditions.
Putting Optimization Into Practice
Scenario 1: Speeding Up Search with Indexes
CREATE INDEX idx_customer_name ON customers (name);
SELECT * FROM customers WHERE name = 'John Doe';

Scenario 2: Efficient Query with WHERE and LIMIT

SELECT product_name, price


FROM products WHERE price > 100 ORDER BY price DESC LIMIT 5;

Scenario 3: Avoiding Calculations in WHERE Clause

-- Inefficient: SELECT * FROM employees WHERE salary * 1.2 > 5000;

-- Optimized: SELECT * FROM employees WHERE salary > 4166.67;


Takeaways for module 9
• Indexing:
⚬ Use indexes for frequently queried columns.
⚬ Remove unused indexes to avoid overhead.

• Efficient Queries:
⚬ Avoid SELECT * and specify required columns.
⚬ Filter data with WHERE and limit rows with LIMIT.

• Common Mistakes:
⚬ Avoid using functions on indexed columns.
⚬ Use proper join strategies for complex queries.

• Testing and Monitoring:


⚬ Regularly test query performance.
⚬ Use tools like EXPLAIN to analyze query execution plans.

You might also like