Vous êtes sur la page 1sur 68

INTRODUCTION TO MYSQL

MYSQL
MySQL is a very popular, open source database.
Officially pronounced my Ess Que Ell (not my
sequel).
Handles very large databases; very fast
performance.
Why are we using MySQL?

Free (much cheaper than Oracle!)


Each student can install MySQL locally.
Easy to use Shell for creating tables, querying tables, etc.
Easy to use with Java JDBC

Structured Query Language


Structured Query Language (SQL) is the language
standardized by the American National Standards Institute
(ANSI) and the International Organization for
Standardization (ISO) for use on relational databases.
It is a declarative rather than procedural language, which
means that users declare what they want without having to
write a step-by-step procedure.

The SQL language was first implemented by the Oracle


Corporation in 1979, with various versions of SQL being
released since then.

SQL DATA DEFINITION LANGUAGE (DDL)


The Data Definition Language (DDL) part of SQL permits
database tables to be created or deleted. We can also define
indexes (keys), specify links between tables, and impose
constraints between database tables.
The most important DDL statements in SQL are:
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

SQL DATA MANIPULATION LANGUAGE (DML)


SQL (Structured Query Language) is a syntax for executing
queries. But the SQL language also includes a syntax to
update, insert, and delete records.
These query and update commands together form the Data
Manipulation Language (DML) part of SQL:
SELECT - extracts data from a database table
UPDATE - updates data in a database table
DELETE - deletes data from a database table
INSERT INTO - inserts new data into a database table

SAMPLE SESSION

For example:

Enter password: *****


Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 241 to server version: 3.23.49
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

To exit the MySQL Shell, just type QUIT or EXIT:

mysql> QUIT
mysql> exit

BASIC QUERIES

You can also enter multiple statements on a single


line. Just end each one with a semicolon:

mysql> SELECT VERSION(); SELECT NOW();


+--------------+
| VERSION()
|
+--------------+
| 3.22.20a-log |
+--------------+
+---------------------+
| NOW()
|
+---------------------+
| 2004 00:15:33 |
+---------------------+

MULTI-LINE COMMANDS
mysql

determines where your statement ends


by looking for the terminating semicolon, not
by looking for the end of the input line.
Here's a simple multiple-line statement:
mysql> SELECT
-> USER()
-> ,
-> CURRENT_DATE;
+--------------------+--------------+
| USER()
| CURRENT_DATE |
+--------------------+--------------+
| joesmith@localhost | 1999-03-18
|
+--------------------+--------------+

CANCELING A COMMAND

If you decide you don't want to execute a command


that you are in the process of entering, cancel it by
typing \c

mysql> SELECT
-> USER()
-> \c
mysql>

USING A DATABASE
To get started on your own database, first check
which databases currently exist.
Use the SHOW statement to find out which databases
currently exist on the server:

mysql> show databases;


+----------+
| Database |
+----------+
| mysql
|
| test
|
+----------+
2 rows in set (0.01 sec)
10

USING A DATABASE

To create a new database, issue the create


database command:
mysql> create database webdb;

To the select a database, issue the use command:


mysql> use webdb;

11

CREATING A TABLE
Once you have selected a database, you can view
all database tables:
mysql> show tables;
Empty set (0.02 sec)

An empty set indicates that I have not created any


tables yet.

12

CREATE TABLE CONSTRUCT

An SQL relation is defined using the create table


command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))

r is the name of the relation


each Ai is an attribute name in the schema of relation r
Di is the data type of attribute Ai

Example:
create table branch
(branch_name
char(15),
branch_city char(30),
assets
integer)

DOMAIN TYPES IN SQL

Type

Description

CHAR(n)

Fixed length character string, with specified length n

VARCHAR(n)

Variable length character string, with specified


maximum length n

INTEGER

Integer (a machine-dependent finite subset of the


integers)

SMALLINT(n)

A small integer (a finite subset of INTEGER)

FLOAT(M,D)

Floating point number, with total number of digits M


and number of digits following the decimal point D

