You are on page 1of 35

Introduction

to
Advanced Sql
Purpose of Joining Tables
1. Data Retrieval: JOINs allow you to fetch data from multiple tables in a single query. This is useful
when the data needed for analysis or presentation is spread across different tables.

2. Data Integrity: By establishing relationships between tables, JOINs help maintain data integrity.
They ensure that related data is properly linked together, preventing inconsistencies and errors in
the database.

3. Efficient Data Access: JOINs enable efficient data retrieval by allowing the database engine to
optimize the query execution plan. By joining tables on related columns, the database can minimize
the amount of data processed and retrieved, leading to faster query performance.

4. Complex Querying: JOINs facilitate complex querying operations such as aggregations, filtering,
and sorting across multiple tables. They allow you to combine data from different sources and
perform operations on the combined dataset.

5. Normalization: Normalizing a database often involves splitting data into multiple tables to
eliminate redundancy and improve data integrity. JOINs are necessary to reconstruct the original
data from these normalized tables when querying the database.
Example

We have the following tables in a database:

Students Table: Courses Table:

• student_id (Primary Key) • course_id (Primary Key)


• student_name • course_name
• student_age • course_description
• student_grade • student_id (Foreign Key referencing student_id in Students table)
Let's say we want to generate a report showing the names of students along with the courses they
are enrolled in.
Imagine the number of students in your school. Without JOINs, it would be challenging to combine
the information from both tables effectively.
Here's how we could achieve this using a JOIN (specifically an INNER JOIN):

SELECT Students.student_name, Courses.course_name


FROM Students
INNER JOIN Courses ON Students.student_id = Courses.student_id;

INNER JOIN: This specifies that we want to combine rows from both tables where there is a match between the
student_id column in the Students table and the student_id column in the Courses table.

Students.student_name and Courses.course_name: These columns are selected for display in the final
result set.

With this query, we can now see the names of students along with the courses they are enrolled
in. This demonstrates to students why JOINs are necessary to retrieve information from multiple
tables and how they can be used to combine related data effectively.
Student_id Student_name Student_age Student_grade Course_id Course_name Course_description Student_id

2001 Charles 16 1.75 001 DIT InfoTech 2001


2002 Luke 17 1.00 002 DFPT FoodTech 2002
2003 Bob 16 2.00 003 DTLED EduTech 2003
2004 James 18 3.00 001 DIT InfoTech 2004
2005 Kevin 18 1.25 001 DIT InfoTech 2005
2006 Rhea 17 2.50 002 DFPT FoodTech 2006
2007 Liz 16 2.75 002 DFPT FoodTech 2007
2008 Gavin 16 1.00 003 DTLED EduTech 2008
2009 Warren 17 5.00 003 DTLED EduTech 2009
Purpose of Stored Procedures
1. Modularity and Reusability: Stored procedures encapsulate SQL statements into a single unit,
making them reusable across multiple parts of an application. Once created, stored procedures can
be invoked repeatedly without having to rewrite the SQL logic each time.

2. Improved Performance: Stored procedures can improve performance by reducing the amount of
data transferred between the database server and the client application. By executing complex SQL
operations on the server side, stored procedures can minimize network traffic and optimize query
execution plans.

3. Enhanced Security: Stored procedures can help enhance security by controlling access to the
database. Users can be granted permission to execute specific stored procedures while being
restricted from directly accessing the underlying tables. This allows for better control over who can
perform which operations on the database.

4. Encapsulation of Business Logic: Stored procedures allow developers to encapsulate complex


business logic directly within the database. This promotes data integrity and consistency by ensuring
that critical operations are performed uniformly, regardless of the application accessing the
database.
Purpose of Stored Procedures

5. Transaction Management: Stored procedures enable transaction management within the


database. They can initiate, commit, or rollback transactions, ensuring data integrity and consistency
in multi-step operations.

6. Reduced Network Traffic: Since the SQL logic is stored and executed on the database server,
stored procedures can reduce network traffic by sending only the procedure invocation and
receiving the result set, rather than sending multiple SQL statements back and forth between the
client and server.

