Sie sind auf Seite 1von 136

MySQL

Introduction:
MySQL is a DBMS (DataBase
Management System) i.e. it is a databse
software.
MySQL is 5.0 can be downloaded from the
website http://dev.mysql.com/downloads.
MySQL runs on all major platforms such
as Windows, Linux, Solaris, Mac OSX etc.

What is SQL?
Full form of SQL is Structured Query
Language. SQL is a language designed
for communicating with the databases. It is
a basic tool for accessing data in a
relational database.

SQL is made up of very few words. It


provides a simple and efficient way to read
and write the data from a database.
SQL is not a proprietary language of any
DBMS. Learning this one language
enables us to interact with any DBMS.
SQL is easy to learn. With the help of
SQL we can perform very complex
database operations.

MySQL is client-server-based databases.


Client server applications are split into two
parts. The server portion is a piece of
software that is responsible for data
access and manipulation.
Client is the piece of software with which
the user interacts.
To use MySQL we need a client, an
application that you use to interact with
MySQL(to give commands to be executed)

There are three tools used as client


application
MySQL command line utility
MySQL Query Browser
MySQL Administrator.
( MySQL command line utility is a part of
core MySQL installation, whereas MySQL
Query Browser and MySQL Administrator
come under GUI tools of MySQL)

Database:
Database is collection of data stored in
some organized fashion. We can consider
it to be similar to a filing cabinet.
We have files in the filing cabinet and
related data is stored in specific files. A file
is called as a table in DBMS.
Hence a database is container of number
of tables.

Relational Database:
When information can be presented in the
form of tables in a database, regardless of
how it is stored, the arrangement of data is
called as relational database. The term
relational database comes from the fact that
data columns are related to each other by
virtue of their values.

Every table in a database has a unique


name that identifies it. That means no
other table in that database can have the
same name.
The database name and the table name
together make the table name unique.
This means one can not use the same
table name in the same database but one
can reuse the table names in different
databases.

Tables are made up of columns. A column


contains a particular piece of information.
For e.g. in a table called CUST we can
have a column containing customer name,
customer address etc.
Each column in a table has an associated
datatype. A datatype defines what type of
data a column can contain.

We will mainly use the following


datatypes
1. Numeric Datatype: Numeric datatypes
store numbers. We will following two
datatypes to store numbers.
INT: This datatype stores integer values and
supports numbers from -2147483648 to
2147483647.
DECIMAL(or DEC): It stores floating point
values with varying levels of precision.

SMALLINT: Stores integer value,


supports numbers from -32768 to 32767
(or 0 to 65535 if UNSIGNED)
BIGINT: Stores integer value supports
numbers from -9223372036854775808 to
9223372036854775807
(or 0 to 18446744073709551615 if
UNSIGNED)

TINYINT: Stores integer value from -128 to


127 (or 0 to 255 if unsigned).
BOOLEAN ( or BOOL): This data type is
used to store value 0 or 1. BOOLEAN
data type is converted into TINYINT.

DECIMAL(or DEC): It stores floating point


values with varying levels of precision. It can
store maximum of 65 digits and supports up to
30 decimals.
FLOAT: Stores small four byte single-precision
floating point values. Precision of floating point
number is between 0 to 24.

DOUBLE: Stores normal eight byte doubleprecision floating point values. Precision is
between 25 to 53.

2.

Date and Time datatypes

DATE: Date from 1000-01-01 to 9999-12-31 in


the format YYYY-MM-DD.

TIME: Time from -838:59:59 to 838:59:59 in


the format HH:MM:SS

DATETIME: A combination of DATE and TIME


in the format YYYY-MM-DD HH:MM:SS. This
type does not have automatic update features
as TIMESTAMP.

TIMESTAMP: Equivalent to DATETIME but with


a smaller range. Range is 1970-01-01 00:00:00
to sometime in 2037. TIMESTAMP is
automatically updated to current date and time
when a new row is inserted or updated.
YEAR: A 2 or 4 digit year 2 digit year supports a
range of 70(1970) to 69(2069), 4 digit year
support a range of 1901 to 2155.

3. String datatypes:
CHAR: Fixed length string from 1 to 255
characters long. Its size must be
specified at the time of creating a table.
If the length is not specified then MySQL
assumes it to be 1.