DOUBLE(M,D)

Double-precision floating point number

Similar to data types in classical programming languages

CREATING A TABLE
Once you have selected a database, you can view
all database tables:
mysql> show tables;
Empty set (0.02 sec)

An empty set indicates that I have not created any


tables yet.

15

CREATING A TABLE
Lets create a table for storing pets.
Table: pets

name:
VARCHAR(20)
owner:
VARCHAR(20)
species: VARCHAR(20)
sex:
CHAR(1)
birth:
DATE
date:
DATE
VARCHAR is
usually used
to store string
data.

16

CREATING A TABLE

To create a table, use the CREATE TABLE


command:

mysql> CREATE TABLE pet (


-> name VARCHAR(20),
-> owner VARCHAR(20),
-> species VARCHAR(20),
-> sex CHAR(1),
-> birth DATE, death DATE);
Query OK, 0 rows affected (0.04 sec)

17

SHOWING TABLES
To

verify that the table has been created:


mysql> show tables;
+------------------+
| Tables_in_test
|
+------------------+
| pet
|
+------------------+
1 row in set (0.01 sec)

18

DESCRIBING TABLES

To view a table structure, use the DESCRIBE


command:

mysql> describe pet;


+---------+-------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name
| varchar(20) | YES |
| NULL
|
|
| owner
| varchar(20) | YES |
| NULL
|
|
| species | varchar(20) | YES |
| NULL
|
|
| sex
| char(1)
| YES |
| NULL
|
|
| birth
| date
| YES |
| NULL
|
|
| death
| date
| YES |
| NULL
|
|
+---------+-------------+------+-----+---------+-------+
6 rows in set (0.02 sec)

19

Loading Data

SQL THE INSERT INTO STATEMENT

THE INSERT INTO STATEMENT


The INSERT INTO statement is used to insert new rows into a table.

Syntax
INSERT INTO table_name

VALUES (value1, value2,....)

You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)

LOADING DATA
Use

the INSERT statement to enter data


into a table.
For example:
INSERT INTO pet VALUES
('Fluffy','Harold','cat','f',
'1999-02-04',NULL);
The

next slide shows a full set of sample


data.
22

Constraints

CONSTRAINTS IN CREATE TABLE

Adding constraints to a table enables the database


system to enforce data integrity.

Different types of constraints:


* Not Null

* Default Values

* Unique

* Primary Key

* Foreign Key * Check Condition

24

NOT NULL CONSTRAINT

CREATE TABLE Student (


ID
NUMBER,
Fname VARCHAR2(20) NOT NULL,
Lname VARCHAR2(20) NOT NULL,
);

25

PRIMARY KEY CONSTRAINT

CREATE TABLE Student (


ID
NUMBER PRIMARY KEY,
Fname VARCHAR2(20) NOT NULL,
Lname VARCHAR2(20) NOT NULL,
);

Primary Key implies: * NOT NULL * UNIQUE.


There can only be one primary key.

26

PRIMARY KEY CONSTRAINT


(SYNTAX 2)

CREATE TABLE Students (


ID
NUMBER,
Fname VARCHAR2(20) NOT NULL,
Lname VARCHAR2(20) NOT NULL,
PRIMARY KEY(ID)
);
Needed when the primary key is made up
of two or more fields

27

ANOTHER TABLE
CREATE TABLE Studies(
Course
NUMBER,
Student
NUMBER
);

What should be the primary key?

What additional constraint do we want on


28
Student?

FOREIGN KEY CONSTRAINT


CREATE TABLE Studies(
Course
NUMBER,
Student
NUMBER,
FOREIGN KEY (Student) REFERENCES
Students(ID)
);

NOTE: ID must be unique (or primary key) in


Student

29

SQL CHECK CONSTRAINT


The CHECK constraint is used to limit the value
range that can be placed in a column.
If you define a CHECK constraint on a single
column it allows only certain values for this column.
If you define a CHECK constraint on a table it can
limit the values in certain columns based on values
in other columns in the row.
The CHECK constraint specifies that the column
"P_Id" must only include integers greater than 0.