7. Ease of Maintenance: Stored procedures provide a centralized location for SQL logic, making it
easier to maintain and update. Changes to the database schema or business rules can be
implemented in the stored procedures without requiring modifications to the application code.
Example

Assume we have a table named Grades with the following structure:

• student_id (Student ID)


• subject (Name of the subject)
• grade (Grade obtained by the student)

We want to create a stored procedure that takes the student_id as input and returns the average
grade for that student across all subjects.
Here's how we can create such a stored procedure:

DELIMITER //

CREATE PROCEDURE CalculateAverageGrade (IN studentID INT)


BEGIN
DECLARE avgGrade DECIMAL(5,2);

SELECT AVG(grade) INTO avgGrade


FROM Grades
WHERE student_id = studentID;

SELECT CONCAT('Average grade for student ', studentID, ' is: ',
avgGrade) AS Result;
END //

DELIMITER ;
• DELIMITER //: This changes the delimiter used for defining the stored procedure. It's necessary because the
standard delimiter (;) is used within the stored procedure itself.

• CREATE PROCEDURE CalculateAverageGrade (IN studentID INT): This line defines the stored procedure
named CalculateAverageGrade, which accepts an input parameter studentID of type integer.

• BEGIN...END: This block contains the body of the stored procedure.


• DECLARE avgGrade DECIMAL(5,2);: This line declares a variable avgGrade of type DECIMAL(5,2) to store the
calculated average grade.

• SELECT AVG(grade) INTO avgGrade FROM Grades WHERE student_id = studentID;: This SQL statement
calculates the average grade for the specified studentID by selecting the average of grade from the Grades table
where the student_id matches the input parameter.

• SELECT CONCAT('Average grade for student ', studentID, ' is: ', avgGrade) AS Result;: This statement returns
the result of the stored procedure as a concatenated string showing the average grade for the student.
Purpose of Triggers
Triggers in SQL serve as a mechanism for automatically executing a set of SQL statements in response
to certain events occurring in the database. These events can include data manipulation operations
(e.g., INSERT, UPDATE, DELETE) on specific tables. The primary purposes of triggers in SQL are as
follows:

1. Enforcing Data Integrity: Triggers can enforce data integrity rules by automatically validating or
modifying data before or after it is inserted, updated, or deleted from a table. This helps ensure that the
data remains consistent and accurate according to the defined business rules.

2. Auditing and Logging: Triggers can be used to log changes made to the database, providing an audit
trail of all data modifications. By capturing information such as who made the change, what data was
modified, and when the change occurred, triggers facilitate tracking and monitoring of database activities
for compliance and troubleshooting purposes.

3. Maintaining Derived Data: Triggers can maintain derived or calculated data in the database by
automatically updating related tables when certain data changes occur. For example, a trigger can
recalculate summary values or update denormalized data structures to reflect changes in underlying
data.
4. Implementing Business Logic: Triggers allow for the implementation of complex business logic
directly within the database. They enable the enforcement of specific business rules or workflows by
executing custom SQL logic in response to predefined events, reducing the need for application-
level validation and ensuring consistency across different applications accessing the database.

5. Synchronization with External Systems: Triggers can synchronize data between the database
and external systems by automatically performing data transformations or triggering actions in
response to changes in the database. This enables seamless integration with other systems or
applications, ensuring data consistency across multiple platforms.

6. Cascading Actions: Triggers can initiate cascading actions in response to data modifications,
such as updating related tables, deleting dependent records, or triggering additional operations.
This helps maintain referential integrity and ensures that changes made to one table are reflected
appropriately in related tables.

7. Security Enforcement: Triggers can enforce security policies by restricting or controlling


access to certain data based on predefined criteria. They can deny unauthorized operations,
enforce access controls, or perform additional authentication checks before allowing data
modifications to proceed.
Scenario: In a university database, there's a table named Grades that stores students' grades for
various courses. We want to implement a trigger that automatically updates a student's overall GPA
(Grade Point Average) whenever a new grade is inserted or updated in the Grades table.