VARCHAR: Same as CHAR but stores


text of variable size length. Maximum
value of width is 65,535 characters.

TEXT : Variable length text with maximum


size of 64K
MEDIUMTEXT: Same as TEXT but with
maximum size of 16K.
LONGTEXT: Same as TEXT but with a
maximum size of 4GB.

Fixed length string are datatypes that are


defined to accept a fixed number of
characters. It will not accept more than the
specified number of characters. Fixed
length string i.e. CHAR can contain 1 to
255 characters.
MySQL can sort and manipulate fixed
length datatypes more quickly than
variable length.

Data in a table is stored in rows. Every


row in a table should have a column(or
columns) that uniquely identifies it. This
column is called as the primary key.
For e.g. a table called CUST may have
cust_id (unique numeric customer ID) as
the primary key.

Any column can be defined as the primary


key as long as it satisfies the following
conditions.
No two rows can have same primary key
value.
Every row must have a primary key value.
(Primary key columns will not allow NULL
values.)

Generally we have one primary key column


for a table. But we may use multiple
columns together as primary key.
The rules defined for a primary key column
must apply to columns that make up the
primary key

Foreign Key: A column in one table that


contains primary key values from another
table is called as the foreign key. It defines
relationship between two tables.
For e.g. In BILL table CUST_ID can be
used as the foreign key, CUST_ID is
primary key in CUST table.

We need a default database to work with.


We can create a new database with help
of command
CREATE DATABASE
Or
CREATE SCHEMA
The keywords in the commands are not
case sensitive.
For e.g. CREATE DATABASE SHOP;

List of databases can be seen with the


help of command
SHOW DATABASES;
List of tables within a database can be
obtained with the help of statement
SHOW TABLES FROM SHOP;
To use a database called SHOP we give
the command
USE SHOP;

To create a table called CUST following


set of SQL statements is used.
CREATE TABLE CUSTOMER
(CUSTID INT NOT NULL,
NAME CHAR(20) NOT NULL,
CITY CHAR(20) NOT NULL,
PHONE CHAR(20) NULL,
PRIMARY KEY (CUSTID));

To create a table called BILL following set


of SQL statements is used.
CREATE TABLE BILL
(CUSTID INT NOT NULL,
BILLNO INT NOT NULL
AUTO_INCREMENT,
AMT DECIMAL(10,2) NOT NULL,
PRIMARY KEY(BILLNO));

Only one auto_increment column will be


allowed per table and it must be made
primary key.
If we want to use a specific value for
auto_increment column then it can be
entered using INSERT statement. This
value will be accepted as long as it is
unique. Subsequent incrementing will start
using the value manually inserted.

The column name can not contain any comma


or blank spaces or any other special symbol
(except $ and _).
Column name can be up to 64 characters long.
Digits from 0 to 9 will be allowed within a column
name.
Keywords can not be used as column names.
Column name may begin with a digit or $. Same
rules are applicable to the table names. Column
names and table names are case insensitive.

We can create BILL table by defining


foreign key as follows
CREATE TABLE BILL
(CUST_ID INT NOT NULL,
BILLNO INT NOT NULL AUTO_INCREMENT,
AMT DECIMAL(10,2) NOT NULL,
PRIMARY KEY(BILLNO),
FOREIGN KEY (CUST_ID) REFERENCES
CUST (CUST_ID));

The two tables CUST and BILL will be


stored in the database SHOP.
To see the list of columns from table
CUST we use the command
SHOW COLUMNS FROM CUST;
Columns CUST_ID and NAME in CUST
must not be empty as NOT NULL is
specified, whereas address and phone
columns may not be filled.

We may use any name to store CUST_ID in the


table BILL and still define it as foreign key.
For e.g. if we use CNO instead of CUST_ID in
BILL then we define foreign key statement as
FOREIGN KEY (CNO) REFERENCES CUST
(CUST_ID));
SHOW COLUMNS FROM BILL;
displays columns as

Field

Type

Null

Key

CUST_ID

int(11)

NO

MUL

BILLNO

int(11)

NO

PRI

AMT

decimal(10,2)

NO

Default

Extra

auto_increment

MUL against column CUST_ID means that