CHECK CONSTRAINT
CREATE TABLE Order
( OrderNum INTEGER,
ProdNum INTEGER,
Quantity INTEGER,
PRIMARY KEY (OrderNum),
FOREIGN KEY (ProdNum) references Product(ProdNum),

CHECK(Quantity >= 1 AND Quantity <=


1000));
2: CHECK (country IN ('USA','UK','India')),
3: dt_of_pub date CHECK (dt_of_pub LIKE '--/--/---'),
4:CHECK ((country='India' AND pub_city='Mumbai')
OR (country='India' AND pub_city='New Delhi'))

SQL DEFAULT CONSTRAINT


The DEFAULT constraint is used to insert a default
value into a column.
The default value will be added to all new records, if
no other value is specified.
CREATE TABLE Persons
(
P_Id int NOT NULL,
Name varchar(255) NOT NULL,
City varchar(255) DEFAULT 'Sandnes'
)

ALTER COMMAND

The ALTER TABLE command is used to change


the structure of an existing table.
It helps to add or delete columns, change the type
of existing columns, rename columns or the table
itself.

ALTER TABLE table1


ADD col4 char(10).

ALTER TABLE table1


MODIFY col1 BIGINT

ALTER CONSTRAINTS
ALTER TABLE tstpurch
ADD PRIMARY KEY invoice_no (invoice_no);
Here is the primary key after adding a
primary key named invoice_no on
invoice_no column.

ALTER TABLE newbook_mast


ADD FOREIGN KEY(book_id,cate_id)
REFERENCES torder(book_id,cateid);

DROP id,
ADD id int NOT NULL DEFAULT 0,
ADD chano VARCHAR(10) NOT NULL,
ADD chadt date,
DROP PRIMARY KEY,
ADD PRIMARY KEY invoice_no (invoice_no),
DROP INDEX cate_id,
ADD INDEX cate_id(cate_id),
DROP FOREIGN KEY ord_no,
ADD FOREIGN KEY(book_id,cate_id) REFERENCES tor
der(book_id,cate_id);

DROP COMMAND

DELETING A TABLE

To delete an entire table, use the DROP TABLE


command:

mysql> drop table pet;


Query OK, 0 rows affected (0.02 sec)

38

SQL THE UPDATE STATEMENT

THE UPDATE STATEMENT


The UPDATE statement is used to modify the data in a table.

Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value

UPDATE ONE COLUMN IN A ROW


LastName

FirstName

Address

City

Nilsen

Fred

Kirkegt 56

Stavanger

Rasmussen

Storgt 67

We want to add a first name to the person with a last name of "Rasmussen":
UPDATE Person SET FirstName = 'Nina'
WHERE LastName = 'Rasmussen'

LastName

FirstName

Address

City

Nilsen

Fred

Kirkegt 56

Stavanger

Rasmussen

Nina

Storgt 67

UPDATE SEVERAL COLUMNS IN A ROW


LastName

FirstName

Address

City

Nilsen

Fred

Kirkegt 56

Stavanger

Rasmussen

Storgt 67

We want to change the address and add the name of the city:

UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen'

LastName

FirstName

Address

City

Nilsen

Fred

Kirkegt 56

Stavanger

Rasmussen

Nina

Stien 12

Stavanger

SQL THE DELETE STATEMENT

THE DELETE STATEMENT


The DELETE statement is used to delete rows in a table.

Syntax
DELETE FROM table_name

WHERE column_name = some_value

DELETE A ROW
LastName

FirstName

Address

City

Nilsen

Fred

Kirkegt 56

Stavanger

Rasmussen

Nina

Stien 12

Stavanger

"Nina Rasmussen" is going to be deleted:

DELETE FROM Person WHERE LastName = 'Rasmussen'

LastName

FirstName

Address

City

Nilsen

Fred

Kirkegt 56

Stavanger

DELETE ALL ROWS


