Week 6 and On
Week 6 and On
Week 6-8
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;
• Understanding core database concepts like tables, rows, columns, schemas, and
relationships is essential.
• USE is the key command to select which database should the commands be run on.
MODULE 2:
MANAGING
TABLE
STRUCTURES
Why Manage Table Structures?
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:
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:
Examples:
Delete the old_data table:
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:
If you want all columns, use SELECT *, but this is not recommended
unless necessary.
Using (AS) for Readability
Example:
SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;
SELECT column1
FROM table_name
WHERE condition;
Examples:
SELECT first_name
Equality Check: FROM employees
WHERE department = 'IT';
Pattern Matching:
SELECT product_name
FROM products
WHERE product_name LIKE 'A%';
SELECT last_name
Using IN Operator: FROM customers
WHERE city IN ('Tripoli',
'Sabha');
Syntax:
SELECT column1
FROM table_name
ORDER BY column1 [ASC|DESC];
Examples:
SELECT first_name
• Default (Ascending) Order: FROM employees
ORDER BY first_name;
SELECT COUNT(*)
• Count Rows:
FROM orders;
• 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;
MODULE 4:
JOINS AND
RELATIONSHIPS
What Are Joins?
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.
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
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.
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.
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:
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.
• Syntax:
• Syntax:
• Syntax:
DELETE FROM table_name
WHERE condition;
Examples:
Deleting Specific Rows:
DELETE FROM customers
WHERE city = 'Misrata';
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.
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).
Examples:
Combine first and last names:
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.
RTRIM(string); LTRIM(string);
Examples:
Remove leading/trailing spaces:
SELECT TRIM(' John ') AS trimmed_name;
Output: John.
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;
Cleaning Data:
SELECT TRIM(' ' FROM phone_number) AS
clean_phone FROM customers;
• 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
Explanation: Groups all rows with the same product_id and calculates the total sales for
each group.
Syntax:
SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table_name
GROUP BY column1
HAVING condition;
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
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:
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
• 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:
Syntax:
Syntax:
BEGIN;
UPDATE employees SET salary = salary * 1.10 WHERE
department = 'Sales';
COMMIT; -- Saves the 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.
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.
• 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:
Dropping an Index:
DROP INDEX index_name ON table_name;
Writing Efficient SQL Commands
Key Strategies:
• Limit Results:
⚬ Use LIMIT or TOP to fetch only a subset of data.
• Neglecting Indexes:
⚬ Failing to use indexes leads to slower searches.
• Solution: Create indexes on frequently searched columns.
■ -- Use this:
SELECT * FROM employees WHERE last_name = 'Doe';
Mistakes That Slow Down Queries
• 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.