multiple occurrences in this column will be
allowed.
If foreign key is defined then we can not
delete or update column CUST_ID in CUST
table.

To look at the code used for creating a


table CUST, we use statement
SHOW CREATE TABLE CUST;
MySQL server status information can be
seen with the help of command
SHOW STATUS;

MySQL enables us to specify default


values to be used if no values are
specified when a row is inserted. Default
values are specified using the DEFAULT
keyword in the column definition in the
CREATE TABLE statement. For e.g.

CREATE TABLE EMP


(EMPID INT NOT NULL,
NAME CHAR(20) NOT NULL,
DEPTID CHAR(10) NOT NULL,
DOJ DATE NOT NULL,
CITY CHAR(10) NOT NULL,
PERM BOOL NOT NULL DEFAULT 1,
PRIMARY KEY (EMPID));

BOOLEAN data type is usually taken as


TINYINT. Value 1 is true and 0 is false.
The order of NOT NULL and DEFAULT can
be interchanged.

We may use DESCRIBE as shortcut for


SHOW COLUMNS FROM
For e.g.
DESCRIBE CUST;

To add data to the columns in the table


CUST we use the command INSERT as
follows.
INSERT INTO CUST
VALUES
('1',
'ANAND',
'MUMBAI',
NULL);

It is important to note that values must be


inserted in the order as the order of
columns specified in the table CUST. One
may write an entire SQL statement in a
single line.

One can use INSERT command by


changing order of the columns in the
table. Order in which values are to be
inserted must be specified. Also one can
omit some of the columns provided the
columns are defined to contain NULL
values or some default values.
For e.g.
INSERT INTO CUST
(NAME,CUST_ID,CITY)
VALUES('BEENA',3, 'PUNE');

We may insert values in a table without


specifying the auto increment value.
For e.g. In BILL table BILLNO is an auto
increment column. To generate the next
BILLNO we specify the other column names
and their values in INSERT statement as
follows.
INSERT INTO BILL(CUST_ID,AMT)
VALUES (4,4000);

We can insert two or more in a table by


using a single INSERT statement
For e.g. we insert two rows in BILL table
as follows
INSERT INTO BILL (CUST_ID,AMT)
VALUES(3,5000),
(5,9000);

ALTER STATEMENT:
ALTER statement is used to change the
structure of a table after it has been created.
ALTER statement is used to add columns or
to delete columns from the table. Also it is
used to change type and width of the
columns and to rename the columns.

For e.g.
ALTER TABLE BILL
ADD DT_PUR DATE NULL;
A new column with name DT_PUR will be
added to the table BILL.
ALTER TABLE CUST
ADD GENDER CHAR(1) NOT NULL;

To drop the column DT_PUR we can give


the command
ALTER TABLE BILL
DROP COLUMN DT_PUR ;
The keyword COLUMN in above two
statements is optional.

We can rename a column using ALTER


statement
e.g.
ALTER TABLE CUST CHANGE COLUMN
PHONE CPHONE CHAR(20) NOT NULL ;
ALTER TABLE CUST CHANGE COLUMN
CPHONE PHONE CHAR(10) NOT NULL;
Column name, its type and width can all be
changed in a single statement.

It is advisable not to change data type as we


may lose data.(It is advisable to specify null
or not null in column definition). Keyword
COLUMN is optional.
To make AMT column in BILL table contain
default value as 0 we use ALTER statement as
follows.
ALTER TABLE BILL CHANGE
COLUMN AMT AMT DEC(10,2) NOT NULL
DEFAULT 0;

We can make alterations to two or more


columns at a time using ALTER TABLE
statement for e.g.
ALTER TABLE CUST DROP GENDER,
ADD PIN CHAR(10) NULL;
ALTER TABLE CUST CHANGE NAME
CNAME CHAR(20) NOT NULL, CHANGE
CPHONE PHONE CHAR(10) NULL;

We can rename a table using RENAME


statement
For e.g.
RENAME TABLE CUST TO CUST1;

To see the contents of all the columns


from table CUST give command
SELECT * FROM CUST;
or
SELECT * FROM SHOP.CUST;
To display contents of specific columns
give command
SELECT CUST_ID,NAME,CITY FROM
CUST;

