Beruflich Dokumente
Kultur Dokumente
FOR
DATABASE MANAGEMENT
SYSTEM
Prepared By:
ooooooXXXXXooooooo
1|Page
MYSQL
Introduction:
The following table shows each of the prompts you may see and
summarizes what they mean about the state that mysql is in:
What is MySQL?
MySQL, the most popular Open Source SQL database management system, is
developed, distributed, and supported by MySQL AB. MySQL AB is a
commercial company, founded by the MySQL developers. It is a second
generation Open Source company that unites Open Source values and
methodology with a successful business model.
History of MySQL
We started out with the intention of using the mySQL database system
to connect to our tables using our own fast low-level (ISAM) routines.
However, after some testing, we came to the conclusion that mySQL was
not fast enough or flexible enough for our needs. This resulted in a
new SQL interface to our database but with almost the same API
interface as mySQL. This API was designed to allow third-party code
that was written for use with mSQL to be ported easily for use with
MySQL.
MySQL is named after co-founder Monty Widenius's daughter My.
The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen
by the founders of MySQL AB from a huge list of names suggested by
users in our “Name the Dolphin” contest. The winning name was
submitted by Ambrose Twebaze, an Open Source software developer from
Swaziland, Africa. According to Ambrose, the feminine name Sakila has
its roots in SiSwati, the local language of Swaziland. Sakila is also
the name of a town in Arusha, Tanzania, near Ambrose's country of
origin, Uganda.
2|Page
Relatively easy to add other storage engines. This is useful if you
want to provide an SQL interface for an in-house database.
A very fast thread-based memory allocation system.
Very fast joins using an optimized one-sweep multi-join.
In-memory hash tables, which are used as temporary tables.
SQL functions are implemented using a highly optimized class library
and should be as fast as possible. Usually there is no memory
allocation at all after query initialization.
The MySQL code is tested with Purify (a commercial memory leakage
detector) as well as with Valgrind, a GPL tool .
mysql –u studentrollno
4). And then successful connect from user client to server then u get
mysql prompt.
3|Page
If you type your programs at mysql prompt then screen will look like
follow:
Mysql>show databases;
Mysql>use databasename;
Mysql>show tables;
Prompt Meaning
mysql> Ready for new command.
-> Waiting for next line of multiple-line command.
‘> Waiting for next line, waiting for completion of a
string that began with a single quote(“’”).
“> Waiting for next line, waiting for completion of a
string that began with a single quote(“””).
`> Waiting for next line, waiting for completion of a
string that began with a single quote(“`”).
/*> Waiting for next line, waiting for completion of a
string that began with a single quote(“’”).
4|Page
COMMENT - add comments to the data dictionary
DELETE - deletes all records from a table, the space for the records
remain
5|Page
Data types:
1.Numeric types;
1.BIT
2.TINYINT
3.BOOLEAN
4.SMALLINT
5.MEDIUMINT
6.INT
7.INTEGER
8.BIGINT
9.FLOAT
10.DOUBLE
11.DECIMAL
1.DATE
2.TIME
3.DATETIME
4.TIMESTAMP
5.YEAR
6|Page
3.String Data types:
1.CHAR
2.VARCHAR
3.TEXT
4.BLOB
5.MEDIUMITEX
6.BINARY
7.VARBINARY
8.ENUM
9.SET
10.LONGTEXT
7|Page
Storage Requirements for String Types
+----------------------+
| Tables_in_cse550 |
+----------------------+
| emp |
| employee |
| product |
| staff |
| student |
+----------------------+
8|Page
mysql> describe emp;
+--------+--------------+------+-----+---------+-------+
+--------+--------------+------+-----+---------+-------+
+--------+--------------+------+-----+---------+-------+
+-------------------------+
| Tables_in_cse550 |
+-------------------------+
| emp |
| employee |
| staff |
| student |
+-------------------------+
9|Page
4 rows in set (0.00 sec)
+------+-------+------+------+-------+--------+------+-------+
+-------+-----+------+------+--------+--------+------+-------+
+-------+-------+------+------+--------+-------+-----+-------+
Mysql COMMANDS
10 | P a g e
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records
remain
Description:
11 | P a g e
CREATE: This command useful for creating creating table.
Syntax:
column 2 datatype[size],…
column n datatype[size] );
Ex:
+------------+-------------+-------+------+---------+------+
+------------+-------------+-------+------+---------+------+
+------------+-------------+------+-----+---------+--------+
12 | P a g e
Empty set (0.04 sec)
1.NOT NULL:
Syntax:
<col><datatype>(size)not null
2.UNIQUE :
Syntax:
<col><datatype>(size)unique;
Ex:
13 | P a g e
Query OK, 0 rows affected (0.10 sec)
Syntax:
Ex:
3.PRIMARY KEY:
Syntax:
<col><datatype>(size)primary key;
Ex:
brach_name varchar(10));
Syntax:
Ex:
14 | P a g e
mysql> create table customer1(customer_id int(5),customer_name
varchar(10),customer_street varchar(10),
4. CHECK:
Ex:
Ex:
5.FOREIGN KEY:
Syntax:
15 | P a g e
<col><datatype>(size>) references <tablename>[<col>];
InnoDB supports foreign key constraints. The syntax for a foreign key
constraint definition in InnoDB looks like this:
+------------+-------------+------+-----+---------+-------+
+------------+-------------+------+-----+---------+-------+
+------------+-------------+------+-----+---------+-------+
16 | P a g e
Foreign key constraint at table level
Syntax:
Ex:
17 | P a g e
Mysql>create table shipment(ono int,wno int,sdate date not
null,primary key(ono,wno),foreign key(ono) references order1(ono) on
delete cascade,
customer
order1
18 | P a g e
Mysql>insert into order1 values(2,'26-mar-2006',2,10000);
item
19 | P a g e
Query OK, 1 row affected (0.00 sec)
oitem
20 | P a g e
Mysql>insert into oitem values(4,2,30);
warehouse
21 | P a g e
shipment
22 | P a g e
Mysql>select cname as custname,count(ono) as no_of_orders,avg(oamt) as
avg_ord_amt from customer c,order1 o where c.ono=o.ono group by
c.cno,cname;
Mysql>select ono from order1 o where not exist ((select wno from
warehouse where city='bangalore') minus (select wno from shipment s
where s.ono=o.ono)) and exists (select wno from warehouse where
city='bangalore');
Syntax::
Ex::
23 | P a g e
mysql> select *from emp;
+------+---------+---------+------+---------+--------+-------+
+-------+---------+--------+------+---------+-------+--------+
+-------+----------+-----------+------+------+--------+------+
+-------+----------+-----------+------+-------+------+--------+
+-------+----------+-----------+------+-------+--------+------+
24 | P a g e
| E1002 | Nagarjuna| asso.prof | CSE | 1050 | NULL | 25000 |
+-------+----------+-----------+------+------+-------+--------+
Syntax:
Ex:
+---------+-------------+-----+------+---------+-------+
+---------+-------------+-----+------+---------+-------+
25 | P a g e
| dob | date | YES | | NULL | |
+--------+--------------+-----+------+---------+-------+
+-------+----------+----------+------+----+------+
+-------+----------+----------+------+----+------+
+-------+----------+-------------+-------+-------+
26 | P a g e
4. Modifying existing columns.
Syntax:
Ex:
Syntax:
Ex:
Syntax:
Ex::
27 | P a g e
7. Destroying tables.
Syntax:
Ex:
1. Insert:
Syntax 1:
28 | P a g e
mysql> insert into emp
values('E1002','Sitaram','asst.prof','EEE',1025,12500);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
ERROR 1064 (42000): You have an error in your MYSQL syntax; check the
manual that corresponds to your Mysql server version for the right
syntax to use near ''Nagababu','asso.prof', 'CSE',1065, 28000)' atline
1
+------+-----------+--------+-------+-----+--------+
+------+-----------+-----------+-----+------+------+
29 | P a g e
| E1002 | Nagaraja | asst.prof | EEE |1035 | 10500 |
+-------+----------+-----------+-----+-----+-------+
+---------+------------+-----+----+-------+-----+
+---------+------------+-----+----+-------+-----+
+---------+------------+-----+----+------+------+
+------+-----------+-----------+-----+------+-------+
+------+-----------+-----------+-----+------+-------+
30 | P a g e
| E1002 | Nagaraja | asst.prof | EEE | 1035 | 10500 |
+-------+----------+-----------+-----+------+-------+
Syntax 2:
Syntax:
Ex:
Syntax:
Ex:
Delete operations.
Syntax:
31 | P a g e
delete from <tablename>;
Ex:
Syntax:
Ex:
Using AUTO_INCREMENT
+----+---------+
| id | name |
+----+---------+
| 1 | dog |
| 2 | cat |
| 3 | penguin |
| 4 | lax |
| 5 | whale |
| 6 | ostrich |
+----+---------+
32 | P a g e
6 rows in set (0.02 sec)
You can retrieve the most recent AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function.
These functions are connection-specific, so their return values are
not affected by another connection which is also performing inserts.
Note
+--------+----+--------+
| grp | id | name |
+--------+----+--------+
| fish | 1 | lax |
| mammal | 1 | dog |
| mammal | 2 | cat |
| mammal | 3 | whale |
| bird | 1 | penguin|
33 | P a g e
| bird | 2 |ostrich |
+-------+----+---------+
34 | P a g e
WEEK 2
E-R DIAGRAMS
2. HOSPITAL MANAGEMENT:
35 | P a g e
3. EMPLOYEE:
36 | P a g e
5. VEHICLE REGISTRATION:
37 | P a g e
7. PROJECT DEVELOPMENT SYSTEM:
38 | P a g e
WEEK 3
SAILORS TABLE
BOATS TABLE
RESERVES TABLE
39 | P a g e
QUERIES:
1. Find the names and sids of sailors who have reserved a red or a
2. Find the names and sids of sailors who have reserved a red and a
104 ?(UNION)
4. Find the names of sailors who have reserved boat 103 ? (IN)
5. Find the names of sailors who have reserved a red boat? (IN)
6. Find the names of sailors who have not reserved a red boat? (NOT
IN)
Horatio? (ANY)
9. Find the names of sailors who have reserved both a red and a green
boat? (IN)
10. Find the names of sailors who have reserved boat no 103? (EXISTS)
11. Find the names of sailors who have reserved all boats? (NOT
EXISTS)
QUERIE 1: Find the names and sids of sailors who have reserved a red
or a green boat?
40 | P a g e
MYSQL> SELECT S.sname, S.sid FROM sailors S, reserves R, boats B WHERE
S.sid=R.sid AND R.bid=B.bid AND B.color='red'
UNION
SNAME SID
-------------------- ----------
Dustin 22
Horatio 64
Horatio 74
Lubber 31
QUERIE 2: Find the names and sids of sailors who have reserved a red
and a green boat?
INTERSECT
SNAME SID
-------------------
Dustin 22
Lubber 31
41 | P a g e
QUERIE 3: Find all sids of sailors who have a rating of 10 or reserved
boat 104?
UNION
SID
----------
22
31
58
71
QUERIE 4: Find the names of sailors who have reserved boat 103 ? (IN)
MYSQL> SELECT S.sname FROM sailors S WHERE S.sid IN (SELECT R.sid FROM
reserves R WHERE R.bid=103);
SNAME
--------------------
Dustin
Lubber
Horatio
42 | P a g e
QUERIE 5: Find the names of sailors who have reserved a red boat?
mysql> SELECT S.sname FROM sailors S WHERE S.sid IN (SELECT R.sid FROM
reserves R WHERE R.bid IN (SELECT B.bid FROM boats B WHERE
B.color='red'));
SNAME
--------------------
Dustin
Lubber
Horatio
QUERIE 6: Find the names of sailors who have not reserved a red boat?
MYSQL> SELECT S.sname FROM sailors S WHERE S.sid NOT IN (SELECT R.sid
FROM reserves R WHERE R.bid IN (SELECT B.bid FROM boats B WHERE
B.color='red'));
SNAME
--------------------
Brutus
Andy
Rusty
Zorba
Horatio
Art
BOB
7 rows selected.
43 | P a g e
QUERIE 7: Find sailors whose rating is better than some sailor called
Horatio?
MYSQL> SELECT S.sid FROM sailors S WHERE S.rating > ANY (SELECT
S1.rating FROM sailors S1 WHERE S1.sname='Horatio');
SID
----------
58
71
74
31
32
mysql> SELECT S.sid FROM sailors S WHERE S.rating >= ALL (SELECT
S1.rating FROM sailors S1);
SID
----------
58
71
QUERIE 9: Find the names of sailors who have reserved both a red and a
green boat?
44 | P a g e
S1.sid FROM sailors S1, reserves R1, boats B1 WHERE S1.sid=R1.sid AND
R1.bid=B1.bid AND B1.color='green');
SNAME
--------------------
Dustin
Dustin
Lubber
Lubber
QUERIE 10: Find the names of sailors who have reserved boat no 103?
SNAME
--------------------
Dustin
Lubber
Horatio
QUERIE 11: Find the names of sailors who have reserved all boats?
MYSQL> SELECT S.sname FROM sailors S WHERE NOT EXISTS (SELECT B.bid
SNAME
--------------------
Dustin
45 | P a g e
1) Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints.
Example: select the rollno and name of the student who secured 4th rank
in the class
TABLE DEFINITIONS
last_name VARCHAR2(20),
address1 VARCHAR2(20),
address2 VARCHAR2(20),
city VARCHAR2(3),
state VARCHAR2(20),
pin VARCHAR2(6),
birth_date DATE,
status VARCHAR2(1),
);
Table created.
46 | P a g e
1 row created.
NO NAME NAME T
1003 BAHADUR RAJ SHANTHI VILLA NEAR MALLIKA UDP KARNATAKA 576101
1-AUG-70 V
1005 KUTTY RAJAN A1 TRADERS NEAR RLY STATION KNR KERALA 67001
9-JUN-71 A
QUERIES
SEELCT *
FROM Customer;
FROM Customer;
47 | P a g e
3. To list the first name and last name of persons in Karnataka.
FROM Customer
SELECT *
FROM Customer
FROM Customer
FROM Customer;
7. To select records where the pin code has not been entered.
SELECT *
FROM Customer
48 | P a g e
WHERE pin IS NULL;
FROM Customer;
SELECT *
FROM Customer
SELECT *
FROM Customer
OR state = ‘KERALA’;
FROM Customer
ORDER BY state;
49 | P a g e
SELECT state, first_name, last_name, pin
FROM Customer
13. To sort the customer data, state wise and within state by the last
name.
FROM Customer
SELECT *
FROM Customer
SELECT *
FROM Customer
OR UPPER(state) = ‘KERALA’;
SELECT *
FROM Customer
50 | P a g e
WHERE (UPPER(state) = ‘KARNATAKA’
OR UPPER(state) = ‘KERALA’)
SELECT *
FROM Customer
18. To retrieve rows where the state name begins with K and followed by
any other character.
FROM Customer
19. To retrieve rows where the first name contains the word RAJ embedded
in it.
FROM Customer
20. To retrieve rows where the address2 contains the word UDUPI or UDIPI
in which the 3rd character may be anything.
FROM Customer
51 | P a g e
WHERE address2 LIKE ‘UD_PI’;
21. To retrieve rows where the cust_no has data representing any value
between 1003 and 1005, both numbers included.
SELECT *
FROM Customer
22. To retrieve rows of persons born after 9-JAN-70 and before 1-AUG-96.
SELECT *
FROM Customer
23. To retrieve rows where the city has data which is equal to UDP or
MNG or BNG or PJM or MAR.
SELECT *
FROM Customer
TABLE DEFINITIONS
Table created.
52 | P a g e
Insert the following data:
Table created.
53 | P a g e
QUERIES
FROM salary
GROUP BY emp_no;
2. To sum the salary of each employee and sort it on the sum of basic.
FROM salary
GROUP BY emp_no
ORDER BY SUM(basic);
FROM salary
GROUP BY emp_no
54 | P a g e
ORDER BY SUM(s.basic) DESC;
ORDER BY AVG(s.basic);
FROM salary
ORDER BY AVG(s.basic);
55 | P a g e
SUBQUERIES
8. To list the employees who earn less than the average salary.
SELECT *
FROM salary
FROM salary);
SELECT *
FROM salary
FROM salary
10. To list the names of employees and salary details, whose basic is
less than the average salary.
FROM salary);
56 | P a g e
2. Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints.
Example: select the rollno and name of the student who secured 4th rank
in the class.
2. Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN),
GROUP BY, HAVING and Creation and Dropping of Views.
TABLE DEFINITIONS
emp_no NUMBER,
emp_name VARCHAR(20),
join_date DATE,
);
Table created.
57 | P a g e
EMP NO EMP NAME JOIN DATE JOIN BASIC
Table created.
58 | P a g e
QUERIES
FROM salary
GROUP BY emp_no;
12. To sum the salary of each employee and sort it on the sum of basic.
FROM salary
GROUP BY emp_no
ORDER BY SUM(basic);
13. To sum the salary of each employee and sort it in descending order
on the sum of basic.
FROM salary
GROUP BY emp_no
14. To sum the salary of each employee and sort it in descending order
on the sum of basic.
59 | P a g e
GROUP BY s.emp_no, e.emp_name
ORDER BY AVG(s.basic);
FROM salary
17. To group the data by average salary of each employee and display
where average basic is more than 2000..
ORDER BY AVG(s.basic);
60 | P a g e
SUBQUERIES
18. To list the employees who earn less than the average salary.
SELECT *
FROM salary
FROM salary);
SELECT *
FROM salary
FROM salary
20. To list the names of employees and salary details, whose basic is
less than the average salary.
FROM salary);
2. Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints. Example: select the rollno
and name of the student who secured 4th rank in the class.
61 | P a g e
2. Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN),
GROUP BY, HAVING and Creation and Dropping of Views.
TABLE DEFINITIONS
BRANCH TABLE
62 | P a g e
CUSTOMER TABLE
LOAN TABLE
63 | P a g e
BORROWER TABLE
Adams l-16
Curry L-93
Hayes L-15
Jackson L-14
Jones L-17
Smith L-11
Smith L-23
Williams L-17
ACCOUNT TABLE
64 | P a g e
DEPOSITOR TABLE
Hayes A102
Johnson A-101
Johnson A-201
Jones A-217
Lindsay A-222
Smith A-215
Turner A-305
QUERIES
SELECT branch_name
FROM Loan;
FROM Loan;
FROM Loan;
FROM Loan;
65 | P a g e
5) Find all loan numbers for loans made at the Perryridge branch with
loan amounts greater than Rs1200.
SELECT loan_number
FROM Loan
6) Find all loan numbers for loans with loan amounts between Rs90,000
and Rs100,000.
SELECT loan_number
FROM Loan
Or
SELECT loan_number
FROM Loan
7) Find all loan numbers for loans with loan amounts not between
Rs90,000 and Rs100,000.
SELECT loan_number
FROM Loan
8) For all customers who have a loan from the bank, find their names,
loan numbers and loan amounts.
66 | P a g e
Or
9) Find the customer names, loan numbers and loan amounts for all
loans at the Perryridge branch.
Or
10) Find the names of all branches that have assets greater than
atleast one branch located in Brooklyn.
11) Find the names of all customers whose street address includes the
substring ‘Main’.
SELECT customer_name
FROM Customer
67 | P a g e
12) To list in alphabetic order all customers who have a loan at the
Perryridge branch.
ORDER BY customer_name;
SELECT *
FROM Loan
(SELECT customer_name
FROM Depositor)
UNION
(SELECT customer_name
FROM Borrower);
(SELECT customer_name
FROM Depositor)
UNION ALL
(SELECT customer_name
FROM Borrower);
68 | P a g e
16) To find all customers having both a loan and an account at the
bank, without duplicates.
(SELECT customer_name
FROM Depositor)
INTERSECT
(SELECT customer_name
FROM Borrower);
(SELECT customer_name
FROM Depositor)
INTERSECT ALL
(SELECT customer_name
FROM Borrower);
18) To find all customers who have an account but no loan at the bank,
without duplicates.
FROM Depositor)
EXCEPT
(SELECT customer_name
FROM Borrower);
19) To find all customers who have an account but no loan at the bank,
with duplicates.
FROM Depositor)
EXCEPT ALL
69 | P a g e
20) Find the average account balance at the Perryridge branch.
FROM Account
SELECT AVG(balance)
FROM Account
GROUP BY branch_name;
GROUP BY branch_name;
23) Find the number of depositors for each branch where average
account balance is more than Rs 1200.
GROUP BY branch_name
SELECT AVG(balance)
FROM Account;
70 | P a g e
25) Find the number of tuples in the customer relation.
SELECT COUNT(*)
FROM Customer;
26) Find the average balance for each customer who lives in Harrision
and has at least three accounts.
GROUP BY D.customer_name
27) Find all the loan number that appear in loan relation with null
amount values.
SELECT loan_number
FROM Loan
28) Find all customers who have both a loan and an account at the
bank.
SELECT customer_name
FROM Borrower
FROM Depositor);
71 | P a g e
29) Find all customers who have both an account and a loan at the
Perryridge branch.
or
SELECT customer_name
FROM Borrower B
FROM Depositor D
30) Find all customers who do not have a loan at the bank, but do not
have an account the bank.
FROM Borrower
(SELECT customer_name
FROM Depositor);
72 | P a g e
31) Find the names of customers who do have a loan at the bank, and
whose names are neither Smith nor Jones.
FROM Borrower
32) Find the names of all branches that have assets greater than those
of at least one branch located in Brooklyn.
33) Find the names of all branches that have assets greater than that
of each branch located in Brooklyn.
SELECT branch_name
FROM Account
GROUP BY branch_name
FROM Account
GROUP BY branch_name);
34) Find all customers who have an account at all the branches located
in Brooklyn.
FROM Depositor AS D
FROM Branch
73 | P a g e
EXCEPT
(SELECT R.branch_name
WHERE T.account_number =
R.account_number
35) Find all customers who have at most one account at the Perryridge
branch.
SELECT T.customer_name
FROM Depositor AS T
36) Find all customers who have at least two accounts at the
Perryridge branch.
FROM Depositor AS T
74 | P a g e
WHERE T.customer_name = R.customer_name
37) Find the average account balance of those branches where the
average account balance is greater than 1200.
FROM Account
GROUP BY branch_name)
AS Branch_avg(branch_name, avg_balance)
38) Find the maximum across all branches of the total balance at each
branch.
SELECT MAX(tot_balance)
FROM Account
GROUP BY branch_name)
AS Branch_total(branch_name, tot_balance);
75 | P a g e
39) Find the all customers who have an account but no loan at the
bank.
SELECT d-CN
ON Depositor.customer_name = Borrower.customer_name)
40) Find the all customers who have either an account or a loan (but
not both) at the bank.
SELECT customer_name
OR loan_number IS NULL;
AGGREGATE FUNCTIONS:
output:-
76 | P a g e
1002 ADAM CLERK 1000
output:-
COUNT(*)
----------
output:-
SUM(SAL)
----------
14720
output:-
AVG(SAL)
----------
3680
output:-
MAX(SAL)
77 | P a g e
----------
7000
output:-
MIN(SAL)
----------
1000
OUTPUT:-
78 | P a g e
7698 BLAKE MANAGER 2850 30
14 rows selected.
OUTPUT:-
ROUND(12.36) ROUND(14.63)
------------ ------------
12 15
OUTPUT:-
FLOOR(12.87) FLOOR(11.23)
------------ ------------
12 11
79 | P a g e
OUTPUT:-
CEIL(16.23) CEIL(12.78)
----------- -----------
17 13
OUTPUT:-
TRUNC(56.63)
------------
56
OUTPUT:-
MOD(11,4)
----------
OUTPUT:-
POWER(2,3)
----------
80 | P a g e
MYSQL> select sign(0),sign(34),sign(-56) ;
OUTPUT:-
0 1 -1
OUTPUT:-
ABS(12) ABS(-89)
---------- ----------
12 89
OUTPUT:-
SQRT(25)
--------
STRING FUNCTIONS:
MYSQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’) ;
81 | P a g e
OUTPUT:-ORACLECORPORATION
MYSQL>SELECT LPAD(‘ORACLE’,15,’*’) ;
OUTPUT:-*********ORACLE
MYSQL>SELECT RPAD(‘ORACLE’,15,’*’) ;
OUTPUT:-ORACLE*********
MYSQL>SELECT LTRIM(‘SSMITHSS’,’S’) ;
OUTPUT:-MITHSS
MYSQL>SELECT RTRIM(‘SSMITHSS’,’S’) ;
OUTPUT:-SSMITH
MYSQL>SELECT LOWER(‘DBMS’) ;
OUTPUT:-dbms
MYSQL>SELECT UPPER(‘dbms’) ;
82 | P a g e
OUTPUT:-DBMS
MYSQL>SELECT INITCAP(‘ORACLE’,’CORPORATION’) ;
OUTPUT:-Oracle Corporation
MYSQL>SELECT LENGTH(‘DATABASE’) ;
OUTPUT:-8
MYSQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4) ;
OUTPUT:-CDEF
OUTPUT:-14
DATE FUNCTIONS:
MYSQL>SELECT SYSDATE ;
OUTPUT:-29-DEC-08
83 | P a g e
MYSQL>SELECT NEXT_DAY(SYSDATE,’WED’) ;
OUTPUT:-05-JAN-09
MYSQL>SELECT ADD_MONTHS(SYSDATE,2) ;
OUTPUT:-28-FEB-09
MYSQL>SELECT LAST_DAY(SYSDATE) ;
OUTPUT:-31-DEC-08
MYSQL>SELECT LEAST('10-JAN-07','12-OCT-07') ;
OUTPUT:-10-JAN-07
MYSQL>SELECT GREATEST('10-JAN-07','12-OCT-07') ;
OUTPUT:-10-JAN-07
MYSQL>SELECT TRUNC(SYSDATE,'DAY') ;
OUTPUT:-28-DEC-08
MYSQL>SELECT TRUNC(SYSDATE,'MONTH') ;
OUTPUT:-01-DEC-08
MYSQL>SELECT TRUNC(SYSDATE,'YEAR') ;
84 | P a g e
OUTPUT:-01-JAN-08
MYSQL>SELECT ROUND(SYSDATE,'DAY') ;
OUTPUT:-28-DEC-08
MYSQL>SELECT ROUND(SYSDATE,'MONTH') ;
OUTPUT:-01-JAN-09
MYSQL>SELECT ROUND(SYSDATE,'YEAR') ;
OUTPUT:-01-JAN-09
Name Description
ADDDATE() Add dates
ADDTIME() Add time
CONVERT_TZ() Convert from one timezone to another
CURDATE() Return the current date
CURRENT_DATE(),
Synonyms for CURDATE()
CURRENT_DATE
CURRENT_TIME(),
Synonyms for CURTIME()
CURRENT_TIME
CURRENT_TIMESTAMP(),
Synonyms for NOW()
CURRENT_TIMESTAMP
CURTIME() Return the current time
DATE_ADD() Add two dates
DATE_FORMAT() Format date as specified
DATE_SUB() Subtract two dates
Extract the date part of a date or
DATE()
datetime expression
DATEDIFF() Subtract two dates
85 | P a g e
DAY() Synonym for DAYOFMONTH()
DAYNAME() Return the name of the weekday
DAYOFMONTH() Return the day of the month (1-31)
Return the weekday index of the
DAYOFWEEK()
argument
DAYOFYEAR() Return the day of the year (1-366)
EXTRACT Extract part of a date
FROM_DAYS() Convert a day number to a date
FROM_UNIXTIME() Format date as a UNIX timestamp
GET_FORMAT() Return a date format string
HOUR() Extract the hour
Return the last day of the month for the
LAST_DAY
argument
LOCALTIME(),
Synonym for NOW()
LOCALTIME
LOCALTIMESTAMP,
Synonym for NOW()
LOCALTIMESTAMP()
Create a date from the year and day of
MAKEDATE()
year
returns a time value calculated from the
MAKETIME
hour, minute, and second arguments
Return the microseconds from
MICROSECOND()
argument
MINUTE() Return the minute from the argument
MONTH() Return the month from the date passed
MONTHNAME() Return the name of the month
NOW() Return the current date and time
PERIOD_ADD() Add a period to a year-month
Return the number of months between
PERIOD_DIFF()
periods
Return the quarter from a date
QUARTER()
argument
Converts seconds to 'HH:MM:SS'
SEC_TO_TIME()
format
SECOND() Return the second (0-59)
STR_TO_DATE() Convert a string to a date
When invoked with three arguments a
SUBDATE()
synonym for DATE_SUB()
SUBTIME() Subtract times
Return the time at which the function
SYSDATE()
executes
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to
86 | P a g e
seconds
Extract the time portion of the
TIME()
expression passed
TIMEDIFF() Subtract time
With a single argument, this function
returns the date or datetime expression.
TIMESTAMP()
With two arguments, the sum of the
arguments
Add an interval to a datetime
TIMESTAMPADD()
expression
Subtract an interval from a datetime
TIMESTAMPDIFF()
expression
Return the date argument converted to
TO_DAYS()
days
UNIX_TIMESTAMP() Return a UNIX timestamp
UTC_DATE() Return the current UTC date
UTC_TIME() Return the current UTC time
UTC_TIMESTAMP() Return the current UTC date and time
WEEK() Return the week number
WEEKDAY() Return the weekday index
Return the calendar week of the date (1-
WEEKOFYEAR()
53)
YEAR() Return the year
YEARWEEK() Return the year and week
OUTPUT:-
DEPTNO MAX(SAL)
---------- ----------
10 5000
20 3000
87 | P a g e
30 2850
OUTPUT:-
DEPTNO MIN(SAL)
---------- ----------
10 1300
20 800
30 950
OUTPUT:-
DEPTNO MAX(SAL)
---------- ----------
30 2850
OUTPUT:-
DEPTNO MIN(SAL)
-------- ----------
10 1300
88 | P a g e
OUTPUT:-
DEPTNO COUNT(*)
--------- -------
10 3
20 5
30 6
3 rows selected.
CONVERSION FUNCTIONS(TO_CHAR)
MYSQL>select to_char(65,'RN') ;
OUTPUT:LXV
MYSQL>select to_char(65,'rn') ;
OUTPUT:lxv
MYSQL>select to_char(58,'s9999') ;
OUTPUT:+58
MYSQL>select to_char(-100,'s9999') ;
OUTPUT:-100
OUTPUT:29
89 | P a g e
MYSQL> select to_char(10,'XXXX') ;
OUTPUT:A
OUTPUT:MONDAY
OUTPUT:JANUARY
OUTPUT:1,23,456
OUTPUT:$1234
OUTPUT:1,23,456.000
SELECT TO_CHAR(2234,'L9999','NLS_CURRENCY=RS') ;
OUTPUT:RS2234
90 | P a g e
2. Queries (along with subqueries) using ANY, ALL, IN, EXISTS, NOT
EXISTS, UNIQUE, INTERSECT, Constraints.
Example: select the rollno and name of the student who secured 4th rank
in the class.
2. Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN),
GROUP BY, HAVING and Creation and Dropping of Views.
select SYSDATE;
select 2*2;
select USER;
91 | P a g e
6. To display system date in specified format.
select ADD_MONTHS(SYSDATE, 5) ;
select LAST_DAY(SYSDATE) ;
GROUP FUNCTIONS:
92 | P a g e
13. To display minimum basic salary of the employees.
STRING FUNCTIONS:
select LOWER(‘A’) ;
select LOWER(‘a’) ;
93 | P a g e
21. To display a field value after converting to initial capital case.
select substr(‘cse2a’, 4, 2) ;
94 | P a g e
SUBQUERRIES
Writing Subqueries
+------+---------------+----------+
+------+---------------+----------+
| 1 | A K Ltd | Delhi |
| 2 | V K Associate | Mumbai |
| 3 | R K India | Banglore |
| 4 | R S P Ltd | Kolkata |
| 5 | A T Ltd | Delhi |
| 6 | D T Info | Delhi |
+------+---------------+----------+
+---------+-------------+------+----------+
95 | P a g e
+---------+-------------+------+----------+
+---------+-------------+------+----------+
Predicate Subqueries
Predicate Subqueries can be used in the HAVING and WHERE clause only
because both are special logical construct. These subqueries must
retrieve one column.
IN Subquery
The IN subquery tests if a scalar values match with the single query
column value in any subquery result row.
96 | P a g e
The general syntax is :
Value_1 [NOT] IN (query_1)
In the following example we are getting the list of clients that are
available in Products table also. Example :
+------+---------------+----------+
+------+---------------+----------+
| 1 | A K Ltd | Delhi |
| 2 | V K Associate | Mumbai |
| 3 | R K India | Banglore |
| 5 | A T Ltd | Delhi |
+------+---------------+----------+
+------+-----------+---------+
+------+-----------+---------+
| 4 | R S P Ltd | Kolkata |
| 6 | D T Info | Delhi |
+------+-----------+---------+
97 | P a g e
2 rows in set (0.01 sec)
Quantified Subqueries
A quantified subquery can use the all comparison operators for several
types of tests. The general syntax is :
Value_1 {=|>|<|>=|<=|<>} {ANY | ALL | SOME} (query_1)
Example :
mysql> SELECT * FROM Client WHERE C_ID= ANY(SELECT C_ID FROM
Products);
+------+---------------+----------+
+------+---------------+----------+
| 1 | A K Ltd | Delhi |
| 2 | V K Associate | Mumbai |
| 3 | R K India | Banglore |
| 5 | A T Ltd | Delhi |
+------+---------------+----------+
Exists Subqueries
98 | P a g e
least one row or a qualifying row exists. The general syntax is :
Exists (query_1)
Any EXISTS subquery should contain an outer reference. It must be a
correlated subquery.
Example :
+------+---------------+----------+
+------+---------------+----------+
| 1 | A K Ltd | Delhi |
| 2 | V K Associate | Mumbai |
| 3 | R K India | Banglore |
| 5 | A T Ltd | Delhi |
+------+---------------+----------+
Scalar Subqueries
Example :
99 | P a g e
+----------------------------------------+
+----------------------------------------+
| A K Ltd |
+----------------------------------------+
mysql> SELECT (SELECT C_ID FROM Products WHERE C_ID=2) FROM Client;
mysql> SELECT (SELECT C_ID FROM Products WHERE C_ID=1) FROM Client;
+------------------------------------------+
+------------------------------------------+
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
+------------------------------------------+
Table Subqueries
Table subqueries are used in the FROM Clause , replace the table name.
These subqueries can have correlation name also. Example :
100 | P a g e
-> WHERE Client.C_ID=Products.C_ID
+------+---------------+--------+----------+
+------+---------------+--------+----------+
+------+---------------+--------+----------+
+------------+
| MAX(Price) |
+------------+
| 15500.00 |
+------------+
The above example retrieve only a single value and its representing
the maximum Price of the Product. In this example we used a MySQL
Function MAX() that finds the greatest values in a specified column.
101 | P a g e
Single ? value subqueries is used to return a single column value and
then they are typically used for comparison. For Example :
mysql>
+------+---------+-------+---------+-------------+------+----------+
+------+---------+-------+---------+-------------+------+----------+
+------+---------+-------+---------+-------------+------+----------+
102 | P a g e
JOINS
+-----------+--------------+----------------------+
| name | phone | selling |
+-----------+--------------+----------------------+
| Mr Brown | 01225 708225 | Old House Farm |
| Mr Pullen | 01380 724040 | The Willows |
| Mr Pullen | 01380 724040 | Tall Trees |
| Mr Pullen | 01380 724040 | The Melksham Florist |
+-----------+--------------+----------------------+
4 rows in set (0.01 sec)
MySQL LEFT, RIGHT JOIN
MySQL joins are hard for beginners. It will try to explain the joins
in the simplest possible way.
Join in MySQL is a query where you can join one or more tables.
For example we have two tables: products and buyers with the following
structures.
Table products:
+----+--------------+--------------+
| id | product_name | manufacturer |
+----+--------------+--------------+
| 1 | Shoes | Company1 |
| 2 | Laptop | Company2 |
| 3 | Monitor | Company3 |
| 4 | DVD | Company4 |
103 | P a g e
+----+--------------+--------------+
Table buyers:
mysql> SELECT * FROM buyers;
+----+------+------------+----------+
+----+------+------------+----------+
| 1 | 1 | Steve | 2 |
| 2 | 2 | John | 1 |
| 3 | 3 | Larry | 1 |
| 4 | 3 | Michael | 5 |
+----+------+------------+----------+
Left Join
+------------+----------+--------------+
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
104 | P a g e
5 rows in set (0.00 sec)
What happened?
Mysql starts with the left table (buyers). For each row from the
table buyers mysql scans the table products, finds the id of the
product and returns the product name. Then the product name is joined
with the matching row from the table buyers. For unmatched rows it
returns null.
To make it simpler, the above query is same as (except the unmatched
rows are not returned):
+------------+----------+--------------+
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
If we do a LEFT JOIN, we get all records that match in the same way
and IN ADDITION you get an extra record for each unmatched record in
the left table of the join - thus ensuring (in my example) that every
PERSON gets a mention:
105 | P a g e
| Mr Pullen | 01380 724040 | The Melksham Florist |
+------------+--------------+----------------------+
5 rows in set (0.00 sec)
A MySQL left join is different from a simple join. A MySQL LEFT JOIN
gives extra consideration to the table that is on the left.
If you do a LEFT JOIN, you get all records that match in the same way
and IN ADDITION I get an extra record for each unmatched record in the
left table of the join - thus ensuring (in my example) that every
AUTHOR gets a mention:
Example:
Enter password:*******
Database changed
+-------------+-----------------+----------------+
+-------------+-----------------+----------------+
| 1 | John Poul | 1 |
| 2 | Abdul S | NULL |
| 3 | Sanjay | 1 |
+-------------+-----------------+----------------+
106 | P a g e
Right Join
+------------+----------+--------------+
+------------+----------+--------------+
| Steve | 2 | Shoes |
| John | 1 | Laptop |
| Larry | 1 | Monitor |
| Michael | 5 | Monitor |
+------------+----------+--------------+
What happens here is Mysql starts with the Right table (products). For
each id from the table products MySQL scans the left table - buyers to
find the matching pid. When it finds the matching pid it returns the
buyer_name and the quantity. For unmatched rows it returns null. From
my example above it returns NULL for DVD because no one bought DVD.
First of all, outer joins are for instances where info is being looked
up on another table and you want rows returned even though nothing was
matched for a particular id, e.g.:
107 | P a g e
'apple', 'N', 'cat'),
(NULL, 'oranges', 'N', 'cat');
table 'food'
table 'animals'
name weight
---- ------
Cat 12
Dog 25
Let's say you want a list of all the foods and the weight of the
animals.
If you do:
+---+--------+--------+--------+--------+
| id| food |yummy | animal | weight |
+---+--------+--------+--------+--------+
| 5 | apple | N | cat | 12 |
| 6 | orange | N | cat | 12 |
| 3 | apple | N | dog | 25 |
| 4 | oranges| N | dog | 25 |
+---+--------+--------+--------+--------+
Notice that humans is missing, but if you want the humans to show up
even
though there's no human entry in the 'animals' table you have to do an
outer join (aka LEFT [OUTER] JOIN in Mysql):
108 | P a g e
In this case the result would be:
+----+---------+-------+--------+--------+
| id | food | yummy | animal | weight |
+----+---------+-------+--------+--------+
| 1 | apple | Y | human | NULL |
| 2 | oranges | Y | human | NULL |
| 3 | apple | N | dog | 25 |
| 4 | oranges | N | dog | 25 |
| 5 | apple | N | cat | 12 |
| 6 | oranges | N | cat | 12 |
+----+---------+-------+--------+--------+
MySQL - LEFT JOIN and RIGHT JOIN, INNER JOIN and OUTER JOIN
109 | P a g e
Person number 3 is (also) selling property number 4 - The Melksham
Florist
Person number 4 is selling property number 5 - Dun Roamin.
+------+------+--------------------+
| pid | spid | selling |
+-----+------+---------------------+
| 1 | 1 | Old House Farm |
| 3 | 2 | The Willows |
| 3 | 3 | Tall Trees |
| 3 | 4 | The Melksham Florist |
| 4 | 5 | Dun Roamin |
+-----+-----+----------------------+
5 rows in set (0.00 sec)
An INNER JOIN does a full join, just like the first example, and the
word OUTER may be added after the word LEFT or RIGHT in the last two
110 | P a g e
examples - it's provided for ODBC compatibility and doesn't add an
extra capabilities.
This INNER JOIN example for MySQL shows you how to combine rows of two
tables using an INNER JOIN. You can write them with the help of the
comma operator or the INNER JOIN keywords. The keywords JOIN and CROSS
JOIN are synonymous with "INNER JOIN".
What can they do?
An INNER JOIN can be used to combine (join) matching rows. This is
important, because they can't be used to identify rows without
matches, i.e. rows in one table that have no match in another table.
To do this, an OUTER JOIN can be used.
Sample data
We will use the following tables for the purpose of this example:
(5, 'printer');
--------------------------------------------------------
(1,10),(2,15),(3,4),(4,12),(5,6);
111 | P a g e
Writing the INNER JOIN
To illustrate how to "join" tables, we are going to generate a listing
of all products which includes the current stock of each product. This
is how to do this using the comma operator:
-- output:
+-----------+----------+-----------+
+-----------+----------+-----------+
| 1 | keyboard | 10 |
| 2 | mouse | 15 |
| 3 | monitor | 4 |
| 4 | harddisk | 12 |
| 5 | printer | 6 |
+-----------+----------+-----------+
First of all, we have to tell MySQL that the selected data is stored
in different tables. To do this, we add all required tables to the
FROM clause, separated by a comma. Additionally, we have to tell MySQL
how to combine the rows using the WHERE clause. In this example we
only need a combinations of rows which belong to the same "productid".
If we omit the WHERE clause, MySQL builds a Cartesian product and
builds all possible combination of rows:
+-----------+---------------+-----------+
+-----------+---------------+-----------+
| 1 | keyboard | 10 |
112 | P a g e
| 2 | mouse | 10 |
| 3 | monitor | 10 |
| 4 | harddisk | 10 |
| 5 | printer | 10 |
| 1 | keyboard | 15 |
| 2 | mouse | 15 |
| 3 | monitor | 15 |
| 4 | harddisk | 15 |
| 5 | printer | 15 |
| 1 | keyboard | 4 |
| 2 | mouse | 4 |
| 3 | monitor | 4 |
| 4 | harddisk | 4 |
| 5 | printer | 4 |
| 1 | keyboard | 12 |
| 2 | mouse | 12 |
| 3 | monitor | 12 |
| 4 | harddisk | 12 |
| 5 | printer | 12 |
| 1 | keyboard | 6 |
| 2 | mouse | 6 |
| 3 | monitor | 6 |
| 4 | harddisk | 6 |
| 5 | printer | 6 |
+-----------+---------------+-----------+
113 | P a g e
Another way to write an INNER JOIN is to use the INNER JOIN keywords
(or a synonym like JOIN / CROSS JOIN). When you use the INNER JOIN
keywords, they are used instead of the comma operator to separate the
tables in the FROM clause. To tell MySQL how to combine the rows,
either ON or USING are used to add a condition for the JOIN:
FROM products p
USING ( productid )
The example uses "USING" because the column which we use to join the
rows has the name "productid". You can also do this using ON, which is
for example required if the columns have different names:
FROM products p
Thus far we have only been getting data from one table at a time. This
is fine for simple takes, but in most real world MySQL usage you will
often need to get data from multiple tables in a single query.
You can use multiple tables in your single SQL query. The act of
joining in MySQL refers to smashing two or more tables into a single
table.
You can use JOINS in SELECT, UPDATE and DELETE statements to join
MySQL tables. We will see an example of LEFT JOIN also which is
different from simple MySQL JOIN.
Example:
Enter password:*******
114 | P a g e
Database changed
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| mahnaz | NULL |
| Jen | NULL |
| Gill | 20 |
| John Poul | 1 |
| Sanjay | 1 |
+-----------------+----------------+
+-----------+---------------+---------------+---------------+
|tutorial_id|tutorial_title |tutorial_author|submission_date|
+-----------+---------------+---------------+---------------+
+-----------+---------------+---------------+---------------+
115 | P a g e
Now we can write a SQL query to join these two tables. This
query will select all the authors from table tutorials_tbl and
will pickup corresponding number of tutorials fromtcount_tbl.
+-------------+-----------------+----------------+
+-------------+-----------------+----------------+
| 1 | John Poul | 1 |
| 3 | Sanjay | 1 |
+-------------+-----------------+----------------+
116 | P a g e
WEEK 5
CREATE
CREATE
RETURNS type
proc_parameter:
func_parameter:
param_name type
type:
characteristic:
117 | P a g e
LANGUAGE SQL
| [NOT] DETERMINISTIC
| COMMENT 'string'
routine_body:
mysql> delimiter //
-> BEGIN
-> END;
-> //
mysql> delimiter ;
+------+
| @a |
118 | P a g e
+------+
| 3 |
+------+
characteristic:
| COMMENT 'string'
CALL sp_name([parameter[,...]])
119 | P a g e
CALL sp_name[()]
BEGIN
END;
+------------+---------------------+
120 | P a g e
| @version | @increment |
+------------+--------------------+
| 5.0.25-log | 11 |
----------------+-----------------+
121 | P a g e
This SELECT syntax stores selected columns directly into variables.
Therefore, only a single row may be retrieved.
Important
SQL variable names should not be the same as column names. If an SQL
statement, such as a SELECT ... INTO statement, contains a reference
to a column and a declared local variable with the same name, MySQL
currently interprets the reference as the name of a variable. For
example, in the following statement, xname is interpreted as a
reference to the xname variable rather than the xname column:
BEGIN
SELECT newname;
END;
When this procedure is called, the newname variable returns the value
'bob' regardless of the value of the table1.xname column.
1. DECLARE Conditions
2. DECLARE Handlers
DECLARE Conditions
122 | P a g e
condition_value:
| mysql_error_code
DECLARE Handlers
handler_type:
CONTINUE
| EXIT
| UNDO
condition_value:
| condition_name
| SQLWARNING
| NOT FOUND
| SQLEXCEPTION
| mysql_error_code
The DECLARE ... HANDLER statement specifies handlers that each may
deal with one or more conditions. If one of these conditions occurs,
the specified statement is executed. Statement can be a simple
123 | P a g e
statement (for example, SET var_name = value), or it can be a compound
statement written using BEGIN and END.
For a CONTINUE handler, execution of the current routine continues
after execution of the handler statement. For an EXIT handler,
execution terminates for the BEGIN ... END compound statement in which
the handler is declared. (This is true even if the condition occurs in
an inner block.) The UNDO handler type statement is not yet supported.
If a condition occurs for which no handler has been declared, the
default action is EXIT.
A condition_value can be any of the following values:
Example:
mysql> delimiter //
-> BEGIN
-> SET @x = 1;
-> SET @x = 2;
124 | P a g e
-> INSERT INTO test.t VALUES (1);
-> SET @x = 3;
-> END;
-> //
+------+
| @x |
+------+
| 3 |
+------+
The example associates a handler with SQLSTATE 23000, which occurs for
a duplicate-key error. Notice that @x is 3, which shows that MySQL
executed to the end of the procedure. If the line DECLARE CONTINUE
HANDLER FOR SQLSTATE '23000' SET @x2 = 1; had not been present, MySQL
would have taken the default path (EXIT) after the second INSERT
failed due to the PRIMARY KEY constraint, and SELECT @x would have
returned 2.
If you want to ignore a condition, you can declare a CONTINUE handler
for it and associate it with an empty block. For example:
125 | P a g e
DECLARE CONTINUE HANDLER FOR SQLWARNING BEGIN END;
CREATE PROCEDURE p ()
BEGIN
retry:
REPEAT
BEGIN
BEGIN
END;
END;
IF i < 0 THEN
END IF;
SET i = i - 1;
END;
The label is in scope for the IF statement within the block. It is not
in scope for the CONTINUE handler, so the reference there is invalid
and results in an error:
126 | P a g e
To avoid using references to outer labels in handlers, you can use
different strategies:
CREATE PROCEDURE p ()
BEGIN
retry:
REPEAT
BEGIN
BEGIN
END;
END;
LEAVE retry;
END IF;
SET i = i - 1;
END;
127 | P a g e
Views
Table of Contents
ALTER
AS select_statement
This statement changes the definition of a view, which must exist. The
syntax is similar to that for CREATE VIEW and the effect is the same
as for CREATE OR REPLACE VIEW. This statement requires the CREATE VIEW
and DROP privileges for the view, and some privilege for each column
referred to in the SELECT statement.
CREATE
[OR REPLACE]
AS select_statement
128 | P a g e
[WITH [CASCADED | LOCAL] CHECK OPTION]
Base tables and views share the same namespace within a database,
so a database cannot contain a base table and a view that have the
same name.
Views must have unique column names with no duplicates, just like
base tables. By default, the names of the columns retrieved by the
SELECT statement are used for the view column names. To define
explicit names for the view columns, the optional column_list clause
can be given as a list of comma-separated identifiers. The number of
names in column_list must be the same as the number of columns
retrieved by the SELECT statement.
2)
129 | P a g e
mysql> SELECT * FROM v;
+-------+--------+-------+
+-------+--------+-------+
| 3 | 50 | 150 |
+-------+--------+-------+
130 | P a g e
mysql> CREATE VIEW v (mycol) AS SELECT 'abc';
+-------+
| mycol |
+-------+
| mycol |
+-------+
+-------+
| mycol |
+-------+
| abc |
+-------+
131 | P a g e
If you specify the DEFINER clause, these rules determine the legal
DEFINER user values:
If the SQL SECURITY value is DEFINER but the definer account does not
exist when the view is referenced, an error occurs.
Within a stored routine that is defined with the SQL SECURITY DEFINER
characteristic, CURRENT_USER returns the routine creator. This also
affects a view defined within such a routine, if the view definition
contains a DEFINER value of CURRENT_USER.
Example: A view might depend on a stored function, and that function
might invoke other stored routines. For example, the following view
invokes a stored function f():
CALL p1();
ELSE
CALL p2();
END IF;
132 | P a g e
the warning go away, it is sufficient to re-create the view so that
the view definition includes a DEFINER clause.
The optional ALGORITHM clause is a MySQL extension to standard
SQL. It affects how MySQL processes the view. ALGORITHM takes three
values: MERGE, TEMPTABLE, or UNDEFINED. The default algorithm is
UNDEFINED if no ALGORITHM clause is present.
For MERGE, the text of a statement that refers to the view and
the view definition are merged such that parts of the view definition
replace corresponding parts of the statement.
For TEMPTABLE, the results from the view are retrieved into a
temporary table, which then is used to execute the statement.
For UNDEFINED, MySQL chooses which algorithm to use. It prefers
MERGE over TEMPTABLE if possible, because MERGE is usually more
efficient and because a view cannot be updatable if a temporary table
is used.
A reason to choose TEMPTABLE explicitly is that locks can be
released on underlying tables after the temporary table has been
created and before it is used to finish processing the statement. This
might result in quicker lock release than the MERGE algorithm so that
other clients that use the view are not blocked as long.
A view algorithm can be UNDEFINED for three reasons:
The examples assume that there is a view v_merge that has this
definition:
133 | P a g e
v_merge becomes t
* becomes vc1, vc2, which corresponds to c1, c2
The view WHERE clause is added
SELECT c1, c2 FROM t WHERE (c3 > 100) AND (c1 < 100);
Some views are updatable. That is, you can use them in statements
such as UPDATE, DELETE, or INSERT to update the contents of the
underlying table. For a view to be updatable there must be a one-to-
one relationship between the rows in the view and the rows in the
underlying table. There are also certain other constructs that make a
view non-updatable. To be more specific, a view is not updatable if it
contains any of the following
134 | P a g e
Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so
forth)
DISTINCT
GROUP BY
HAVING
UNION or UNION ALL
Subquery in the select list
Certain joins (see additional join discussion later in
this section)
Non-updatable view in the FROM clause
A subquery in the WHERE clause that refers to a table in
the FROM clause
Refers only to literal values (in this case, there is no
underlying table to update)
ALGORITHM = TEMPTABLE (use of a temporary table always
makes a view non-updatable)
The view must contain all columns in the base table that
do not have a default value.
The view columns must be simple column references and not
derived columns. A derived column is one that is not a
simple column reference but is derived from an expression.
These are examples of derived columns:
3.14159
col1 + 3
UPPER(col2)
col3 / col4
(subquery)
A view that has a mix of simple column references and derived columns
is not insertable, but it can be updatable if you update only those
columns that are not derived. Consider this view:
135 | P a g e
This update is not allowable because it attempts to update a derived
column:
Here the v2 and v3 views are defined in terms of another view, v1. v2
has a LOCAL check option, so inserts are tested only against the v2
136 | P a g e
check. v3 has a CASCADED check option, so inserts are tested not only
against its own check, but against those of underlying views. The
following statements illustrate these differences:
MORE EXAMPLES:
mysql>
mysql>
mysql>
mysql> CREATE TABLE Employee(
-> id int,
-> first_name VARCHAR(15),
-> last_name VARCHAR(15),
-> start_date DATE,
-> end_date DATE,
-> salary FLOAT(8,2),
-> city VARCHAR(10),
-> description VARCHAR(15)
-> );
Query OK, 0 rows affected (0.02 sec)
137 | P a g e
Query OK, 1 row affected (0.00 sec)
138 | P a g e
12 | 7897.78 | New York | Manager |
| 8 | James | Cat | 1996-09-17 | 2002-04-
15 | 1232.78 | Vancouver | Tester |
+------+------------+-----------+------------+------------+---------+-
----------+-------------+
8 rows in set (0.00 sec)
mysql>
mysql>
mysql> CREATE TABLE Employee(
-> id int,
-> first_name VARCHAR(15),
-> last_name VARCHAR(15),
-> start_date DATE,
-> end_date DATE,
-> salary FLOAT(8,2),
-> city VARCHAR(10),
-> description VARCHAR(15)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql>
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary,
City, Description)
139 | P a g e
values (1,'Jason', 'Martin', '19960725', '20060725', 1234.56,
'Toronto', 'Programmer');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
> values(2,'Alison', 'Mathews', '19760321', '19860221', 6661.78,
'Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
>values(3,'James', 'Smith', '19781212', '19900315', 6544.78, '
Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
> values(4,'Celia', 'Rice', '19821024', '19990421', 2344.78,
'Vancouver','Manager');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
> values(5,'Robert', 'Black', '19840115', '199808
08', 2334.78, 'Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
> values(6,'Linda', 'Green', '19870730', '199601
04', 4322.78,'New York', 'Tester');
Query OK, 1 row affected (0.00 sec)
140 | P a g e
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
> values(7,'David', 'Larry', '19901231', '199802
12', 7897.78,'New York', 'Manager');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, en
d_Date, salary, City, Description)
-
> values(8,'James', 'Cat', '19960917', '20020415', 1232.78,'
Vancouver', 'Tester');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> select * from Employee;
+------+------------+-----------+------------+------------+---------
+-----------+-------------+
| id | first_name | last_name | start_date | end_date | salary
| city | description |
+------+------------+-----------+------------+------------+---------
+-----------+-------------+
| 1 | Jason | Martin | 1996-07-25 | 2006-07-
25 | 1234.56 | Toronto | Programmer |
| 2 | Alison | Mathews | 1976-03-21 | 1986-02-
21 | 6661.78 | Vancouver | Tester |
| 3 | James | Smith | 1978-12-12 | 1990-03-
15 | 6544.78 | Vancouver | Tester |
| 4 | Celia | Rice | 1982-10-24 | 1999-04-
21 | 2344.78 | Vancouver | Manager |
| 5 | Robert | Black | 1984-01-15 | 1998-08-
08 | 2334.78 | Vancouver | Tester |
| 6 | Linda | Green | 1987-07-30 | 1996-01-
04 | 4322.78 | New York | Tester |
| 7 | David | Larry | 1990-12-31 | 1998-02-
12 | 7897.78 | New York | Manager |
| 8 | James | Cat | 1996-09-17 | 2002-04-
15 | 1232.78 | Vancouver | Tester |
+------+------------+-----------+------------+------------+---------
+-----------+-------------+
8 rows in set (0.00 sec)
141 | P a g e
mysql>
mysql>
mysql>
mysql>
mysql> CREATE VIEW myView (vid, vfirstname) AS
-> SELECT id, first_name FROM employee WHERE id = 1;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql> SELECT * FROM myView;
+------+------------+
| vid | vfirstname |
+------+------------+
| 1 | Jason |
+------+------------+
1 row in set (0.01 sec)
mysql>
mysql>
mysql> drop view myView;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql>
mysql>
mysql> drop table Employee;
Query OK, 0 rows affected (0.00 sec)
142 | P a g e
TRIGGERS
CREATE
143 | P a g e
so much as it represents a type of table operation. For example, an
INSERT trigger is activated by not only INSERT statements but also
LOAD DATA statements because both statements insert rows into a
table.
b4 INT DEFAULT 0
);
DELIMITER |
144 | P a g e
INSERT INTO test2 SET a2 = NEW.a1;
END;
DELIMITER ;
(0), (0), (0), (0), (0), (0), (0), (0), (0), (0);
Suppose that you insert the following values into table test1 as shown
here:
145 | P a g e
mysql> SELECT * FROM test1;
+------+
| a1 |
+------+
| 1 |
| 3 |
| 1 |
| 7 |
| 1 |
| 8 |
| 4 |
| 4 |
+------+
+------+
| a2 |
+------+
| 1 |
| 3 |
| 1 |
| 7 |
| 1 |
146 | P a g e
| 8 |
| 4 |
| 4 |
+------+
+----+
| a3 |
+----+
| 2 |
| 5 |
| 6 |
| 9 |
| 10 |
+----+
+----+------+
| a4 | b4 |
+----+------+
| 1 | 3 |
| 2 | 0 |
147 | P a g e
| 3 | 1 |
| 4 | 2 |
| 5 | 0 |
| 6 | 0 |
| 7 | 1 |
| 8 | 1 |
| 9 | 0 |
| 10 | 0 |
+----+------+
You can refer to columns in the subject table (the table associated
with the trigger) by using the aliases OLD and NEW. OLD.col_name
refers to a column of an existing row before it is updated or deleted.
NEW.col_name refers to the column of a new row to be inserted or an
existing row after it is updated.
The DEFINER clause specifies the MySQL account to be used when
checking access privileges at trigger activation time. If a user value
is given, it should be a MySQL account in 'user_name'@'host_name'
format (the same format used in the GRANT statement). The user_name
and host_name values both are required. The definer can also be given
as CURRENT_USER or CURRENT_USER(). The default DEFINER value is the
user who executes the CREATE TRIGGER statement. (This is the same as
DEFINER = CURRENT_USER.)
If you specify the DEFINER clause, these rules determine the legal
DEFINER user values:
If you do not have the SUPER privilege, the only legal user value is
your own account, either specified literally or by using
CURRENT_USER. You cannot set the definer to some other account.
If you have the SUPER privilege, you can specify any syntactically
legal account name. If the account does not actually exist, a
warning is generated.
148 | P a g e
(MySQL 5.1.6 implements the TRIGGER privilege and requires that
privilege for trigger creation, so at that point both rules come into
play and SUPER is required only for specifying a DEFINER value other
than your own account.)
From MySQL checks trigger privileges like this:
At CREATE TRIGGER time, the user that issues the statement must have
the SUPER privilege.
At trigger activation time, privileges are checked against the
DEFINER user. This user must have these privileges:
o The SUPER privilege.
o The SELECT privilege for the subject table if references to
table columns occur via OLD.col_name or NEW.col_name in the
trigger definition.
o The UPDATE privilege for the subject table if table columns
are targets of SET NEW.col_name = value assignments in the
trigger definition.
o Whatever other privileges normally are required for the
statements executed by the trigger.
At CREATE TRIGGER time, the user that issues the statement must have
the SUPER privilege.
3. Using Triggers
149 | P a g e
uses for triggers are to perform checks of values to be inserted into
a table or to perform calculations on values involved in an update.
A trigger is associated with a table and is defined to activate when
an INSERT, DELETE, or UPDATE statement for the table executes. A
trigger can be set to activate either before or after the triggering
statement. For example, you can have a trigger activate before each
row that is deleted from a table or after each row that is updated.
Important
MySQL triggers are activated by SQL statements only. They are not
activated by changes in tables made by APIs that do not transmit SQL
statements to the MySQL Server; in particular, they are not activated
by updates made using the NDB API.
Here is a simple example that associates a trigger with a table for
INSERT statements. It acts as an accumulator to sum the values
inserted into one of the columns of the table.
The following statements create a table and a trigger for it:
The keyword BEFORE indicates the trigger action time. In this case,
the trigger should activate before each row inserted into the table.
The other allowable keyword here is AFTER.
The keyword INSERT indicates the event that activates the trigger.
In the example, INSERT statements cause trigger activation. You can
also create triggers for DELETE and UPDATE statements.
The statement following FOR EACH ROW defines the statement to
execute each time the trigger activates, which occurs once for each
row affected by the triggering statement In the example, the
triggered statement is a simple SET that accumulates the values
inserted into the amount column. The statement refers to the column
as NEW.amount which means “the value of the amount column to be
inserted into the new row.”
150 | P a g e
mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-
100.00);
+-----------------------+
+-----------------------+
| 1852.48 |
+-----------------------+
In this case, the value of @sum after the INSERT statement has
executed is 14.98 + 1937.50 - 100, or 1852.48.
To destroy the trigger, use a DROP TRIGGER statement. You must specify
the schema name if the trigger is not in the default schema:
Triggers for a table are also dropped if you drop the table.
Trigger names exist in the schema namespace, meaning that all
triggers must have unique names within a schema. Triggers in different
schemas can have the same name.
In addition to the requirement that trigger names be unique for a
schema, there are other limitations on the types of triggers you can
create. In particular, you cannot have two triggers for a table that
have the same activation time and activation event. For example, you
cannot define two BEFORE INSERT triggers or two AFTER UPDATE triggers
for a table. This should rarely be a significant limitation, because
it is possible to define a trigger that executes multiple statements
by using the BEGIN ... END compound statement construct after FOR EACH
ROW. (An example appears later in this section.)
The OLD and NEW keywords enable you to access columns in the rows
affected by a trigger. (OLD and NEW are not case sensitive.) In an
INSERT trigger, only NEW.col_name can be used; there is no old row. In
a DELETE trigger, only OLD.col_name can be used; there is no new row.
In an UPDATE trigger, you can use OLD.col_name to refer to the columns
of a row before it is updated and NEW.col_name to refer to the columns
of the row after it is updated.
A column named with OLD is read only. You can refer to it (if you have
the SELECT privilege), but not modify it. A column named with NEW can
be referred to if you have the SELECT privilege for it. In a BEFORE
trigger, you can also change its value with SET NEW.col_name = value
if you have the UPDATE privilege for it. This means you can use a
151 | P a g e
trigger to modify the values to be inserted into a new row or that are
used to update a row.
In a BEFORE trigger, the NEW value for an AUTO_INCREMENT column is 0,
not the automatically generated sequence number that will be generated
when the new record actually is inserted.
OLD and NEW are MySQL extensions to triggers.
By using the BEGIN ... END construct, you can define a trigger that
executes multiple statements. Within the BEGIN block, you also can use
other syntax that is allowed within stored routines such as
conditionals and loops. However, just as for stored routines, if you
use the mysql program to define a trigger that executes multiple
statements, it is necessary to redefine the mysql statement delimiter
so that you can use the ; statement delimiter within the trigger
definition. The following example illustrates these points. It defines
an UPDATE trigger that checks the new value to be used for updating
each row, and modifies the value to be within the range from 0 to 100.
This must be a BEFORE trigger because the value needs to be checked
before it is used to update the row:
mysql> delimiter //
-> BEGIN
-> END;//
mysql> delimiter ;
152 | P a g e
The trigger cannot use the CALL statement to invoke stored
procedures that return data to the client or that use dynamic SQL.
(Stored procedures are allowed to return data to the trigger through
OUT or INOUT parameters.)
The trigger cannot use statements that explicitly or implicitly
begin or end a transaction such as START TRANSACTION, COMMIT, or
ROLLBACK.
153 | P a g e
Cursors
1. Declaring Cursors
Asensitive: The server may or may not make a copy of its result
table
Read only: Not updatable
Non-scrollable: Can be traversed only in one direction and cannot
skip rows
BEGIN
OPEN cur1;
OPEN cur2;
REPEAT
154 | P a g e
FETCH cur1 INTO a, b;
IF b < c THEN
ELSE
END IF;
END IF;
CLOSE cur1;
CLOSE cur2;
END
1. Declaring Cursors
OPEN cursor_name
This statement fetches the next row (if a row exists) using the
specified open cursor, and advances the cursor pointer.
155 | P a g e
If no more rows are available, a No Data condition occurs with
SQLSTATE value 02000. To detect this condition, you can set up a
handler for it (or for a NOT FOUND condition).
CLOSE cursor_name
mysql>
mysql> CREATE TABLE Employee(
-> id int,
-> first_name VARCHAR(15),
-> last_name VARCHAR(15),
-> start_date DATE,
-> end_date DATE,
-> salary FLOAT(8,2),
-> city VARCHAR(10),
-> description VARCHAR(15)
-> );
Query OK, 0 rows affected (0.03 sec)
mysql>
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date,
salary, City, Description)
-
> values (1,'Jason', 'Martin', '19960725', '20060725', 1234
.56, 'Toronto', 'Programmer');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date,
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_
Date, salary, City, Description)
-
156 | P a g e
> values(3,'James', 'Smith', '19781212', '19900315
', 6544.78, 'Vancouver','Tester');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_
Date, salary, City, Description)-> values(4,'Celia', 'Rice',
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, s
alary, City, Description)
-
> values(5,'Robert', 'Black', '19840115', '19980808', 2334.7
8, 'Vancouver','Tester');
Query OK, 1 row affected (0.01 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, s
alary, City, Description)
-
> values(6,'Linda', 'Green', '19870730', '19960104', 4322.7
8,'New York', 'Tester');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, s
alary, City, Description)
-
> values(7,'David', 'Larry', '19901231', '19980212', 7897.7
8,'New York', 'Manager');
Query OK, 1 row affected (0.00 sec)
mysql>
mysql> insert into Employee(id,first_name, last_name, start_date, end_Date, s
alary, City, Description)
-
> values(8,'James', 'Cat', '19960917', '20020415', 1232.7
8,'Vancouver', 'Tester');
Query OK, 1 row affected (0.02 sec)
mysql>
mysql> select * from Employee;
+------+------------+-----------+------------+------------+---------+-----------+-------------+
| id | first_name | last_name | start_date | end_date | salary | city | description |
+------+------------+-----------+------------+------------+---------+-----------+-------------+
| 1 | Jason | Martin | 1996-07-25 | 2006-07-25 | 1234.56 | Toronto | Programmer |
| 2 | Alison | Mathews | 1976-03-21 | 1986-02-21 | 6661.78 | Vancouver | Tester |
| 3 | James | Smith | 1978-12-12 | 1990-03-15 | 6544.78 | Vancouver | Tester |
| 4 | Celia | Rice | 1982-10-24 | 1999-04-21 | 2344.78 | Vancouver | Manager |
| 5 | Robert | Black | 1984-01-15 | 1998-08-08 | 2334.78 | Vancouver | Tester |
| 6 | Linda | Green | 1987-07-30 | 1996-01-04 | 4322.78 | New York | Tester |
| 7 | David | Larry | 1990-12-31 | 1998-02-12 | 7897.78 | New York | Manager |
| 8 | James | Cat | 1996-09-17 | 2002-04-15 | 1232.78 | Vancouver | Tester |
+------+------------+-----------+------------+------------+---------+-----------+-------------+
8 rows in set (0.00 sec)
157 | P a g e
mysql>
mysql>
mysql>
mysql>
mysql> DELIMITER //
mysql> CREATE FUNCTION city_list() RETURNS VARCHAR(255)
-> BEGIN
->
-> DECLARE finished INTEGER DEFAULT 0;
-> DECLARE city_name VARCHAR(50) DEFAULT "";
-> DECLARE list VARCHAR(255) DEFAULT "";
-> DECLARE city_cur CURSOR FOR SELECT city FROM employee;
-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
->
-> OPEN city_cur;
->
-> get_city: LOOP
-> FETCH city_cur INTO city_name;
-> IF finished THEN
-> LEAVE get_city;
-> END IF;
-> SET list = CONCAT(list,", ",city_name);
-> END LOOP get_city;
->
-> CLOSE city_cur;
->
-> RETURN SUBSTR(list,3);
-> END
-> //
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql>
mysql> SELECT city_list() AS cities;
+------------------------------------------------------------------------------------+
| cities |
+------------------------------------------------------------------------------------+
| Toronto, Vancouver, Vancouver, Vancouver, Vancouver, New York, New York, Vancouver |
+------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql>
mysql> drop function city_list;
Query OK, 0 rows affected (0.00 sec)
mysql>
mysql>
mysql>
mysql> drop table Employee;
Query OK, 0 rows affected (0.01 sec)
158 | P a g e