.
Sql
Constraint
The constraint in MySQL is used to specify the rule that allows or restricts what values/data will
be stored in the table.
ensure data accuracy and integrity inside the table.
helps to limit the type of data that will be inserted inside the table.
If any interruption occurs between the constraint and data action, the action is failed.
Two way to apply constraint
1)using create
2)using alter
○ NOT NULL
○ CHECK: ensures that the inserted value in a column must be satisfied with the
given condition. In other words, it determines whether the value associated with
the column is valid or not with the given condition.
○ DEFAULT:-constraint is used to set the default value for the particular column
where we have not specified any value.
○ PRIMARY KEY:-identify each record in a table uniquely. it cannot be null or empty.
A table can contain only one primary key. It always contains unique value into a
column.
○ AUTO_INCREMENT:-automatically generates a unique number whenever we
insert a new record into the table. Generally, we use this constraint for the
primary key field in a table.
○ UNIQUE:- all values inserted into the column will be unique. Icannot stores
duplicate values. more than one column with UNIQUE constraint in a table.
○ FOREIGN KEY:-constraint is used to link two tables together. It is also known as
the referencing key. A foreign key column matches the primary key field of
another table. It means a foreign key field in one table refers to the primary key
field of another [Link] also lets us decide what to do ON UPDATE and ON
DELETE actions performed on the rows of the primary table.
Primary key on parent table and foreign key on child table
CASCADE option automatically deletes or updates matching rows in the child table when deleting or
updating rows in the parent table.
CREATE TABLE child ( id INT, parent_id INT, INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id) ON UPDATE CASCADE ON DELETE
CASCADE )
create table order1 (id int auto_increment,name varchar(23) not null unique,age int
check(age>=18),clg varchar(23) default 'sia',primary key(id));
create table pro1(p_id int primary key,id int,foreign key(id) references order1(id) on
update cascade on delete cascade);
alter table pro1 drop primary key;
alter table pro1 modify column p_id int primary key;
For unique:
alter table pro1 modify column p_id int unique;
alter table pro1 drop index p_id;
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
alter table order1 drop check order1_chk_1;
Joins:-A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
Inner join
Inner join
is used when we want to display matching records from two tables.
ON keyword to tell the database which columns should be used for matching
the records
INNER JOIN only displays records that are available in both tables.
Outer join
returns all records from both tables that satisfy the join condition. In other words, this
join will not return only the matching record but also return all unmatched rows from
one or both tables.
○ LEFT OUTER JOIN
○ RIGHT OUTER JOIN
○ FULL OUTER JOIN
Left outer join
retrieves all the records from the left table and matching rows from the right table. It
will return NULL when no matching record is found in the right side table. Since OUTER
is an optional keyword, it is also known as LEFT JOIN.
Outer left
Write a query to display all customers irrespective of
items bought or not. Display the name of the customer,
and the item bought. If nothing is bought, display NULL.
outer_right
RIGHT OUTER JOIN retrieves all the records from the right-hand table and matched
rows from the left-hand table. It will return NULL when no matching record is found in
the left-hand table. Since OUTER is an optional keyword, it is also known as RIGHT JOIN.
Write a query to get all the items bought by customers,
even if the customer does not exist in the Customer
database. Display customer name and item name. If a
customer doesn’t exist, display NULL.
SELECT [Link], Shopping_Details.Item_Name
FROM Customers RIGHT OUTER JOIN Shopping_Details;
ON [Link] = Shopping_Details.ID;
FULL OUTER JOIN
The FULL OUTER JOIN in SQL Server returns a result that includes all rows from both
tables. The columns of the right-hand table return NULL when no matching records are
found in the left-hand table. And if no matching records are found in the right-hand
table, the left-hand table column returns NULL.
The below visual representation illustrates the FULL OUTER JOIN:
Write a query to provide data for all customers and items
ever bought from the store. Display the name of the
customer and the item name. If either data does not
exist, display NULL.
Query
SELECT [Link], Shopping_Details.Item_Name
FROM Customers FULL OUTER JOIN Shopping_Details
WHERE [Link] = Shopping_Details.ID;
Self Join
The SQL Self Join is used to join a table to itself as if the table were two tables. To
carry this out, at least one table is temporarily renamed in the SQL statement.
Self Join is a type of inner join, which is performed in cases where the comparison
between two columns of a same table is required; probably to establish a relationship
between them. In other words, a table is joined with itself when it contains both
Foreign Key and Primary Key in it.
CROSS JOIN in SQL Server combines all of the possibilities of two or more tables and
returns a result that includes every row from all contributing tables. It's also known as
CARTESIAN JOIN because it produces the Cartesian product of all linked tables. The
Cartesian product represents all rows present in the first table multiplied by all rows
present in the second table.
The below visual representation illustrates the CROSS JOIN. It will give all the records
from table1 and table2 wIn SQL, CROSS JOINs are used to combine each row of one
table with each row of another table, and return the Cartesian product of the sets of
rows from the tables that are joined.
When to use the CROSS JOIN?
The CROSS JOIN query in SQL is used to generate all combinations of records in two
tables.
here each row is the combination of rows of both tables:
SELECT Student.admission_no, Student.first_name, Student.last_name,
[Link], Fee.amount_paid FROM Student CROSS JOIN Fee
WHERE Student.admission_no = Fee.admission_no;
subQUERY
A MySQL subquery is a query nested within another query such as SELECT, INSERT,
UPDATE or DELETE. Also, a subquery can be nested within another subquery.
A MySQL subquery is called an inner query while the query that contains the subquery is
called an outer query.
SubQuery
A subquery is a nested query (inner query) that’s used to filter the results of
the outer query. Subqueries can be used as an alternative to joins. A
subquery is typically nested inside the WHERE clause.
SELECT, INSERT, UPDATE or DELETE statement along with the various operators
Difference in joins and subquery?
An SQL Join statement is used to combine data or rows from two or more
tables based on a common field between [Link] statement is used to A
subquery is a query that is nested inside a SELECT, INSERT, UPDATE, or
DELETE statement, or inside another subquery.
Joins and subqueries are both used to combine data from different tables into
a single result.
select * from order where c_ id in (select c_id from customer where
c_name="jagruti" );
select * from employee where c_ id not in (select c_id from customer where
c_name="jagruti" );
insert into history select * from employee;
delete from employee where id in ( select id from history where
name="jagruti");
Stored Procedure
collection of pre-compiled SQL statements stored inside the database. , UPDATE ,
ohelp group one or multiple SQL statements for reuse under a common name,
encapsulating common business logic within the database itself.
CALL command:- use to call stored procedure.
1) Increases the performances of application
2) Reduce the traffic between application and database server becoz application
sent only the sp name and parameter instead of sending multiple sql statement
3) reusable
Has three modes:
1) IN parameter:-
2) OUT parameter
3) INOUT parameter
delimiter &&
create procedure get_new()
begin
select * from history;
end&&
delimiter ;
call get_new();
1)IN
delimiter &&
create procedure get_new1(in var int)
begin
select * from history where id=var;
end&&
delimiter ;
call get_new1(1);
2)OUT:-It is used to pass a parameter as output. Its value can be changed inside
the stored procedure, and the changed (new) value is passed back to the calling
program. It
delimiter &&
create procedure get_new6(OUT var int)
begin
select COUNT(id) into var from history ;
end&&
delimiter ;
call get_new6(@M);
select @M;
3)INOUT
delimiter &&
create procedure get_new8(INOUT var int)
begin
select salary into var from history where id=var ;
end&&
delimiter ;
set @M='1';
call get_new8(@M);
select @M;
Drop the stored procedure
DROP PROCEDURE get_new1;
[Link]
d-procedure
Trigger
show triggers;
SHOW TABLES FROM database_name;
drop trigger login.before_insert_empworkinghours;
CREATE TABLE employee(
name varchar(45) NOT NULL,
occupation varchar(35) NOT NULL,
working_date date,
working_hours varchar(10)
);
INSERT INTO employee VALUES
('Robin', 'Scientist', '2020-10-04', 12),
('Warner', 'Engineer', '2020-10-04', 10),
('Peter', 'Actor', '2020-10-04', 13),
('Marco', 'Doctor', '2020-10-04', 14),
('Brayden', 'Teacher', '2020-10-04', 12),
('Antonio', 'Business', '2020-10-04', 11);
DELIMITER //
Create Trigger before_insert_empworkinghours
BEFORE INSERT ON employee FOR EACH ROW
BEGIN
IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
END IF;
END //
INSERT INTO employee VALUES
('Markus', 'Former', '2020-10-08', 14);
INSERT INTO employee VALUES
('Alexander', 'Actor', '2020-10-012', -13);
select * from employee;
CREATE TABLE employee(
name varchar(45) NOT NULL,
occupation varchar(35) NOT NULL,
working_date date,
working_hours varchar(10)
);
DELIMITER //
create trigger befor_insert_occupation
before insert on employee for each row
begin
if [Link]='it' then set [Link]='developer';
end if;
end//
INSERT INTO employee VALUES
('Markus', 'it', '2020-10-08', 14);
Trigger can be defined on table,veiw,schema or database with which is event is
associated
Benefits of triggers
Triggers can be written for the following purposes-
1) Gain strong control over security
2) Enforcing referential integrity
3) Event logging and storing information on table access.
4) Auditing
5) Synchronous replication of table
6) Preventing invalid transaction
Syntax of trigger
Create [OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER}
{INSERT[OR] | UPDATE [OR] |DELETE}
ON table_name
[FOR EACH ROW]
DECLARE
Declaration-statements
BEGIN
Executable-statements
END;
Create [OR REPLACE] TRIGGER trigger_name :- create or replace an exiting
trigger with trigger name.
{BEFORE | AFTER} :- this is specifies when the trigger will be executed.
{INSERT[OR] | UPDATE [OR] |DELETE} :-specifies dml operation
ON table_name :-name of the table associated with the trigger.
[FOR EACH ROW] :- this specifies a row-level trigger, i.e. the trigger will be
executed for each row being affected. Otherwise the trigger will execute just
once when sql statement is executed, which is called a table level trigger
DELIMITER //
Create Trigger before_insert_occupation
BEFORE INSERT ON employee1 FOR EACH ROW
BEGIN
IF [Link] = 'Scientist' THEN SET [Link] = 'Doctor';
END IF;
END //
How to call the BEFORE INSERT trigger?
INSERT INTO employee1 VALUES
('Alexander', 'Actor', '2020-10-012', 13);
INSERT INTO employee1 VALUES
('Markus', 'Scientist', '2020-10-08', 14);
//trigger occur before insert wneh scientist inserted
Restrictions
○ We can access and change the NEW values only in a BEFORE INSERT trigger.
○ We cannot access the OLD If we try to access the OLD values, we will get an error
because OLD values do not exist.
○ We cannot create a BEFORE INSERT trigger on a VIEW.
AFTER INSERT Trigger
After Insert Trigger in MySQL is invoked automatically whenever an insert event occurs
on the table.
Restriction:-
1)can access the NEW values but cannot change them
2) cannot access the OLD If we try to access the OLD values, we will get an error
because there is no OLD on the INSERT trigger.
3) cannot create the AFTER INSERT trigger on a VIEW.
CREATE TABLE student_info (
stud_id int NOT NULL,
stud_code varchar(15) DEFAULT NULL,
stud_name varchar(35) DEFAULT NULL,
subject varchar(25) DEFAULT NULL,
marks int DEFAULT NULL,
phone varchar(15) DEFAULT NULL,
PRIMARY KEY (stud_id)
CREATE TABLE student_detail (
stud_id int NOT NULL,
stud_code varchar(15) DEFAULT NULL,
stud_name varchar(35) DEFAULT NULL,
subject varchar(25) DEFAULT NULL,
marks int DEFAULT NULL,
phone varchar(15) DEFAULT NULL,
Lasinserted Time,
PRIMARY KEY (stud_id)
);
DELIMITER //
CREATE Trigger after_insert_details
AFTER INSERT ON student_info FOR EACH ROW
BEGIN
insert into student_detail values
(new.stud_id,new.stud_code,new.stud_name,[Link],[Link],[Link],CURTIM
E());
END //
How to call the AFTER INSERT trigger?
INSERT INTO student_info VALUES
(10, 110, 'Alexandar', 'Biology', 67, '2347346438');
BEFORE UPDATE Trigger
invoked automatically whenever an update operation is fired on the table associated
with the trigger.
Restrictions
○ We cannot update the OLD values in a BEFORE UPDATE trigger.
○ We can change the NEW values.
○ We cannot create a BEFORE UPDATE trigger on a VIEW.
CREATE TABLE sales_info (
id INT AUTO_INCREMENT,
product VARCHAR(100) NOT NULL,
quantity INT NOT NULL DEFAULT 0,
fiscalYear SMALLINT NOT NULL,
CHECK(fiscalYear BETWEEN 2000 and 2050),
CHECK (quantity >=0),
UNIQUE(product, fiscalYear),
PRIMARY KEY(id)
);
INSERT INTO sales_info(product, quantity, fiscalYear)
VALUES
('2003 Maruti Suzuki',110, 2020),
('2015 Avenger', 120,2020),
('2018 Honda Shine', 150,2020),
('2014 Apache', 150,2020);
DELIMITER $$
CREATE TRIGGER before_update_salesinfo
before update
on sales_info for each row
begin
declare error_msg varchar(255);
SET error_msg = ('The new quantity cannot be greater than 2 times the current
quantity');
if [Link]>[Link] * 2 then
SIGNAL SQLSTATE '45000'
set MESSAGE_TEXT=error_msg;
END IF;
END $$
DELIMITER ;
How to call the BEFORE UPDATE trigger?
UPDATE sales_info SET quantity = 125 WHERE id = 2;
UPDATE sales_info SET quantity = 600 WHERE id = 2; //it will fetch exception cause
quantity is 2 times greater than current quantity.
SIGNAL SQLSTATE statement to raise a custom exception or error condition. The SIGNAL
SQLSTATE statement allows you to specify a custom error message and a SQL state
code, which can provide more specific information about the error.
'45000' is a SQL state code. You can choose an appropriate SQL state code or use
'45000', which is a generic code for user-defined exceptions.
AFTER UPDATE TRIGGER
AFTER UPDATE trigger in MySQL is invoked automatically whenever an UPDATE event is
fired on the table associated with the triggers.
Restrictions
○ We can access the OLD rows but cannot update them.
○ We can access the NEW rows but cannot update them.
○ We cannot create an AFTER UPDATE trigger on a VIEW.
CREATE TABLE students(
id int NOT NULL AUTO_INCREMENT,
name varchar(45) NOT NULL,
class int NOT NULL,
email_id varchar(65) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO students (name, class, email_id)
VALUES ('Stephen', 6, 'stephen@[Link]'),
('Bob', 7, 'bob@[Link]'),
('Steven', 8, 'steven@[Link]'),
('Alexandar', 7, 'alexandar@[Link]');
USER() function is used to retrieve the current user name and host for the MySQL
connection. It returns a string in the format 'username'@'hostname'. The USER() function
does not require any arguments and is used within SQL statements or queries to identify
the user who is currently connected to the MySQL server.
CREATE TABLE students_log(
user varchar(45) NOT NULL,
descreptions varchar(65) NOT NULL
);
DELIMITER $$
CREATE TRIGGER after_update_studentinfo
after update
on students for each row
begin
insert into students_log values(user(),concat('update student
record',[Link],[Link],'presnet class',[Link]));
END $$
DELIMITER ;
How to call the AFTER UPDATE trigger?
SET SQL_SAFE_UPDATES = 0;
UPDATE students SET class = class + 1;
BEFORE DELETE Trigger
BEFORE DELETE Trigger in MySQL is invoked automatically whenever a delete operation
is fired on the table.
Restrictions
○ We can access the OLD rows but cannot update them in a BEFORE DELETE
trigger.
○ We cannot access the NEW rows. It is because there are no new row exists.
○ We cannot create a BEFORE DELETE trigger on a VIEW.
CREATE TABLE salaries (
emp_num INT PRIMARY KEY,
valid_from DATE NOT NULL,
amount DEC(8 , 2 ) NOT NULL DEFAULT 0
);
INSERT INTO salaries (emp_num, valid_from, amount)
VALUES
(102, '2020-01-10', 45000),
(103, '2020-01-10', 65000),
(105, '2020-01-10', 55000),
(107, '2020-01-10', 70000),
(109, '2020-01-10', 40000);
CREATE TABLE salary_archives (
id INT PRIMARY KEY AUTO_INCREMENT,
emp_num INT,
valid_from DATE NOT NULL,
amount DEC(18 , 2 ) NOT NULL DEFAULT 0,
deleted_time TIMESTAMP DEFAULT NOW()
);
DELIMITER $$
CREATE TRIGGER before_delete_salaries
before delete on salaries for each row
begin
insert into salary_archives (emp_num, valid_from, amount)
values(old.emp_num,old.valid_from,[Link]);
END $$
DELIMITER ;
How to call the BEFORE DELETE trigger?
delete from salaries where emp_num=105;
SELECT * FROM salary_archives;
AFTER DELETE Trigger
The AFTER DELETE Trigger in MySQL is invoked automatically whenever a delete event
is fired on the table.
Restrictions
○ We can access the OLD rows but cannot update them in the AFTER DELETE
trigger.
○ We cannot access the NEW rows. It is because there are no NEW row exists.
○ We cannot create an AFTER DELETE trigger on a VIEW.
CREATE TABLE total_salary_budget(
total_budget DECIMAL(10,2) NOT NULL
);
SUM() function that returns the total salary from the salaries table and keep this
information in the total_salary_budget table:
insert into total_salary_budget(total_budget) select sum(amount) from salaries;
DELIMITER $$
CREATE TRIGGER after_delete_salaries
after delete
on salaries for each row
begin
update total_salary_budget set total_budget=total_budget - [Link];
END $$
DELIMITER ;
How to call the AFTER DELETE trigger?
delete from salaries where emp_num=107;