CUST_ID
1
2
3
4
5
6
7
9

NAME
BEENA
GEETA
ANAND
ATUL
RAHUL
LATA
AJAY
DEEPA

CITY
MUMBAI
NAGPUR
PUNE
MUMBAI
MUMBAI
PUNE
MUMBAI
MUMBAI

SELECT CUST.NAME FROM


SHOP.CUST;
To return first few rows we use LIMIT
clause for e.g.
SELECT * FROM CUST LIMIT 5;
It will display the first five rows of table
CUST
SELECT * FROM CUST LIMIT 5,4;
It will display rows from 6 to 9 of table
CUST.

DISTINCT:
To get distinct CUST_ID values from table
BILL we use statement
SELECT DISTINCT CUST_ID FROM
BILL;
If DISTINCT is not specified then all the
rows will be retrieved. That means ALL is
the default value.

ORDER BY
Data in a table can be sorted in ascending
or descending order with help of clause
ORDER BY
For e.g.
SELECT * FROM CUST ORDER BY NAME;
SELECT * FROM CUST ORDER BY NAME
DESC;

Sorting can be done on multiple fields for


e.g.
SELECT * FROM CUST ORDER BY
CITY,NAME;
SELECT * FROM CUST ORDER BY CITY
DESC, NAME;
SELECT * FROM CUST ORDER BY
CITY,NAME DESC;

We can combine ORDER BY and LIMIT


clause
SELECT * FROM CUST
ORDER BY CITY LIMIT 4;
SELECT * FROM CUST
ORDER BY CITY LIMIT 2,3;

WHERE clause: WHERE clause is used


to retrieve those rows which match the
specified condition.
SELECT * FROM CUST WHERE
CITY='MUMBAI' AND CUST_ID<=3;
SELECT * FROM CUST WHERE
CITY='MUMBAI' OR CUST_ID<=3;
SELECT * FROM BILL WHERE
AMT>=5000;

SELECT DISTINCT CUST_ID FROM BILL


WHERE AMT>10000;
CUST_ID
1
2
3
4
7

SELECT CUST_ID,AMT FROM BILL


WHERE AMT>10000 ORDER BY
CUST_ID;
CUST_ID AMT
1

11000

11000

16000

11000

16000

11000

SELECT CUST_ID,NAME,CITY FROM


CUST WHERE CITY<>'MUMBAI';
SELECT CUST_ID,NAME,CITY FROM
CUST WHERE CITY!='MUMBAI';
SELECT * FROM CUST WHERE
NAME<='G' ORDER BY NAME;
SELECT * FROM CUST WHERE
NAME>'G' ORDER BY NAME;

LIKE operator:
SELECT * FROM CUST WHERE NAME LIKE 'A
%';
The above command gives list of all rows for which
NAME begins with letter A
SELECT * FROM CUST WHERE NAME LIKE 'a
%';
The above command gives list of all rows for
which NAME begins with letter a.

SELECT * FROM CUST WHERE NAME


LIKE '%A%';
The above command gives list of all rows
for which NAME contains letter A.
One can combine LIKE operator and
ORDER BY clause.
e.g.
SELECT * FROM CUST WHERE CITY
LIKE 'D%' ORDER BY NAME;

We can combine LIKE operator and AND


operator for e.g.
SELECT * FROM CUST WHERE CNAME
LIKE '%A%' AND CITY='MUMBAI';

SELECT * FROM CUST WHERE


CITY='MUMBAI' ORDER BY NAME;
SELECT * FROM BILL WHERE DT_PUR
BETWEEN '2000-05-05' AND '2002-0909';
The above statement is equivalent to
SELECT * FROM BILL
WHERE DT_PUR >='2000-05-05' AND
DT_PUR <='2002-09-09';
Date must be enclosed in quotes.

SELECT BILLNO, AMT FROM BILL


WHERE AMT BETWEEN 5000 AND 7000;
The above statement is equivalent to
SELECT BILLNO, AMT FROM BILL
WHERE AMT>=5000 AND AMT<=7000;

IN operator:
IN is a keyword used in WHERE clause to
specify a list of values to be matched
using an OR comparison.
e.g. SELECT CUST_ID, NAME
FROM CUST WHERE CUST_ID IN
(2,4) ORDER BY NAME;
It returns CUST_ID and NAME for those
rows for which CUST_ID has value 2 OR
4 in alphabetical order of NAME.