Objective: We'll create a trigger that calculates the overall GPA of a student whenever a new grade is
inserted or updated in the Grades table.
Tables:

Grades: Contains student grades for different courses.


Students: Contains student information including their overall GPA.

Steps:

Create a Trigger: We'll create a trigger that fires after each insert or update operation on the Grades table.
Calculate GPA: Inside the trigger, we'll calculate the overall GPA of the student based on their grades in
different courses.
Update Student's GPA: Finally, we'll update the student's overall GPA in the Students table.
CREATE TRIGGER UpdateGPA
AFTER INSERT ON Grades


FOR EACH ROW
BEGIN CREATE A TRIGGER
DECLARE total_credits INT;
DECLARE total_grade_points DECIMAL(5, 2);
DECLARE new_gpa DECIMAL(5, 2);

-- Calculate total credits and grade points for the student


SELECT SUM(course_credits), SUM(grade * course_credits)
INTO total_credits, total_grade_points
FROM Grades


WHERE student_id = NEW.student_id;
CALCULATE GPA
-- Calculate GPA
IF total_credits > 0 THEN
SET new_gpa = total_grade_points / total_credits;
ELSE
SET new_gpa = 0; -- To handle the case when there are no grades yet
END IF;

-- Update student's GPA


UPDATE Students
SET gpa = new_gpa
WHERE student_id = NEW.student_id;
END;
UPDATE GPA ✓
MySQL Events
• MySQL events, commonly known as scheduled events, are the tasks that
are executed according to a specified schedule.
• MySQL events are similar to cron jobs on Linux or task schedulers on
Windows, providing a tool to automate recurring tasks within the MySQL
database server.

For example, you can create an event to optimize all tables in a database,
scheduling it to run at 1:00 AM every Sunday.
• Events are also known as “temporal triggers” because they are triggered
by time, not by the changes made to tables like triggers.
• To schedule and execute events, MySQL uses an event scheduler that
continuously monitors events and ensures their timely execution.
MySQL event lifecycle
Here’s the typical lifecycle of an event:

• Creation – MySQL allows you to create an event using the CREATE EVENT statement.
Like other database objects, MySQL stores events in the event scheduler.
• Activation – after defining an event, you need to explicitly activate it using the ALTER
EVENT ... ENABLE statement.
• Modification – You can modify an event using the ALTER EVENT statement to change
attributes such as the schedule or the SQL statements to be executed.
• Deactivation – The stop the event, you can deactivate it using the ALTER EVENT ...
DISABLE statement.
• Removal – If an event is no longer in use, you can remove it by using the DROP
EVENT statement.
MySQL event scheduler configuration
MySQL uses a special thread called an event scheduler thread to execute all scheduled events. You can view the
status of the event scheduler thread by executing the SHOW PROCESSLIST command:
SHOW PROCESSLIST;
Output:

The output shows that the event scheduler is currently running.


If the event scheduler is not enabled, you can set the event_scheduler system variable to ON to enable and start it:
SET GLOBAL event_scheduler = ON;
To disable and stop the event scheduler thread, you can set event_scheduler system variable to OFF:
SET GLOBAL event_scheduler = OFF;
Use cases of MySQL events
In practice, you’ll find events useful in the following cases:
• Data backup
Events can be used to automate regular data backups to ensure the safety and
recoverability of critical data.
• Data purging
Events allow you to schedule tasks to automatically remove outdated data, optimizing
database performance.
• Reporting
Events allow you to generate periodic reports or statistical analyses during off-peak hours.
• Maintenance tasks
Events allow automating routine maintenance tasks such as index rebuilding or table
optimization to keep the database running efficiently.
To create a new event,
you use The CREATE EVENT statement. Here’s the basic syntax of the CREATE
EVENT statement:
CREATE EVENT [IF NOT EXIST] event_name
ON SCHEDULE schedule
DO
event_body

