Professional Documents
Culture Documents
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
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
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.
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
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 //
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.
• 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.
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:
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);
✓
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;
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:
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.
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.
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.
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 .
• 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