It is possible to delete all rows in a table without deleting the table. This means
that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name
Or
DELETE * FROM table_name

SQL SELECT
The SELECT statement is used to pull information
from a table.
The general format is:

SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy

47

SELECTING ALL DATA

The simplest form of SELECT retrieves everything


from a table

mysql> select * from pet;


+----------+--------+---------+------+------------+------------+
| name
| owner | species | sex | birth
| death
|
+----------+--------+---------+------+------------+------------+
| Fluffy
| Harold | cat
| f
| 1999-02-04 | NULL
|
| Claws
| Gwen
| cat
| f
| 1994-03-17 | NULL
|
| Buffy
| Harold | dog
| f
| 1989-05-13 | NULL
|
| Fang
| Benny | dog
| m
| 1999-08-27 | NULL
|
| Bowser
| Diane | dog
| m
| 1998-08-31 | 1995-07-29 |
| Chirpy
| Gwen
| bird
| f
| 1998-09-11 | NULL
|
| Whistler | Gwen
| bird
|
| 1997-12-09 | NULL
|
| Slim
| Benny | snake
| m
| 1996-04-29 | NULL
|
+----------+--------+---------+------+------------+------------+
8 rows in set (0.00 sec)

48

SELECTING PARTICULAR ROWS


You

can select only particular rows from


your table.
For example, if you want to verify the
change that you made to Bowser's birth
date, select Bowser's record like this:
mysql> SELECT * FROM pet WHERE name = "Bowser";
+--------+-------+---------+------+------------+-----------+
| name
| owner | species | sex | birth
| death
|
+--------+-------+---------+------+------------+-----------+
| Bowser | Diane | dog
| m
| 1998-08-31 | 1995-07-29
|
+--------+-------+---------+------+------------+-----------+
1 row in set (0.00 sec)
49

SELECTING PARTICULAR ROWS

To find all animals born after 1998.


SELECT * FROM pet WHERE birth >= "1998-1-1";

To find all female dogs.


SELECT * FROM pet WHERE species = "dog" AND sex = "f";

To find all snakes or birds.


SELECT * FROM pet WHERE species = "snake"
OR species = "bird";

| name

| owner

| species | sex

| birth

| death

50

SELECTING PARTICULAR COLUMNS

If you dont want to see entire rows from your table,


just name the columns in which you are interested,
separated by commas.

For example, if you want to know when your pets


were born, select the name and birth columns.

51

SELECTING PARTICULAR COLUMNS


mysql> select name, birth from pet;
+----------+------------+
| name
| birth
|
+----------+------------+
| Fluffy
| 1999-02-04 |
| Claws
| 1994-03-17 |
| Buffy
| 1989-05-13 |
| Fang
| 1999-08-27 |
| Bowser
| 1998-08-31 |
| Chirpy
| 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim
| 1996-04-29 |
+----------+------------+
8 rows in set (0.01 sec)
52

THE SELECT CLAUSE (CONT.)

SQL allows duplicates in relations as well as in query


results.

To

force the elimination of duplicates, insert


the keyword distinct after select.

Find the names of all branches in the loan relations,


and remove duplicates
select distinct branch_name
from loan

THE SELECT CLAUSE (ARTHEMATIC OPERATORS)

An asterisk in the select clause denotes all attributes


select * from loan

The select clause can contain arithmetic


expressions involving the operation, +, , , and /,
and operating on constants or attributes of tuples.

E.g.:

select loan_number, branch_name, amount 100 from loan

OPERATORS PRECEDENCE
Logical operators: AND, OR, NOT
Operator Precedence:
()
NOT , !
AND ,&&
OR,||,
ALL,BETWEEN, IN, LIKE

IN

OPERATOR

IN

operator is used to check whether a


column contains one or more values.

Syntax:

For

expr IN ( value1, value2, value3)

eg:

Select city from member where City IN(Newyork,


Rome, dover, Big city);

BETWEEN
BETWEEN

OPERATOR

operator allows to specify the

range
Syntax:

