2. Contents
Set 1 : CREATE Database, Table, Records, USE and DROP Database
Set 2: USE Database, Create Table, Index, Perform Queries
Set 3: SELECT-FROM-WHERE-GROUP BY-HAVING-ORDER BY-LIMIT
Set 4: SQL Functions
Set 5: JOINS - INNER,LEFT,RIGHT,CROSS,FULL OUTER
Set 6: Subqueries (Queries within Queries)
Set 7: USER and PRIVILEGES - Grant and Revoke
Set 8: STORED PROCEDURES
Set 9: TRANSACTIONS- Commit, Rollback, Savepoint, Rollback To Savepoint
Set 10: TRIGGERS
Set 11: VIEW
Monthly Back Up Plan: Full and Incremental Backup
6. Set 1: CREATE, USE, DROP – Database, Table & Records
Create, Use and Drop Database
>> create database msdb;
>> use msdb;
>> drop msdb;
Create, Drop and Modify Table
>>create table country (countryID int, countryname varchar(45), countryPopulation int,
countryLanguage varchar(45), primary key(countryID));
>> ALTER TABLE country ADD countryNoState varchar(45); -- adding column using ALTER TABLE
>> ALTER TABLE country ALTER COLUMN countryNoState int; -- changing column Data Type
>> ALTER TABLE country DROP COLUMN countryNoState; -- dropping column
7. Set 2:USE Database, Create Table, Index and Write Queries
INSERT data into tables
>> insert into country values (1,'USA', 123456789, 'English', 50);
>> insert into country values (2,'China', 912346789, 'Mandarin', 40);
>> insert into country values (3,'India', 812345789, 'Hindi', 30);
>> insert into country values (4,'Brazil', 13456789, 'Portuguese', 15);
SELECT data FROM tables
>> SELECT * FROM country;
>> SELECT countryname, countrylanguage
FROM country;
>> SELECT countryname, countrylanguage
FROM country
WHERE countrynostate > 30;
8. Set 2 : Cont’ed…
UPDATE data into tables
>> update country
set countrypopulation=534267
WHERE countryID=3;
>> update country
set countrylanguage='Español'
WHERE countryID=1;
DELETE data FROM tables
>> delete FROM country
WHERE countryID=4;
9. Set 2 : Cont’ed…
Example: (using create index statement)
>> create index accountNumber on mydb.accountdetail(CustomerAccountNumber);
>> create index customerFName on mydb.customerdetail(CustomerFirstName);
>> create index contactNumber on mydb.customeraddresscontact(Customercontact);
>> create index customerLName on mydb.customerdetail(CustomerLastName);
INDEX
- To speed up searches and reduce the time to execute complex queries
- Faster read, slower write
- Index must be updated when table is updated
- Index require additional space
Types of Index
Primary Key – unique but NULL not allowed
Foreign Key – primary key in some other table
Regular – permits duplicate and NULL values
Unique – unique and NULL allowed
Full-text – defined only on CHAR, VARCHAR and TEXT columns
10. Set 3: SELECT-FROM-WHERE-GROUP BY-HAVING-
ORDER BY-LIMIT
ORDER BY
>> SELECT CustomerID,`First Name`,`Last Name`, `Address Line`,
City,State,Country
FROM `View_CustomerDetail`
ORDER BY city;
LIMIT clause
>> SELECT CustomerID,`First Name`,`Last Name`,`Address Line`,
City,State,Country
FROM`View_CustomerDetail`
ORDER BY city
LIMIT 5;
11. Set 3 : Cont’ed…
GROUP BY
>> SELECT city, state, count(*) as Total
FROM `View_CustomerDetail`
GROUP BY city, State;
HAVING
>> SELECT employeedetail.EmployeeFirstName,
COUNT(accountdetail.AccountID) AS NumberOfCustomer
FROM accountdetailINNER
JOIN employeedetail
ON accountdetail.VerifyingEmployeeID=Employeedetail.EmployeeID
GROUP BY EmployeeFirstNameHAVING
COUNT(accountdetail.AccountID) >= 1;
12. Set 4: SQL Functions
COMPARISON FUNCTION
GREATEST( )
>> SELECT EmployeeFirstName, EmployeeLastName, EmployeeDesignation,EmployeeManagerID
FROM employeedetail
WHERE EmployeeManagerID=greatest(8,9,11,7);
CONTROL FLOW FUNCTION
CASE( )
>> SELECT CustomerID, customerdetail.CustomerFirstName,
CASE
WHEN customerfirstname='Hawkins'
THEN '----Available in the List----‘
ELSE '*****Not available *****‘
END
FROM customerdetail;
STRING FUNCTION
CONCAT_WS( ) / CONCAT( ) FUNCTION
>> SELECT concat_ws('------> ', customerfirstname, customerLastName) FROM customerdetail;
>> SELECT concat(customerfirstname, customerLastName) FROM customerdetail;
13. Set 4 : Cont’ed…
NUMERIC FUNCTION
FLOOR( ), CELING( )
>> select accountdetail.CurrentBalance as Actual,
floor(accountdetail.CurrentBalance) as Floor, ceiling(accountdetail.CurrentBalance)
as CEILING
from accountdetail;
DATE( )/TIME( ) FUNCTION
>> select transactiondetail.TransactionID, transactiondetail.TransactionTimestamp
as `Timestamp`,
DATE(transactiondetail.TransactionTimestamp) as `Date`,
YEAR(transactiondetail.TransactionTimestamp) as`Year`,
MONTH(transactiondetail.TransactionTimestamp) as `Month`,
DAY(transactiondetail.TransactionTimestamp) as `Day`,
TIME(transactiondetail.TransactionTimestamp) as `Time`,
HOUR(transactiondetail.TransactionTimestamp) as `Hour`,
MINUTE(transactiondetail.TransactionTimestamp) as `Minute`,
SECOND(transactiondetail.TransactionTimestamp) as `Second`
from transactiondetail;
14. Set 4 : Cont’ed….
SUMMARIZING FUNCTION
AVG( )
>> select avg(CurrentBalance) as 'Average Balance of Customer‘
from accountdetail;
SUM( )
>> select sum(CurrentBalance) as 'Total Amount‘
from accountdetail;
15. Set 4 : Cont’ed….
MAX( )
>> select accountid, CurrentBalance as 'Maximum Balance‘
from accountdetail
where CurrentBalance=(select max(CurrentBalance) from accountdetail);
MIN( )
>> select accountid, CurrentBalance as 'Minimum Balance‘
from accountdetail
where CurrentBalance=(select min(CurrentBalance) from accountdetail);
16. Set 5: JOINS - INNER,LEFT,RIGHT,CROSS,FULL OUTER
INNER
Combines result from BOTH side of table on the condition given in ON clause
>> select trans1.AccountID, trans1.TransactionAmount as AmountTransfered,
trans1.TransactionBalance as AccountBalance
from transactiondetail as trans1
inner join accountdetail as acnt
on trans1.AccountID=acnt.AccountID
where trans1.AccountID=(select accountdetail.AccountID from accountdetail where
accountdetail.CustomerAccountNumber='GE71499928852933330509');
RIGHT
All records from RIGHT side of OUTER JOIN statement are returned regardless of values on left side
>> select AccountID, EmployeeID, EmployeeDesignation
from mydb.employeedetail
RIGHT JOIN accountdetail
on employeedetail.EmployeeID=accountdetail.VerifyingEmployeeID
order by AccountID;
17. Set 5 : Cont’ed…
LEFT JOIN
All records from LEFT side of OUTER JOIN statement are returned regardless of
values on right side
Example:
>> select AccountID,EmployeeID, EmployeeLastName, EmployeeDesignation
from mydb.accountdetail
RIGHT JOIN employeedetail
on employeedetail.EmployeeID=accountdetail.VerifyingEmployeeID;
18. Set 5 : Cont’ed…
CROSS JOIN
It is a join without ON clause
all the rows from all the tables listed in the join are included
Example:
>> Select BranchID, BranchName, zipcodedetail.Zipcode
from branchdetail, zipcodedetail
order by BranchID;
FULL JOIN: does not exist in MySQL
Cross Join
19. Set 6: Subqueries (Queries within Queries)
Definition:
Used to access multiple tables from within SQL statement
Can be added on SELECT,DELETE,UPDATE only
Powerful when used with operators like IN,ANY,SOME,ALL
Subquery can contain JOIN, HAVING,WHERE,GROUP BY
Consume a lot of processing, disk, memory resourses
Example:
>> select accountid, CurrentBalance as 'Maximum Balance‘
from accountdetail
where CurrentBalance=(select max(CurrentBalance) from accountdetail) ;
20. Set 7: USER and PRIVILEGES - Grant and Revoke
Query to create USER:
>> create user admin1@localhost identified by 'admin';
grant select , insert, update, delete on accountdetail to admin1@localhost;
grant select , insert, update, delete on branchdetail to admin1@localhost;
grant select , insert, update, delete on customeraddresscontact to admin1@localhost;
grant select , insert, update, delete on customerdetail to admin1@localhost;
grant select , insert, update, delete on employeedetail to admin1@localhost;
grant select , insert, update, delete on nomineeaddresscontact to admin1@localhost;
grant select , insert, update, delete on nomineedetail to admin1@localhost;
grant select , insert, update, delete on transactiondetail to admin1@localhost;
grant select , insert, update, delete on zipcodedetail to admin1@localhost;
Granting Privileges to VIEW
>> grant select on CustomerViewBanking to admin1@localhost;
Query to drop USER
>> drop user customer@localhost;
21. Set 7 : Cont’ed…
Query to create USER:
>> create user tester@localhost identified by 'tester';
grant select , insert, update on accountdetail to tester@localhost;
grant select , insert, update on branchdetail to tester@localhost;
grant select , insert, update on customeraddresscontact to tester@localhost;
grant select , insert, update on customerdetail to tester@localhost;
grant select , insert, update on employeedetail to tester@localhost;
grant select , insert, update on nomineeaddresscontact to tester@localhost;
grant select , insert, update on nomineedetail to tester@localhost;
grant select , insert, update on transactiondetail to tester@localhost;
grant select , insert, update on zipcodedetail to tester@localhost;
22. Set 7 : Cont’ed…
Query to create USER:
>> create user customer@localhost identified by 'customer';
grant select on accountdetail to customer@localhost;
grant select , insert, update on customeraddresscontact to customer@localhost;
grant select , insert, update on customerdetail to customer@localhost;
grant select , insert, update on nomineeaddresscontact to customer@localhost;
grant select , insert, update on nomineedetail to customer@localhost;
DENY for customer AND APPROVED for admin
>> insert into accountdetail values ('1616651D51651S61CE', '2012-12-12', 10000, 'Active', 18, 5);
It will revoke SELECT grant on accountdetails
>> REVOKE select ON accountdetail FROM customer@localhost;
Now it won’t SELECT data from table because we REVOKED access to SELECT the table
>> select * from mydb.accountdetail;
Query to drop USER
>> drop user customer@localhost;
23. Set 7 : Cont’ed…
Query to create USER:
>> create user 'developer'@'localhost' identified by 'developer';
grant select , insert, update on accountdetail to developer@localhost;
grant select , insert, update on branchdetail to developer@localhost;
grant select , insert, update on customeraddresscontact to developer@localhost;
grant select , insert, update on customerdetail to developer@localhost;
grant select , insert, update on employeedetail to developer@localhost;
grant select , insert, update on nomineeaddresscontact to developer@localhost;
grant select , insert, update on nomineedetail to developer@localhost;
grant select , insert, update on transactiondetail to developer@localhost;
grant select , insert, update on zipcodedetail to developer@localhost;
It will revoke SELECT grant on accountdetails
>> REVOKE insert ON accountdetail FROM developer@localhost;
DENY for customer AND APPROVED for developer
>> INSERT INTO mydb.accountdetail values ('1616651D51651S61CE', '2012-12-12', 10000, 'Active', 18, 5);
24. Set 8: STORED PROCEDURES
Definition:
It is a routine of set of pre-defined SQL statements that takes action on data in database when called.
Used to execute set of SQL statements which is more likely to use again and again
Bypasses some of the steps while executing series of SQL statements repeatedly
It is like user defined function in OOP language.
Also commonly known as ‘sproc’
Advantages:
Improves performance by storing execution plan of SQL statements
Code stored as data in database so it is easy to maintain and back-up with data
Simplifies administration and maintenance in large database project
Logic reusability can be achieved through store procedure
Provide different level of access to different user
Control access to underlying data and structure
Prevents certain actions from damaging database and data in it
25. Set 8 : Cont’ed…
Following is Stored Procedure to make deposit into account
To Create Store Procedure
DELIMITER //
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_deposit`(amountx int, accountIDx int)
main:BEGIN
insert into transactiondetail (transactiontimestamp, transactionAmount,AccountID, transactionbalance)
values (now(), amountx, accountIDx, transactionamount+(select mydb.accountdetail.CurrentBalance from
mydb.accountdetail where accountid=accountIDx));
leave main;
end //
delimiter ;
To run Store Procedure CALL command is used
call proc_deposit(1000,1);
To Drop Store Procedure
drop procedure proc_deposit;
26. Set 8 : Cont’ed…
Following is Stored Procedure to make withdrawal from account
To create Stored Procedure
DELIMITER //
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_withdrawl`(amountx int, accountIDx int)
main:BEGIN
insert into transactiondetail (transactiontimestamp, transactionAmount,AccountID, transactionbalance)
values (now(), amountx, accountIDx, 0-transactionamount+(select TransactionBalance from
mydb.transactiondetail where TransactionID=(select max(TransactionID) from transactiondetail where
AccountID=accountIDx)));
leave main;
end //
delimiter ;
To Run and Drop Stored Procedure
call proc_withdrawl(1000,1);
drop procedure proc_withdrawl;
27. Set 9: TRANSACTIONS- Commit, Rollback, Savepoint,
Rollback To Savepoint
>> Start transaction;
>> call proc_deposit(1000,1);
>> savepoint sp1;
>> call proc_deposit(1000,21);
>> rollback to savepoint sp1;
>> commit;
>> select * from transactiondetail;
START TRANSACTION is used to begin transaction
It increases performance drastically
SAVEPOINT allows to define saving point in transaction
ROLLBACK TO SAVEPOINT allow to rollback a transaction to
specific savepoint mentioned
COMMIT is used to terminate a transaction and to save all
changes in the Database
28. Set 10: TRIGGERS
TRIGGER: It is similar to Stored Procedure but can’t call explicitely. It is reaction to action
performed on table.
create table customer (cID int, cname varchar(45), corderID int, primary key(cID));
create table invetory (invID int, prodID int, cID int,quant int, price int, primary key(invID));
insert into customer values (1,'USA', 123456789);
insert into customer values (2,'China', 912346789);
insert into customer values (3,'India', 812345789);
insert into invetory values (1,812345789, 3, 6, 15);
select * from customer;
select * from invetory;
Query to create TRIGGER:
create trigger newinvetory after insert on inventory
for each row
update customer set corderid=new.invid
where cid=new.cid;
NOW, TRIGGER will be fired after INSERT
insert into invetory values (2,55555, 2, 8, 50);
Before Trigger get fired
After Trigger get fired
29. Set 11: VIEW
VIEW: A virtual table whose definition is stored in the database but that does not actually contain data.
It is a basically SELECT statement stored as a named object.
Query to create VIEW : View_CustomerPersonal
create view `View_CustomerPersonal` as
select cust.CustomerID,cust.CustomerFirstName as `First Name`, cust.CustomerLastName as `Last Name`, cust.CustomerBirthdate as
`Date of Birth`, cust.CustomerSSN as `Social Security`, cust.CustomerOccupation as Occupation, custAddr.CustomerAddress as
`Address Line`, custAddr.CustomerContact as `Contact`, zip.City, zip.State, zip.Country
from customerdetail as cust
left join customeraddresscontact as custAddr on cust.CustomerAddressID=custAddr.CustomerAddressID
left join zipcodedetail as zip on custAddr.Zipcode=zip.Zipcode;
Query to select and drop VIEW
select * from View_CustomerPersonal;
drop view `View_CustomerPersonal`;
30. Set 11 : Cont’ed
Following is the VIEW created by ‘View_CustomerPersonal’
31. Set 11 : Cont’ed…
Query to create VIEW : View_CustomerNomineePersonal
create view `View_CustomerNomineePersonal` as
select cust.CustomerID,cust.CustomerFirstName as `First Name`, cust.CustomerLastName as `Last Name`, cust.CustomerBirthdate as `Date of Birth`,
cust.CustomerSSN as `Social Security`, cust.CustomerOccupation as Occupation,
concat_ws(' ',nom.NomineeFirstName, nom.NomineeLastName), nom.NomineeBirthdate as Birthdate, nom.NomineeRelation as Relation,
nomAddr.NomineeContact as Contact, nomAddr.NomineeAddress as 'Nominee Address',
zip.City, zip.state, zip.Country
from customerdetail as cust
left join nomineedetail as nom on cust.NomineeID=nom.nomineeID
left join nomineeaddresscontact as nomAddr on nom.NomineeAddressID=nomAddr.NomineeAddressID
left join zipcodedetail as zip on nomAddr.Zipcode=zip.Zipcode;
Query to Select and Drop VIEW
select * from View_CustomerNomineePersonal;
drop view `View_CustomerNomineePersonal`;
32. Set 11 : Cont’ed
Following is the VIEW created by ‘View_CustomerNomineePersonal’
33. Set 11 : Cont’ed…
Query to create VIEW : View_CustomerDetail
create view `View_CustomerDetail` as
select cust.CustomerID,cust.CustomerFirstName as `First Name`, cust.CustomerLastName as `Last Name`, cust.CustomerBirthdate as `Date
of Birth`, cust.CustomerSSN as `Social Security`, cust.CustomerOccupation as Occupation,
custAddr.CustomerAddress as `Address Line`, custAddr.CustomerContact as Contact, zip.City, zip.State, zip.Country,
acnt.CustomerAccountNumber as `Account Number`, acnt.AccountOpeningDate as `Opening Date`, acnt.CurrentBalance as `Current
Balance`, acnt.`Status`,
br.branchname as `Branch`, concat_ws(' ',emp.EmployeeFirstName, emp.EmployeeLastName) as "Verified By"
from customerdetail as cust
left join customeraddresscontact as custAddr on cust.CustomerAddressID=custAddr.CustomerAddressID
left join zipcodedetail as zip on custAddr.Zipcode=zip.Zipcode
left join accountdetail as acnt on cust.AccountID=acnt.AccountID
left join branchdetail as br on acnt.BranchID=br.BranchID
left join employeedetail as emp on acnt.VerifyingEmployeeID=emp.EmployeeID ;
Query to select VIEW
select * from `View_CustomerDetail`;
34. Set 11 : Cont’ed
Following is the VIEW created by ‘View_CustomerDetail’
Query to drop VIEW:
drop view `View_CustomerDetail`;
Granting Privileges to VIEW
grant select on View_CustomerDetail to admin1@localhost;
35. Monthly Back Up Plan: Full and Incremental Backup
Assumptions:
1. Every data generated is important to Bank for analysis and support.
2. Bank works 6 days/week in which Saturday is Half day working
3. Bank prefers weekly auditing of all accounts
4. Full back-up takes more time than incremental back-up
Back-Up Plan for Banking:
1.For the first time, full back of system will be taken
2. Then each day from Monday through Friday daily incremental back-up will be done
3. As working hours are half on Saturday, weekly full back-up will be covered
4. After every two week, one full back-up is planned to reduce monthly back-up load
4. Towards end of month, on nearest Saturday Full Last month back-up will be taken
5. Process will be repeated every month and in the end of year, yearly back-up will be covered.
Back-Up Schedule for complete 1 month is on the next slide….
36. 29 December 30 31 1 2 3/4
5 6 7 8 9 10/11
12 13 14 15 16 17/18
19 20 21 22 23 24/25
26 27 28 29 30 31/1 February
january
2 3 4 5 6 7/8
2015
Monday
First Full Back-Up
1
Tuesday
Daily Incremental
2
Wednesday
Daily Incremental
3
Thursday
Daily Incremental
4
Friday
Daily Incremental
5
Saturday
Weekly Full Back-Up
6
Monday
Daily Incremental
8
Tuesday
Daily Incremental
9
Wednesday
Daily Incremental
10
Thursday
Daily Incremental
11
Friday
Daily Incremental
12
Saturday
Full Back-Up of last Two
weeks
13
Monday
Daily Incremental
15
Tuesday
Daily Incremental
16
Wednesday
Daily Incremental
17
Thursday
Daily Incremental
18
Friday
Daily Incremental
19
Saturday
Weekly Full Back-Up
20
Monday
Daily Incremental
22
Tuesday
Daily Incremental
23
Wednesday
Daily Incremental
24
Thursday
Daily Incremental
25
Friday
Daily Incremental
26
Saturday
Full Back-Up of last Two
weeks
27
Monday
Daily Incremental
28
Tuesday
Daily Incremental
29
Wednesday
Daily Incremental
30
Thursday
Daily Incremental
31
Friday
Daily Incremental
1
Saturday
MONTHLY FULL BACKUP
2
December Month Back-Up Plan for Bank Database
NEXT MONTH
First Saturday of Next Month
37. References
Books:
Beginning MySQL
Beginning SQL
Modern Database Management
Website:
www.w3school.com
www.Wikipedia.com/mysql/
www.Lynda.com/Essential mysql training
Notes:
INFO 6210 : Data Management and Database Design by Prof. Mutsalklisana
38. Thank you !
INFO 6210 : Data Management and
Database Design
Final Exam Presentation
Presented By Ashwinkumar Dinoriya