Vous êtes sur la page 1sur 44

SQL with MySQL

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

Creation of table with primary key


CREATE TABLE [IF NOT EXISTS][schema] tablename
(columnname datatype [DEFAULT value],
[columnname datatype [DEFAULT value],

[PRIMARY KEY(columnname, [columnname]] )


Take a look at the list of data types in MySQL in the reference material
CREATE

TABLE IF NOT EXISTS Customer(


CID INT NOT NULL ,
CNAME VARCHAR(45) NULL ,
ADDR VARCHAR(45 NULL ,
PRIMARY KEY (CID) );

Creation of table with foreign key


[CONSTRAINT [symbol]] FOREIGN KEY [index_name]
(index_col_name, ...) REFERENCES tbl_name
(index_col_name,...) [ON DELETE reference_option]
[ON UPDATE reference_option] reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION

CREATE TABLE ORDER(oid integer ,cid integer, ODATE


date, PRIMARY KEY (oid), FOREIGN KEY (cid)
REFERENCES Customer(cid))

Deleting a table
DROP TABLE

tablename

Remove table Temp from the database.


DROP TABLE TEMP

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];

Omitting WHERE clause causes all rows in the table to be deleted.


DELETE FROM Customer WHERE cid=1

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

Syntax and example


Syntax of SELECT clause
SELECT field1 [,field2,,fieldn]
FROM table1 [,table2,, tablem]
[WHERE conditions]
[GROUP BY field1 [,field2,,fieldk]]
[HAVING condition]
[ORDER BY field1 [,field2,,fieldl]]
SQL is not case sensitive. By convention the keywords are in upper case.
Example: Get all the details of the courses whose duration is more than 50
hours.
SELECT * FROM Course WHERE duration >50
13

Distinct, Patterns, Ranges


DISTINCT/UNIQUE is used to eliminate duplicate rows.
LIKE operator is used with wild card characters to search for patterns.
Wild cards:
% : any number of characters
_: one character
BETWEEN allows querying within ranges.
Find all enrollments which has taken place from July till September.
AND , OR , NOT logical operators can be used to combine where
conditions.
SELECT * FROM enrollment WHERE edate BETWEEN '01-JUL2006' AND '30-SEP-2006
14

Exercises: Simple SQL with where clause


1. Find the ids and names of all students .
2. Get all the details of the students whose age is above 20 years
3. Find sid of Bill Will.
4. For number of 7-hour day it will take to finish the individual courses.
5. Find sids and names of the students have enrolled for at least one course.
6. Find all the students who name end with the letter y.
7. Find all the enrollments that happened in july.
8. Find the 2 lettered course name that ends with a S.
9. Find all the students whose name as two characters before ll.
10. Find all courses in the range of 30 to 35 hours.
11. Find names of all students who have enrolled for some courses and whose age is 20.

15

Set Manipulation Constructs


UNION
INTERSECT
EXCEPT (OR MINUS)

eliminates the duplicate


rows from the final set.

UNION ALL
IN
Op ANY and Op ALL
EXISTS

Nested and Correlated


Subqueries

16

Exercises on Set Manipulation


1. Find the sids of all the students who have taken Java or RDBMS
courses.
2. Find the sids of all the students who have taken both Java and
RDBMS courses.
3. Find the sids of all the students who have taken Java but not
RDBMS courses.

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?

SELECT sid FROM

ENROLLMENT e, COURSE c WHERE

CNAME LIKE 'Java%' AND CNAME LIKE 'RDBMS%' AND


e.cid=c.cid

18

Aggregate Operators

COUNT([DISTINCT] a)
SUM([DISTINCT] a)
AVG([DISTINCT] a)
MAX(a)
MIN(a)

where a is an attribute of the table.


Note that aggregate values are not allowed in the WHERE
clause.

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

Exercises: Nested Query


1. Find all the students whose age is below the age of any of the students
whose name end with y.
2.

Find the names of all students who have taken Java course.

3. Get all the students name whose sids are not in 2 or 4.


4. Find the names of the students who have enrolled for a course on 1
September 2006.
5. Find the names of the students who have enrolled for a course on 1
September 2006.
6. Find all the courses whose duration is more than any other course
duration.
7. What is/are name(s) of the youngest student(s) enrolled for 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

ORDER BY, GROUP BY and HAVING


ORDER BY causes the result of the query to be displayed in a specific
order (ASC : ascending or DESC :descending) based on the attribute.
GROUP BY allows us to query based on groups of rows which have same
value for some attribute(s).
Find the number of students enrolled for each course.
SELECT cid, count(*) FROM enrollment GROUP BY cid
CID
COUNT(*)
--------------------------------------1
3
2
2

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

Cartesian or Cross Join

Result of such joining yields the cross product of combining each


row of the table with the other.
Find all the records of all the students who have taken courses.
SELECT * FROM Student, Course

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

Join USING and ON


In cases where there are more than one common key, if we need
to join based on only one key the USING keyword can be used.
SELECT DISTINCT sid, sname FROM Student JOIN
Enrollment USING(sid)
Or
SELECT DISTINCT Student.sid, sname FROM Student
JOIN Enrollment ON Student.sid= Enrollment.sid

35

Outer Join- Left , Right and Full


In the outer join, the records that do not match the criteria also
appear.
Left outer join lists all the records from the table on the left , right
outer join list the table on the right and full lists records from both
left and right table.
List out all the student names. Also list out the courses, if any, that
each student has enrolled for.
select sname from student LEFT OUTER JOIN
enrollment on student.sid=enrollment.sid

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

Control Flow statements


IF search_condition THEN statement_list [ELSEIF
search_condition THEN statement_list] ... [ELSE
statement_list] END IF
CASE value WHEN [compare_value] THEN result [WHEN
[compare_value] THEN result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN
[condition] THEN result ...] [ELSE result] END
IFNULL(expr1,expr2)
NULLIF(expr1,expr2)

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

Example: Stored Procedures


Write a procedure that gets the count and the course name where
enrollment is more than the specified number.
(make delimiter as // before executing)
CREATE PROCEDURE courseCount (OUT cnt INT, IN num INT,
OUT coursename varchar(35))
BEGIN
-- local variable
comment
declare vcid INT;
Local variable declaration
SELECT cid , COUNT(*) INTO vcid,cnt FROM
Enrollment group by cid having count(*)>num;
SELECT cname INTO coursename FROM Course WHERE
cid=vcid;
END;
42

Executing Stored Procedures


mysql> delimiter ;
mysql> call courseCount(@cnt,2,@cname);
Query OK, 0 rows affected (0.04 sec)
mysql> select @cnt, @cname;
+------+----------+
| @cnt | @cname

+------+----------+
|

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

Vous aimerez peut-être aussi