expr BETWEEN value1 AND value2

For eg:
Select Filmname from films where rating
BETWEEN 3 And 5.

BETWEEN OPERATOR
eg.

List the 1A students whose Math test score is


between 80 and 90 (incl.)
SELECT name, mtest FROM student ;
WHERE class="1A" AND ;
mtest BETWEEN 80 AND 90
Result

name
Luke
Aaron
Gigi

mtest
86
83
84

LIKE

SQL includes a string-matching operator for


comparisons on character strings. The operator like
uses patterns that are described using two special
characters:

OPERATOR

percent (%). The % character matches any substring.


underscore (_). The _ character matches any character.

Find the names of all customers whose street


includes the substring Main.
select customer_name
from customer
where customer_street like '% Main%

AND, NOT, OR Operators


mysql> select studid, name from student where marks > 80 and marks <
100;
(or)
mysql> select studid, name from student where marks > 80 && marks <
100;

mysql> select name, marks, address from student where name like 'a%' or
name like 's%';
(or)
mysql> select name, marks, address from student where name like 'a%' ||
name like 's%';

mysql> select * from student where not (studid=1);


(or)
mysql> select * from student where ! (studid=1);

ORDERING THE DISPLAY OF TUPLES

List in alphabetic order the names of all customers having a


loan in Perryridge branch
select distinct customer_name
from borrower
where branch_name = 'Perryridge'
order by customer_name

We may specify desc for descending order or asc for ascending


order, for each attribute; ascending order is the default.

Example: order by customer_name desc

THE RENAME OPERATION ( USING ALIASES)


SQL allows renaming relations and attributes using the
as clause:
old-name as new-name
E.g. Find the name, loan number and loan amount of all
customers; rename the column name loan_number as
loan_id.

Select loan_number as loan_id


from loan
where loan >10,000

as tells the dbs that you want the results to be known


as the alias loan_id.

AGGREGATE FUNCTIONS

These functions operate on the multiset of


values of a column of a relation, and return a
value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values

AGGREGATE FUNCTIONS (CONT.)

Find the average account balance at the Perryridge branch.


select avg (balance)
from account
where branch_name = 'Perryridge'

Find the number of tuples in the customer relation.

select count (*)


from customer
Find the number of depositors in the bank.

select count (distinct customer_name)


from depositor

Aggregate Functions : THE GROUP BY CLAUSE


The function to divide the tuples into groups and
returns an aggregate for each group.
It is an aggregate functions companion
SELECT food, sum(sold) as totalSold
FROM FoodCart
group by food;
FoodCart

date
02/25/08
02/26/08
02/26/08

food
pizza
hotdog
pizza

sold
349
500
70

food
totalSol
hotdog 500
pizza 419

SQL: THE HAVING CLAUSE


The substitute of WHERE for aggregate functions
Usually, it is an aggregate functions companion
SELECT food, sum(sold) as totalSold
FROM FoodCart
group by food
having sum(sold) > 450;
FoodCart

date
02/25/08
02/26/08
02/26/08

food
pizza
hotdog
pizza

sold
349
500
70

food
totalSol
hotdog 500

AGGREGATE FUNCTIONS HAVING CLAUSE

Find the names of all branches where the


average account balance is more than $1,200.
select branch_name, avg (balance)
from account
group by branch_name
having avg (balance) > 1200
Note: predicates in the having clause are applied after the
formation of groups whereas predicates in the where
clause are applied before forming groups

Employee(empid,nam,phone,deptid, jobid)
Write a query to get the number of employees with the same job.
SELECT job_id, COUNT(*)
FROM employees
GROUP BY job_id;

Write a query to get the average salary for each job ID excluding programmer
SELECT job_id, AVG(salary)
FROM employees
WHERE job_id <> 'IT_PROG'
GROUP BY job_id;

Write a query to get the average salary for all departments employing more than
10 employees.
SELECT job_id, AVG(salary), COUNT(*)
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 10;

Vous aimerez peut-être aussi