Académique Documents
Professionnel Documents
Culture Documents
What is MySQL
MySQL is the most popular Open Source Relational SQL database
management system.
It is a reliable and easy-to-use relational database system.
It is freely available and released under GPL (GNU General Public
License ).
It is available for most of the popular OS.
It can handle very large databases and offers rich and very useful set of
functions.
Connectivity, speed and security make MySQL very suited for accessing
database on a network.
SQL
Structured Query Language is a standard relational database language.
Originally developed by IBM and later became official standard- ANSI-SQL.
SQL language can be split into:
DML: Querying and manipulating data
DDL: Creation and deletion of schemas
Triggers: Actions executed based on some conditions
Embedded SQL
Security and Transaction management
Deleting a table
DROP TABLE
tablename
Alter tables
ALTER TABLE tbl_name ADD [CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...) [ON
DELETE reference_option] [ON UPDATE
reference_option]
ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol;
CREATE TABLE ORDER ADD FOREIGN KEY (cid) REFERENCES
Customer(cid))
Exercises
Create the tables listed below
Student
sid: integer and primary key , sname : string, age: integer
Course
cid: integer and primary key, cname: string, duration: integer
Enrollment
sid: integer and primary key , cid: integer, edate: date
Add a constraint to Enrollment table (after it has been created)
such that sid and cid refer to the corresponding fields of Student
and Course
Insertion
INSERT statement is used to insert data into tables.
INSERT INTO tablename[(columnname,)] VALUES (data1,
);
INSERT INTO Customer VALUES(6,RAM',RAM NAGAR,
CBE)
Updation
UPDATE is used to modify existing records.
UPDATE tablename SET columnname= data [WHERE
condition]
UPDATE Customer SET cname=RAM PRASAD WHERE
cid=1'
10
Deletion
DELETE statement is used to delete rows from a table.
DELETE FROM tablename
[WHERE condition];
11
Exercises
Insert data as specified in the tables below.
Change all the student names to upper case in student table. Hint:
upper(fieldname) returns the value in upper case.
Change Java to Java 1.6
Student
SID
SNAME
AGE
---------------------------------------1
Mary Molle
20
2
John July
21
3
Lilly Lolly
20
4
Bill Will
22
Enrollment
SID
CID
EDATE
----------------------------------1
2
10-07-06
2
2
10-07-06
3
1
01-09-06
4
1
01-04-06
1
1
01-09-06
Course
CID
CNAME DURATION
--------------------------------------1
Java
52
2
RDBMS
30
3
DS
35
12
15
UNION ALL
IN
Op ANY and Op ALL
EXISTS
16
17
Activity
For the query, find the sids of all the students who have taken both
Java and RDBMS courses, would the query below work?
18
Aggregate Operators
COUNT([DISTINCT] a)
SUM([DISTINCT] a)
AVG([DISTINCT] a)
MAX(a)
MIN(a)
19
Exercises
Find the total number of courses.
Find the total number of unique students who have enrolled for a
course.
What is the age of the youngest student?
Find all the courses whose duration is more than any other course
duration.
How many hours at the minimum would it take for anybody to finish
if this person takes all the courses?
What is the average age of a student?
20
Subquery
Two types
Nested: Subquery is executed first and the result of the
subquery is passed on the main queries (typically to it where
clause)
Correlated: The main query is executed first and then the
subquery is executed for every row of the main query.
21
Nested Subquery
ALL and ANY is used in cases where we need to specify the condition
based on all or any one of the records selected.
Find all the course whose duration is more any other course.
SELECT cname FROM course WHERE duration >=
ALL(SELECT duration FROM course )
The IN operator allows us to test whether a given value is in a given set
of elements.
Get all the students name whose sids are 2 and 4.
SELECT sname FROM Student WHERE sid IN(2,4)
22
Find the names of all students who have taken Java course.
23
Correlated Subquery
The correlated subquery has the subquery refer back to the table(s) in
the main query
Find the names of the students whose age is next to the oldest student(s).
select sname,age from student s where 1=(select
count(DISTINCT age) from student s1 where
s.age<s1.age)
EXISTS like IN operator with the difference that the top-level query
executes based on the existence of a record of the subquery.
Find the names of the students who have enrolled for a course on 1
September 2006.
SELECT sname FROM Student s where EXISTS (SELECT *
FROM Enrollment e WHERE e.sid=s.sid AND e.edate='1SEP-2006')
24
Challenge !
Find the names of the students whose age is next to the oldest
student(s).
25
DIVISION
Division operation finds the subset of items in one set that are
related to all items in another set.
There is no straight division operator as such in SQL.
But the there is a way in which such operation are performed using
correlated subqueries.
Find the students who have taken all the courses.
SELECT sid FROM Student s WHERE not exists (
SELECT cid FROM course
MINUS
SELECT cid FROM enrollment e WHERE
e.sid=s.sid)
B
26
Student
SID SNAME
Course
CID CNAME
SID CID
1
2
1
2
1
2
1
Bill Will
Nora M
Java
RDBMS
1
1
2
Round 1: sid =1 .
A: SELECT cid FROM course : (1,2)
B: SELECT cid FROM enrollment e WHERE e.sid=s.sid :
(1,2)
A-B=().
Outer query selects sid=1
Round 1: sid =2 .
A: SELECT cid FROM course : (1,2)
B: SELECT cid FROM enrollment e WHERE e.sid=s.sid :
(1)
A-B=(2).
Since A-B is not empty, outer query does not return anything.
27
NULL
A column with an unknown value has the value NULL.
A null value is not < or > or = to anything. Any arithmetic operation
on null value yields null. But with aggregate functions this not the
case.
To compare with NULL value the comparison operator IS NULL or
IS NOT NULL is used.
28
HAVING clause is used to query the result of the row that is generated by a
GROUP BY clause.
Display the course name and number of students enrolled for each
course for courses which have more than 2 students.
SELECT cname, count(*) FROM course c,enrollment e WHERE
c.cid=e.cid GROUP BY cname HAVING count(*)>2
29
Exercises
Find all the students whose ages have not been given.
Display the student records in sorted order by their names.
Display the course records displaying from highest to lowest w.r.t.
course duration and then sorted by course name.
Find all the sids who have taken a course which sid=1 has taken.
30
Joins
Joining is a technique using in which two or more tables are
combined to generate results.
Cartesian or Cross Join
Equality Join :
Simple Join
Natural Join
Join USING
Inner Join
Outer Join
31
32
Simple join
Query that involves data from two or more tables based on join
condition.
Find sids and names of the students have enrolled for at least one
course.
SELECT s.sid, sname FROM Student s, Enrollment e WHERE
s.sid= e.sid
Using alias
SELECT s.sid, sname FROM Student s, Enrollment e WHERE
s.sid= e.sid
33
Natural Join
NATURAL JOIN is performed based on common field names.
If there are more than one common field, then all the filed are
compared.
Find sids and names of the students who have enrolled for at least one
course.
SELECT DISTINCT sid, sname FROM Student NATURAL JOIN
Enrollment
34
35
36
Self Join
A table that needs to get results based on the values of its two
columns uses selfjoin.
Assume that we have a table called customer.
CustID
Name
ReferredBy
Neeta Shyam
Dolly Dilly
Meena Kumari
Find the names of all customers who have referred other customers.
SELECT c1.name FROM Customer c1 JOIN Customer c2
ON c1.custid=c2.ReferredBy
37
Exercises
1. Using simple join, find cids and course names where at least one
student has enrolled.
2. Convert the above query using Join USING .
3. Find the names of the students and the names of the course which
they have enrolled for.
4. Display the course name and number of students enrolled for each
course.
5. Using natural join, find cids and course names where more than one
student has enrolled.
6. List out all the courses. Also list out the batch start date for the courses
that start in july. Hint month(edate) returns the month.
7. List out all the courses. Also list out the students, if any, who have
enrolled for each of the courses
8. List all the courses and all the students. Link the students and courses
whenever appropriate
38
Triggers
A trigger is an event that is activated automatically on a table when certain
events like insert/update/delete occurs on the table.
It is a database object like table that has a name.
CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER
trigger_name BEFORE|AFTER INSERT|UPDATE|DELETE ON
tbl_name FOR EACH ROW trigger_body
Write a trigger such that each time the course is updated, a record is inserted
in the auditCourse(cid, oldDuration, newDuration,dateOfChange).
mysql> delimiter //
mysql>CREATE TRIGGER auditCourseTrigger
->AFTER UPDATE ON Course
->FOR EACH ROW
->BEGIN
->INSERT INTO auditCourse VALUES(old.cid,
->old.duration, new.duration, CURDATE());
->END;
-> //
39
40
Stored Procedures
A stored procedure is a named group of SQL statement that have been
previously created and stored in the database server.
It is a module that performs one or more actions which can be called
from another PL/SQL block or another procedure.
They accept input parameters and return output as parameters.
In the client server environment, the stored procedure reduce network
traffic and improve performance.
CREATE [DEFINER = { user | CURRENT_USER }] PROCEDURE
sp_name ([ [ IN | OUT | INOUT ] param_name type[,...]
])
[characteristic ...] routine_body
characteristic: COMMENT 'string' | LANGUAGE SQL | [NOT]
DETERMINISTIC | { CONTAINS SQL | NO SQL | READS SQL
DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER |
INVOKER
41
+------+----------+
|
3 | Java 1.5 |
+------+----------+
1 row in set (0.00 sec))
43
Exercises
Write a trigger such that each time a negative age, a 0, or age >60
is inserted into the student table, a null is set.
Create a procedure called incrementAge that will increment the age
of the specified student by the specified value and return the new
value.
44