Same task can be accomplished with help


of OR operator as follows
SELECT CUST_ID, NAME
FROM CUST WHERE CUST_ID =2 OR
CUST_ID=4 ORDER BY NAME;
SELECT CUST_ID,NAME,CITY FROM
CUST WHERE CITY IN ('MUMBAI','PUNE');

NOT operator: It is used to negate a


condition. e.g.
SELECT CUST_ID, NAME
FROM CUST WHERE CUST_ID NOT IN
(2,4) ORDER BY NAME;
It returns CUST_ID and NAME for all
those rows for which CUST_ID is other
than 2 or 4.

This task can also be accomplished with


the help of AND operator as follows
SELECT CUST_ID, NAME
FROM CUST WHERE CUST_ID !=2 AND
CUST_ID!=4 ORDER BY NAME;
SELECT CUST_ID,CNAME,CITY FROM
CUST WHERE CITY NOT IN
('MUMBAI','NAGPUR') ORDER BY NAME;

Another example of IN operator


SELECT * FROM CUST WHERE
CUST_ID IN (2,3,4);
SELECT * FROM CUST WHERE
CUST_ID NOT IN (2,3,4);

UPDATE statement:
To modify data in a table UPDATE
statement is used.
It can be used in two ways.
1. To update specific rows in a table.
2. To update all the rows in a table.

Basic format of UPDATE statement


consists of three parts.
1. The table to be updated
2. The column names and their new values
3. The condition which determines which rows
to be updated.

To update specific rows in a table we


WHERE clause
For e.g.
(i) UPDATE BILL
SET DT_PUR ='2007-05-05' WHERE
BILLNO=237;
(ii) UPDATE CUST
SET CITY='MUMBAI',
PHONE='4567889' WHERE CUST_ID=5;

If we omit the WHERE clause in UPDATE


statement then every row in the table gets
updated with the new values.
UPDATE CUST SET CITY='MUMBAI';
For every row ADDRESS gets updated as
MUMBAI.
UPDATE BILL SET AMT=AMT+1000;
Each amt will be increased by 1000.

DELETE statement:
DELETE is used to
1. To delete specific rows from a table
2. To delete all rows from a table

For e.g.
DELETE FROM CUST
WHERE CUST_ID=5;
DELETE FROM BILL WHERE
AMT>=5000;
If we execute DELETE statement without
WHERE clause then all the contents of a
table get deleted.

We can use ORDER BY and LIMIT clause


along with DELETE statement as follows
DELETE FROM BILL ORDER BY CUST_ID
LIMIT 5;
It deletes first 5 rows from the BILL table
after arranging the table in ascending order
of CUST_ID.

DROP statement:
It is used to delete entire table.
e.g. DROP TABLE CUST;
This statement deletes table CUST. There is
no confirmation nor there is an undo.
It can also be used to delete entire
database
e.g. DROP DATABASE SHOP;

Aggregate functions:
Aggregate functions are used to
summarize the data without actually
retrieving it.
AVG(): It returns average value of a
column.

COUNT() : It returns number of rows in a


column.
MAX() and MIN() return the maximum and
minimum values of a column.
SUM() returns total for a column.

GROUP BY clause:
The GROUP BY clause is used to sort the
data into groups for the purpose of
aggregation.
Suppose we want the number of times
each customer has purchased from the
shop then for this we use GROUP BY
clause as follows

SELECT CUST_ID,COUNT(*)
FROM BILL GROUP BY CUST_ID;
SELECT AVG(AMT) FROM BILL
GROUP BY CUST_ID;

SELECT CUST_ID,SUM(AMT) FROM


BILL GROUP BY CUST_ID;
SELECT CUST_ID, COUNT(*),SUM(AMT)
FROM BILL WHERE AMT>=10000
GROUP BY CUST_ID ORDER BY
CUST_ID DESC;

CUST_ID

COUNT(*)
7
6
5
4
3
2
1

1
1
2
1
2
2
1

SUM(AMT)
11000
12000
20000
16000
27000
21000
11000

SELECT CUST_ID, MAX(AMT) FROM