In this syntax:
• First, specify the name of the event that you want to create after the CREATE EVENT keywords. The event names must be unique
within the same database.
• Second, specify a schedule after the ON SCHEDULE keywords.

If the event is a one-time event, you use the syntax:


AT timestamp [+ INTERVAL]Code language: SQL (Structured Query Language) (sql)If the event is a recurring event, you use the EVERY clause:
EVERY interval STARTS timestamp [+INTERVAL] ENDS timestamp [+INTERVAL]Code language: SQL (Structured Query Language)
(sql)The STARTS specifies when the event starts repeating and the ENDS specifies when the event stops repeating.

• Third, place an SQL statement to execute after the DO keyword.


If you have multiple statements, you can use the BEGIN...END block. Please note that you can call a stored procedure inside the body of an
event.
ALTER EVENT
MySQL allows you to change various attributes of an existing event using the ALTER EVENT statement. Here’s the basic
syntax of the ALTER EVENT statement:

ALTER EVENT [IF EXISTS] event_name


ON SCHEDULE schedule
[ON COMPLETION [NOT] PRESERVE]
[COMMENT 'comment']
[ENABLE | DISABLE]
DO event_body

In this syntax:

• IF EXISTS: This optional clause prevents an error from occurring if the specified event does not exist.
• event_name: The name of the event you want to change.
• ON SCHEDULE: Specifies the new schedule for the event, including frequency, start time, and end time.
• ON COMPLETION: Indicates whether you want to preserve or drop the event after it is completed.
Use PRESERVE to keep the event, and NOT PRESERVE to drop it.
• COMMENT 'comment': An optional comment describing the event.
• ENABLE | DISABLE: Allows you to enable or disable the event. Note that a disabled event will not run until you re-
enable it.
• DO event_body: Specifies the new SQL statement(s) or procedure to be executed by the event.
DROP EVENT
Here’s the basic syntax of the DROP EVENT statement:

DROP EVENT [IF EXISTS] event_name [, event_name] ...;Code language: SQL (Structured
Query Language) (sql)

In this syntax:
• IF EXISTS: An optional clause that prevents an error from occurring if the specified
event does not exist.
• event_name: The name of the event you want to drop. You can specify multiple
events, separated by commas.
Note that you can use the wildcard % in the event name to remove all the events that
match a specific pattern.
To perform the DROP EVENT statement, you need to have EVENT privilege for the
database to which the event belongs.
SHOW EVENTS
The SHOW EVENTS statement allows you to retrieve information about scheduled events within a
database.

Here’s the basic syntax of the SHOW EVENTS statement:

SHOW EVENTS [FROM db_name] [LIKE 'pattern' | WHERE expr];Code language: SQL (Structured Query
Language) (sql)

In this syntax:

• FROM db_name (optional): specify the database name after the SHOW EVENT keywords to instruct
from which database you want to show the events. If you omit the FROM clause, the statement
shows events from the current database.
• LIKE 'pattern' (optional): allow you to filter the events based on a pattern. You can include
wildcards (% and _) in the pattern.
• WHERE expr (optional): allow you to form a more complex condition to filter the events, including
event status.
The SHOW EVENTS statement returns the output that includes the following fields:
Field Name Meaning
Db The timestamp indicates when the event was created or started.
Name The name of the event. This is the identifier you assigned.
Definer The MySQL account that defined the event (username@host).
Time Zone The time zone associated with the event’s schedule.
Type Indicates whether the event is one-time or recurring.
Execute At For recurring events, the next execution time; for one-time events, the scheduled execution time.
Interval Value The timestamp indicates when the event was created or started.
Interval Field The unit of time for the interval (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND).
Starts The timestamp indicating when the event was created or started.
Ends For recurring events, when the event is scheduled to end; for one-time events, it is NULL.
Status The current status of the event (ENABLED or DISABLED).
Originator The server ID of the MySQL server on which the event was created; used in replication.
Character_set_client The value of the character_set_client system variable at the time the event was created.
Collation_connection The value of the collation_connection system variable at the time the event was created.
Database Collation The collation of the database with which the event is associated.
This query returns data from both tables customers and payments using the inner join:

