0% found this document useful (0 votes)
13 views

Index, Constraints, Triggers

Indexes can improve database query performance and enable efficient sorting and data retrieval. The document discusses different types of database constraints including primary keys, foreign keys, unique constraints, check constraints, default constraints, and triggers that can automatically execute SQL statements in response to data changes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Index, Constraints, Triggers

Indexes can improve database query performance and enable efficient sorting and data retrieval. The document discusses different types of database constraints including primary keys, foreign keys, unique constraints, check constraints, default constraints, and triggers that can automatically execute SQL statements in response to data changes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Index

Indexes can be created using one or more columns of a database table, providing the basis for both
rapid random lookups and efficient access of ordered records

The advantages of indexes are as follows:


 Their use in queries usually results in much better performance.
 They make it possible to quickly retrieve (fetch) data.
 They can be used for sorting. A post-fetch-sort operation can be eliminated.
 Unique indexes guarantee uniquely identifiable records in the databas

alter table zest_books.orders add index


Order_Date(Order_Date );

Types of Constraints
Primary Key Constraint
A primary key constraint can be used to make a record in database table unique. While deigning a
primary key it must not be empty, i.e., it cannot contain NULL values. Only one primary key given to a
table .

NOT NULL Constraint


Note that when you add a NOT NULL constraint to a column, you cannot insert NULL values into that
column. If you try to insert a NULL value into a column with a NOT NULL constraint, you will get an error.

ALTER TABLE table_name MODIFY column_name data_type NOT NULL;

Alter table orders modify Order_Date Date NOT NULL

FOREIGN Key Constraint


Foreign Key constraints are used to connect two database tables. A foreign key column can be value of a
primary key in another table in the database .

Unique Constraint
The UNIQUE Constraint does not allow two records to have same values in a column

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name);

Alter table customer add CONSTRAINT unique_name UNIQUE(cust_name)


Check Constraint

The CHECK constraint is used to limit the value range that can be placed in a
column.

If you define a CHECK constraint on a column it will allow only certain values for
this column.

ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (condition);


ALTER TABLE books ADD CONSTRAINT price_check CHECK (Book_price >=50)
Default Constraint
Table named Customer with columns Custid , Cust_Name, and Cust_Address,
where Cust_Address has a default value of “RAK”:
CREATE TABLE Customer ( Custid int PRIMARY KEY, Cust_Name VARCHAR(200)
DEFAULT “John”, Cust_Address varchar(100) DEFAULT “RAK” );

Alter table Customer alter Cust_Address set default “RAK”


Trigger
Trigger is a set of SQL statements that automatically "fires" or executes when a specific event
occurs on a table. These events can be INSERT, UPDATE, or DELETE operations on the table.
Triggers are often used to enforce data integrity rules, perform checking of values, or automate
tasks related to database changes.

Here are the key components and concepts related to triggers in MySQL:

Event: The event is the action that triggers the execution of the trigger. In MySQL, triggers
can be associated with INSERT, UPDATE, or DELETE operations on a table.
Timing: Triggers can be defined to execute either before or after the event that triggers
them. Before triggers execute before the event, while after triggers execute after the event.
Trigger Body: The trigger body contains the SQL statements that are executed when the
trigger is activated. These statements can be any valid SQL statements, including SELECT,
INSERT, UPDATE, DELETE, or even CALL to stored procedures.
Trigger Conditions: Triggers can be defined to activate only under certain conditions. These
conditions are specified using a WHEN clause, and the trigger will only execute if the
condition evaluates to true.
Trigger Activation: Triggers are activated automatically when the defined event occurs on
the associated table. There's no need to explicitly call a trigger; it is invoked by the database
system when the specified condition is met.
Trigger Management: Triggers can be created, altered, or dropped using SQL commands.
They are associated with a specific table and remain in effect until they are explicitly dropped.

AFTER Trigger
An after trigger, on the other hand, executes after the triggering event has occurred. These
triggers are commonly used for logging changes, auditing, or performing actions after the data
modification has taken place.

After trigger can be used to create a Trigger after insert on orders table to reduce
quantity of the books table identified by Book_id

Definition
BEGIN
DECLARE book_id INT;
DECLARE order_quantity INT;
-- Get the book_id and order_quantity from the newly inserted order
SELECT NEW.Book_id, NEW.Quantity INTO book_id, order_quantity;

-- Update the Books table to reduce the quantity by the ordered amount
UPDATE Books
SET quantity = quantity - order_quantity
WHERE Book_id = book_id;
END

Before Triggers (BEFORE INSERT/UPDATE/DELETE):

A before trigger, is a trigger that executes before the triggering event occurs. These
triggers are useful for enforcing business rules, performing data validation, or modifying
values before they are written to the table.

To enforce a business rule that prevents inserting orders with a quantity greater
than the available quantity of a book in the Books table, use a before insert
trigger to validate it.

DELIMITER //
CREATE TRIGGER before_insert_order
BEFORE INSERT ON Orders
FOR EACH ROW
BEGIN
DECLARE available_quantity INT;
SELECT quantity INTO available_quantity
FROM Books
WHERE Book_id = NEW.Book_id;
IF NEW.Quantity > available_quantity THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Quantity ordered exceeds available quantity';
END IF;
END;
//
DELIMITER ;

You might also like