BILL WHERE
AMT>=10000 AND AMT<=15000
GROUP BY CUST_ID ORDER BY
CUST_ID DESC;
SELECT CUST_ID, MIN(AMT) FROM
BILL WHERE
DT_PUR>= '2009-01-01'
GROUP BY CUST_ID ORDER BY
CUST_ID DESC;

A column name can be called by some


other name called as column alias. e.g.
SELECT * , .10*AMT AS DISCOUNT
FROM BILL;
SELECT * , AMT-.10*AMT AS NSP FROM
BILL;
Keyword AS is optional.

MySQL functions:
CONCAT() function is used to combine two
or more strings.
SELECT
CONCAT(NAME , STAYS IN ,CITY) FROM
CUSTOMER;

SELECT
CONCAT(TRIM('
MONDAY
SELECT
CONCAT(RTRIM(' MONDAY
SELECT
CONCAT(LTRIM('
MONDAY

'),' 'TUESDAY');
'),' ','TUESDAY');
'),' ','TUESDAY');

SELECT MID('COMPUTER',4,3);
SELECT SUBSTRING('COMPUTER',4,3);

SELECT RIGHT(NAME,3) FROM CUST;


Returns 3 rightmost characters from NAME
SELECT LEFT(NAME,3) FROM CUST;
Returns 3 leftmost characters from NAME
SELECT UPPER(NAME) FROM CUST;
Returns NAME in uppercase letters. We
may use UCASE instead of UPPER.

SELECT LOWER(CNAME) FROM CUST;


Returns CNAME in lowercase letters. We
may use LCASE instead of LOWER.
LENGTH()
This function returns the number of
characters contained in the given string.
SELECT LENGTH('COMPUTER');

SELECT NOW();
Returns the current date and time.
SELECT TIME(NOW());
Returns the current time.
SELECT TIME('2009-12-14 19:30:00');
Returns the time. i.e. 19:30:00
SELECT CURDATE();
Returns the current date.

SELECT DATE('2009-09-14 19:30:00');


Returns the date i.e. 2009-09-14
SELECT DAY('2009-09-14 19:30:00');
Returns day value i.e. 14
SELECT DAYNAME('2009-09-25 19:30:00');
Returns day name Friday

MONTH()
Returns month from given date
SELECT MONTH('2009-09-10');
MONTHNAME()
Returns name of the month from given date
SELECT MONTHNAME('2009-09-10');
YEAR()
Returns year from given date
SELECT YEAR('2009-09-10');

SELECT MONTH('2009-12-14 19:30:00');


Returns month 12
SELECT MONTHNAME('2009-12-14 9:30:00');
Returns December
SELECT YEAR('2009-12-14 19:30:00');
Returns year i.e. 2009.
ABS()
Returns absolute value of the given number.
SELECT ABS(-10);

POW() or POWER()
Returns a number raised to a power.
SELECT POW(3,2);
MOD()
Returns remainder after dividing first
number by the second
SELECT MOD(5,4);

ROUND()
It rounds off the number to specified number of
decimal places.
SELECT ROUND(123.5678,2);
SQRT()
Returns square root of a positive number
SELECT SQRT(9);
EXP()
Returns e raised to specified power.
SELECT EXP(2);

HAVING clause:
HAVING clause is used to add additional control
to the aggregation of rows in a GROUP BY
operation.
Suppose we want list of all those customers who
have purchased at least twice from the shop we
use HAVING clause as follows
SELECT CUST_ID, COUNT(*) FROM BILL
GROUP BY CUST_ID HAVING COUNT(*)>=2;

A WHERE clause does not work here as


filtering is done based on groups and not
based on individual rows.
SELECT CUST_ID,SUM(AMT) FROM
BILL GROUP BY CUST_ID HAVING
SUM(AMT)>=10000 ORDER BY
CUST_ID;

CUST_ID

SUM(AMT)
1
2
3
4
5
6
7

11000
26000
36000
25000
20000
12000
16000

SELECT CUST_ID,MAX(AMT) FROM BILL


GROUP BY CUST_ID
HAVING SUM(AMT)>=15000 AND
SUM(AMT)<=50000 ORDER BY CUST_ID;
SELECT CUST_ID,COUNT(*),SUM(AMT)
FROM BILL WHERE DT_PUR>='2009-01-01'
GROUP BY CUST_ID HAVING
SUM(AMT)>=10000 ORDER BY CUST_ID;

CUST_ID

COUNT(*)

SUM(AMT)

11000

20000

25000

12000

SELECT CUST_ID,COUNT(*),SUM(AMT)
FROM BILL
WHERE DT_PUR>='2009-01-01'
GROUP BY CUST_ID HAVING
SUM(AMT)>=10000 ORDER BY
SUM(AMT);

CUST_ID

COUNT(*)

SUM(AMT)

11000

12000

20000

25000

JOIN:
Relational Tables:
The two tables discussed so far are
relational tables. Table CUST contains
information about customers visiting a
shop such as customer name, address
etc. Customer identity (CUST_ID) is the
primary key.

Another table BILL contains information


regarding details about bill amount, date
of purchase, bill number (bill number
forms the primary key as this table
contains multiple entries). The two tables
can be related to each other through a
common value which is CUST_ID in this
case.

We have split the information into two


tables so that having multiple occurrences
of the same data ( i.e. CUST_ID, CITY)
can be avoided. This is the basic concept
of a relational database design.
Breaking data into multiple tables makes
storage of data more efficient, data is easy
to manipulate and large amount of data is
easy to handle.

When data is stored in multiple tables, we


can access the data in these tables with
the help of a mechanism called JOIN.
For creating a join we have to specify all
the tables to be included and how they are
related to each other

When columns in different tables are


joined, we have to qualify column names
with their corresponding table names.
e.g.
SELECT NAME,AMT
FROM BILL,CUST WHERE
CUST.CUST_ID=BILL.CUST_ID
ORDER BY NAME;
Order of tables specified with FROM can
be changed.

The join we have used here is called as


Equijoin or Inner Join. A slightly different
syntax can also be used as follows.
SELECT NAME ,AMT
FROM CUST INNER JOIN BILL
ON BILL.CUST_ID=CUST.CUST_ID
ORDER BY NAME;

SELECT NAME ,AMT


FROM BILL INNER JOIN CUST
ON BILL.CUST_ID=CUST.CUST_ID
ORDER BY NAME;
SELECT NAME,AMT
FROM BILL,CUST WHERE
CUST.CUST_ID=BILL.CUST_ID AND
AMT>=10000;

SELECT NAME,AMT
FROM BILL INNER JOIN CUST ON
CUST.CUST_ID=BILL.CUST_ID AND
AMT>=10000;

NAME
GEETA
GEETA
ANAND
ANAND
RAHUL
RAHUL
LATA
AJAY

AMT
11000
10000
16000
11000
10000
10000
12000
11000

SELECT CUST.CUST_ID,NAME ,AMT


FROM CUST INNER JOIN BILL
ON BILL.CUST_ID=CUST.CUST_ID
ORDER BY NAME;

CUST_ID

CNAME

AMT

7 AJAY

11000

7 AJAY

5000

3 ANAND

16000

3 ANAND

11000

4 ATUL

16000

4 ATUL

9000

2 GEETA

11000

6 LATA

12000

5 RAHUL

10000

To access data in all the columns of


each of the tables CUST and BILL we
use SELECT * in JOIN as follows
SELECT CUST.*, BILL.*
FROM BILL,CUST WHERE
CUST.CUST_ID=BILL.CUST_ID
ORDER BY NAME;

or
SELECT CUST.* ,BILL.*
FROM BILL INNER JOIN CUST
ON BILL.CUST_ID=CUST.CUST_ID
ORDER BY NAME;

Same task can be accomplished with the


help of statement
SELECT C.* , B.*
FROM BILL AS B INNER JOIN CUST AS C
ON B.CUST_ID=C.CUST_ID ORDER BY
NAME;
B is called as alias of BILL table and C is an
alias of CUST table. Aliases are used to
improve readability of MySQL statements.
We need not type table name every time.

CUST_ID

NAME

CITY

PHONE

AJAY

MUMBAI

252

11000

AJAY

MUMBAI

265

5000

ANAND

PUNE

4545545

262

16000

ANAND

PUNE

4545545

263

11000

ATUL

MUMBAI

259

16000

ATUL

MUMBAI

264

9000

GEETA

NAGPUR

261

11000

LATA

PUNE

266

12000

2009-09-09

RAHUL

MUMBAI

251

10000

2007-10-10

24444444

CUST_ID

BILLNO

AMT

DT_PUR
2007-08-04

2009-09-09

Subqueries:
A query that is wrapped within another
query. It is also known as inner query.
A subquery is a SELECT statement within
another statement. Subqueries always
appear as part of WHERE clause or
HAVING clause.

In WHERE clause subqueries select the


individual rows. A subquery is always
enclosed in the parentheses. A subquery
must produce a single column of data as
its result, that means we can not use
SELECT * in a subquery.

Outer Query:
A query which contains an inner query or
subquery.
Inner Query:
A query inside another query. It is also
known as subquery.

The ORDER BY clause can not be used in a


subquery. Since the results of a subquery
are used internally and are not displayed
ordering does not make much sense. We
can specify ORDER BY in the main query or
outer query. e.g.
SELECT CUST_ID,NAME,
(SELECT SUM(AMT) FROM BILL
WHERE CUST.CUST_ID=BILL.CUST_ID)
FROM CUST ORDER BY NAME;

In this example SELECT CUST_ID,NAME is


called as the outer query or main query and
(SELECT SUM(AMT) FROM BILL
WHERE CUST.CUST_ID=BILL.CUST_ID)
is called as the subquery.
The above example is a correlated
subquery as reference to the table CUST is
made in it. Table name CUST appears in the
outer query.

Noncorrelated Subquery:
A subquery that stands alone and does not
reference anything from the outer query.
Correlated Subquery:
A subquery that relies on values returned
from the outer query

A subquery can be constructed using IN


clause, for e.g.
SELECT CUST_ID, NAME, CITY
FROM CUST WHERE CUST_ID IN
(SELECT CUST_ID FROM BILL WHERE
AMT>=10000) ORDER BY NAME;

CUST_ID
7
3
4
2
6
5

NAME
AJAY
ANAND
ATUL
GEETA
LATA
RAHUL

CITY
MUMBAI
PUNE
MUMBAI
NAGPUR
PUNE
MUMBAI

This query displays CUST_ID and NAME


from CUST table in alphabetical order of
name for those customers whose AMT is
greater than or equal to 10000.

To retrieve CUST_ID, AMT for those


customers who have AMT>=AVG(AMT) we
use a subquery as
SELECT CUST_ID, AMT FROM BILL
WHERE
AMT>=(SELECT AVG(AMT) FROM BILL);

Subquery using HAVING clause:


Suppose we want to retrieve CUST_ID,
AVG(AMT) for all those customers who have
AVG(AMT) more than AVG(AMT) of the
entire table then we type a subquery using
HAVING clause as

SELECT CUST_ID,AVG(AMT) FROM BILL


GROUP BY CUST_ID HAVING
AVG(AMT)>(SELECT AVG(AMT)FROM
BILL);

Transaction processing is used to maintain


database integrity. It is used to ensure that
the batches of MySQL operations execute
completely or not at all. For e.g. if a row is
wrongly deleted then this can be undone
with the help of ROLLBACK.
Transaction processing is used to manage
INSERT, UPDATE and DELETE
statements. We can not roll back CREATE,
DROP or SELECT statements.

To start a transaction we use the statement


START TRANSACTION
For e.g.
SELECT * from CUST;
START TRANSACTION;
DELETE FROM CUST;
SELECT * FROM CUST;
ROLLBACK;
The deleted rows are retrieved using ROLLBACK.

MySQL statements are usually executed


and written directly to database tables.
This is called implicit commit. This does
not happen within a transaction block.
We can undo the previous MySQL
statements that appear within START
TRANSACTION. This is done with help of
ROLLBACK.

To force explicit commit, the commit statement is


used
For e.g.
START TRANSACTION;
SELECT * FROM CUST;
DELETE FROM CUST WHERE CITY ='PUNE';
SELECT * FROM CUST;
COMMIT;
SELECT * FROM CUST;
Rows with city name PUNE will be deleted.
Transaction block ends after COMMIT or
ROLLBACK.

Das könnte Ihnen auch gefallen