MySQL Views
Let’s see the following tables customers and payments from the sample database.

This query returns data from both tables customers and payments using the inner join:

SELECT
customerName,
checkNumber,
paymentDate,
amount
FROM
customers
INNER JOIN
payments USING (customerNumber);
Here is the output:
To create a new view you use the CREATE VIEW statement.

CREATE VIEW customerPayments


AS
SELECT
customerName,
checkNumber,
paymentDate,
amount
FROM
customers
INNER JOIN
payments USING (customerNumber);
MySQL allows you to create a view based on a SELECT statement that
retrieves data from one or more tables
For example, you can create a view called daysofweek that return 7 days a week
CREATE VIEW daysofweek (day) AS
SELECT 'Mon'
UNION
SELECT 'Tue'
UNION
SELECT 'Web'
UNION
SELECT 'Thu'
UNION
SELECT 'Fri'
UNION
SELECT 'Sat'
UNION
SELECT 'Sun';
You can query data from the daysofweek view
SELECT * FROM daysofweek;
Advantages of MySQL Views
1.) Simplify complex query
Views help simplify complex queries. If you have any frequently used complex query, you can create a view based on it so that you can reference the view by using a
simple SELECT statement instead of typing the query all over again.

2) Make the business logic consistent


Suppose you have to repeatedly write the same formula in every query. Or you have a query that has complex business logic. To make this logic consistent across queries, you
can use a view to store the calculation and hide the complexity.

3) Add extra security layers


A table may expose a lot of data including sensitive data such as personal and banking information.
By using views and privileges, you can limit which data users can access by exposing only the necessary data to them.

For example, the table employees may contain SSN and address information, which should be accessible by the HR department only.

To expose general information such as first name, last name, and gender to the General Administration (GA) department, you can create a view based on these columns and
grant the users of the GA department the view, not the entire table employees .

4) Enable backward compatibility


In legacy systems, views can enable backward compatibility.
Suppose, you want to normalize a big table into many smaller ones. And you don’t want to impact the current applications that reference the table.
In this case, you can create a view whose name is the same as the table based on the new tables so that all applications can reference the view as if it were a table.
MySQL Index
MySQL uses indexes to rapidly locate rows
with specific column values. Without an
index, MySQL must scan the entire table to
find the relevant rows. The larger the table,
the slower the search becomes.
Section 1. Creating and Managing MySQL indexes
This section explains what an index is and shows you how
to create, modify, and drop an index.

• Creating indexes – introduce the index concept and


show you how to create an index for one or more
columns of a table.
• Removing indexes – show you how to remove an
existing index of a table.
• Listing table indexes – provide you with a statement to
list all indexes or specific indexes of a table.
Section 2. MySQL Index Types
• Unique indexes – use unique indexes to ensure distinct values stored in a column.
• Prefix indexes – show you how to use the prefix index to create an index for a
character string column.
• Invisible indexes – cover the index visibility and show you how to make an index visible
or invisible.
• Descending indexes – show you how to use descending indexes to increase query
performance.
• Composite indexes – illustrate the application of composite indexes and show you
when to use them to speed up your queries.
• Clustered indexes – explain the clustered indexes in InnoDB tables.
• Index cardinality – explain the index cardinality and show you how to view it using the
show indexes command.
• Functional index – learn how to create an index based on the result of an expression or
function.
Section 3. MySQL Index Hints
This section introduces the index hints that you can use when
the query optimizer doesn’t choose the most efficient index for
your specific query, or when you want to test with different
index options to improve query performance.

• USE INDEX hint – show you how to use the USE INDEX hint
to instruct the query optimizer to use the only list of
specified indexes to find rows in a table.
• FORCE INDEX hint – show you how to use the FORCE INDEX
hint to force the query optimizer to use specified indexes to
select data from a table.
Alubijid | Balubal | Cagayan de Oro | Claveria | Jasaan | Oroquieta | Panaon | Villanueva

Home of the Trailblazers

You might also like