Download as pdf or txt
Download as pdf or txt
You are on page 1of 81

Introduction To MySQL

 What is data?
 What is the difference between data and
information?
 What is a database?
 Examples of databases around you
 What is a DBMS?
 Collection of related data.
 For eg. University database might contain
information about the following:
Entities such as Student, Faculty, Course,
Classroom Relationship between those entities
Some properties of Database:
 Database represents some aspects of real world.
 It is logically coherent collection of data with
some inherent meaning.
 A database is designed , built , populated with
data for a specific purpose. It has intended
group of users and preconceived application.
Data Information Knowledge Action
RELATION: A table of values
 A relation may be thought of as a set of rows/tuples
 A relation may alternately be though of as a set of columns
 Each row represents a fact that corresponds to a real-world
entity or relationship
 Each row has a value of an item or set of items that
uniquely identifies that row in the table
 Each column typically is called by its column name or
column header or attribute name
 Each value of an attribute is derived from an
appropriate domain/type
 The database schema corresponds to variable declarations in programs
 Schema – the overall design/logical structure of database.
Schema Diagram:
Student:
NAME St_no Class Major

 Data in a database at particular moment is called database state or


snapshot.
 Instance – the actual content of the database at a particular point in time
 DBMS stores description of schema construct and constraints known as
Metadata.
Students( sid: string, name: string, login: string,
age: integer, gpa: real )

sid name login age gpa


53666 Jones jones@cs 18 3.4
53688 Smith smith@ee 18 3.2
53650 Smith smith@math 19 3.8
 Specification notation for defining the database
schema
Example: create table account (
account_number char(10),
branch_name char(10),
balance integer)
 DDL compiler generates a set of tables stored in a
data dictionary
 Data dictionary contains metadata (i.e., data about
data)
 Database schema
 Data storage and definition language
 Specifies the storage structure and access methods used
 Integrity constraints
 Domain constraints
 Referential integrity (e.g. branch_name must correspond to a
valid branch in the branch table)
 Authorization information for each relation
 Languagefor accessing and manipulating the
data organized by the appropriate data
model
 DML also known as query language
 Two classes of languages
 Procedural – user specifies what data is required
and how to get those data
 Declarative (nonprocedural) – user specifies
what data is required without specifying how to
get those data
 SQL is the most widely used query language
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.
• Application programs generally access databases through one of
– Language extensions to allow embedded SQL
– Application program interface (e.g., ODBC/JDBC) which allow SQL queries
to be sent to a database
Resources for practice:
http://sqlzoo.net/
http://www.mysqltutorial.org/basic-mysql-tutorial.aspx
http://www.w3schools.com/sql/
http://www.sqlcourse.com/
http://sol.gfxile.net/g3/
 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

23
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
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
 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

26
 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)
27
 Tocreate a new database, issue the “create
database” command:
 mysql> create database webdb;
 To
the select a database, issue the “use”
command:
 mysql> use webdb;

28
 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)
 char(n). Fixed length character string, with user-specified
length n
 varchar(n). Variable length character strings, with user-
specified maximum length n
 int. Integer (a finite subset of the integers that is machine-
dependent)
 smallint. Small integer (a machine-dependent subset of the
integer domain type)
 numeric(p,d). Fixed point number, with user-specified
precision of p digits, with n digits to the right of decimal
point.
 real, double precision. Floating point and double-precision
floating point numbers, with machine-dependent precision
 float(n). Floating point number, with user-specified
precision of at least n digits
 date(yyyymmdd). Holds a date in the format „yyyy-mm-dd‟ .
Method sysdate() is used to return current date in MySQL
Domain Types in SQL
Create a table ‘pets’ with following
attributes:

| name | owner | species | birth | death


 To create a table, use the CREATE TABLE
command:

mysql> CREATE TABLE pet (


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

33
 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 | |
| birth | date | YES | | NULL | |
| death | date | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
5 rows in set (0.02 sec)

34
By default, newly created table is empty
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,....)
 Use the INSERT statement to enter data
into a table.
 For example:

INSERT INTO pet VALUES


('Fluffy','Harold','cat‘,
'1999-02-04',NULL);
 For multiple tuples entry:
INSERT INTO pet VALUES
('Fluffy','Harold','cat','1999-02-
04',NULL),(‘Pluto’,’Alex’,’dog’,’m’
,’2015-05-31’,NULL);
36
 SQL constraints are used to specify rules for
the data in a table.
 Constraints can be specified when the table
is created (inside the CREATE TABLE
statement) or after the table is created
(inside the ALTER TABLE statement).
 NOT NULL - Indicates that a column cannot store
NULL value
 UNIQUE - Ensures that each row for a column must
have a unique value
 PRIMARY KEY - A combination of a NOT NULL and
UNIQUE. Ensures that a column (or combination of
two or more columns) have an unique identity which
helps to find a particular record in a table more
easily and quickly
 FOREIGN KEY - Ensure the referential integrity of the
data in one table to match values in another table
 CHECK - Ensures that the value in a column meets a
specific condition
 DEFAULT - Specifies a default value when specified
none for this column
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

OR
After table creation:
ALTER TABLE Persons ADD UNIQUE (P_Id);
 The PRIMARY KEY constraint uniquely
identifies each record in a database table.
 Primary keys must contain unique values.
 A primary key column cannot contain NULL
values.
 Each table should have a primary key, and
each table can have only one primary key.
 CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);

 ALTER TABLE Persons ADD PRIMARY KEY (P_Id);

 ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY


(P_Id,LastName);

 ALTER TABLE Persons DROP PRIMARY KEY;


A foreign key is a field (or fields) that points
to the primary key of another table
 The purpose of the foreign key is to ensure
referential integrity of the data
 The FOREIGN KEY constraint also prevents
that invalid data is inserted into the foreign
key column, because it has to be one of the
values contained in the table it points to
•The "P_Id" column in the PERSONS table is its PRIMARY KEY
•The "P_Id" column in the ORDERS table is a FOREIGN KEY
•The ORDERS table cannot contain information on a person that is
not in the PERSONS table

PERSONS

P_Id LastName FirstName City


1 Hansen Ola Sandnes
2 Svendson Tove Sandnes
3 Pettersen Kari Stavanger
ORDERS
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
);

ALTER TABLE Orders ADD FOREIGN KEY (P_Id)


REFERENCES Persons(P_Id);
 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.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CHECK (P_Id>0)
);

ALTER TABLE Persons ADD CHECK (P_Id>0);


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

CHECK(Quantity >= 1 AND Quantity <= 1000));


CHECK (country IN ('USA','UK','India'));
CHECK ((country='India' AND pub_city='Mumbai') OR
(country='India' AND pub_city='New Delhi'));
 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,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
);

ALTER TABLE Persons ALTER City SET DEFAULT 'SANDNES„;

ALTER TABLE Persons ALTER City DROP DEFAULT;


 A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P

 Ai represents an attribute
 Ri represents a relation
 P is a predicate.
OR

SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy

 The result of an SQL query is a relation


 Theselect clause list the attributes desired in the
result of a query
 corresponds to the projection operation of the
relational algebra
 Example: find the names of all branches in the
loan relation:
select branch_name
from loan
 NOTE: SQL names are case insensitive (i.e., you
may use upper- or lower-case letters.)
 E.g. Branch_Name ≡ BRANCH_NAME ≡ branch_name
 Some people use upper case wherever we use bold
font.
 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 keyword all specifies that duplicates not be


removed.

select all branch_name


from loan
 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
 The where clause specifies conditions that the result
must satisfy
 Corresponds to the selection predicate of the relational
algebra.
 To find all loan number for loans made at the
Perryridge branch with loan amounts greater than
$1200.
select loan_number
from loan
where branch_name = 'Perryridge' and
amount > 1200
 Comparison results can be combined using the logical
connectives and, or, and not.
 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)

55
 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)

56
 Ifyou don‟t 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.

57
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)

58
 Operator Precedence:
()
NOT
AND, &&
OR, ||
BETWEEN, IN, LIKE
 The AND operator displays a record if both
the first condition AND the second condition
are true.
 The OR operator displays a record if either
the first condition OR the second condition is
true.

 SELECT* FROM Customers


WHERE Country='Germany'
AND (City='Berlin' OR City='München');
| name | owner | species | sex | birth | death

 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";

62
 The IN operator allows you to specify
multiple values in a WHERE clause.
 SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
 SELECT * FROM Customers
WHERE City IN ('Paris','London');
 The BETWEEN operator selects values within
a range. The values can be numbers, text, or
dates.
 SQL BETWEEN Syntax
 SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND v
alue2;
 List in alphabetic order the names of all customers
having a loan in Perryridge branch
select distinct customer-name
from loan
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.
 E.g. order by customer-name desc
 It is possible for tuples to have a null value, denoted by
null, for some of their attributes
 null signifies an unknown value or that a value does not
exist.
 The predicate is null can be used to check for null
values.
 E.g. Find all loan number which appear in the loan relation
with null values for amount.
select loan-number
from loan
where amount is null
 The result of any arithmetic expression involving null is
null
 E.g. 5 + null returns null
 However, aggregate functions simply ignore nulls
 more on this shortly
 SQL includes a string-matching operator for comparisons on character
strings. Patterns are described using two special characters:
 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%’
 Match the name “Main%”
like ‘Main\%’ escape ‘\’
 The opposite of like operation is performed by „not like’
 SQL supports a variety of string operations such as
 concatenation (using “||”)
 converting from upper to lower case (and vice versa)
 finding string length, extracting substrings, etc.
 Return all actors living in Mumbai
 Return all actors whose age is more than 35
 Return all actors whose age is more than 35 and who live in
Mumbai
 Return the name and age of all actors
 Return all actors in decreasing order of their age
 Return the addresses of the actors having age between 20-30
 Return the names of actors over 35 who live in Mumbai OR LA
 Return names of all actors that have the string “is” in their name
 Return all actors with a address starting with any character,
followed by “umbai"
 The SQL allows renaming relations and
attributes using the as clause:
old-name as new-name
 Find the name, loan number and loan
amount of all customers; rename the column
name loan-number as loan-id.

select customer-name, loan-number as loan-


id, amount
from borrower
 Used to update particular existing records in
a table
 UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
 If you omit the WHERE clause, all records
will be updated!
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
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
 The DELETE statement is used to delete rows
in a table
 DELETE FROM table_name
WHERE some_column=some_value;
 Delete all table rows:
 DELETE FROM table_name;

or

DELETE * FROM table_name;


LastName FirstName Address City
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

How to delete "Nina Rasmussen“?


DELETE FROM Person WHERE LastName = 'Rasmussen'

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
 The drop table command deletes all information
about the dropped relation from the database.
 The alter table command is used to add
attributes to an existing relation:
alter table r add A D
where A is the name of the attribute to be
added to relation r and D is the domain of A.
 All tuples in the relation are assigned null as the value
for the new attribute.
 The alter table command can also be used to
drop attributes of a relation:
alter table r drop A
where A is the name of an attribute of relation r
 Dropping of attributes not supported by many
databases
 Example: Adding or modifying table attributes:

ALTER TABLE table1


ADD col4 char(10);

ALTER TABLE table1


MODIFY col1 BIGINT;

ALTER TABLE table1


DROP col2;
 To permanently alter a table name, use
ALTER TABLE table_name RENAME TO
new_table_name;
 To permanently alter a column name, use
ALTER TABLE CHANGE oldcol_name
newcol_name datatype;
 To
delete an entire table, use the DROP
TABLE command:

mysql> drop table pet;


Query OK, 0 rows affected (0.02 sec)

78
 These functions operate on the multiset of values
of a column of a relation, and return a value

returns the smallest value


MIN
in a given column
returns the largest value in
MAX
a given column
returns the sum of the
SUM numeric values in a given
column
returns the average value
AVG
of a given column

returns the total number


COUNT
of values in a given column

returns the number of


COUNT(*)
rows in a table
 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
 The GROUP BY statement is used in
conjunction with the aggregate functions to
group the result-set by one or more columns.

 SELECTcolumn_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
 Findthe number of depositors for each branch.
select branch-name, count (distinct customer-
name)
from depositor
group by branch-name
Note: Attributes in select clause outside of
aggregate functions must appear in group by list
SELECT ENAME, AVG(SALARY)
FROM EMPLOYEE GROUP BY
DEPT ;

Errorat Line 1: Not a GROUP


BY Expression
 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
 Find number of countries with population smaller than
150000
 Find sum of population of all countries in 'Europe'
 For each region, show the region and number of
countries.
 For each region, show the region and number of
countries with populations of at least 10 million.
 List the regions that have a total area of at least 1
million.
 Find average population of 'Poland', 'Germany' and
'Denmark„
 Find medium population density of each region
 Find name and population of the country with the
largest population
 SELECT COUNT(name) FROM bbc WHERE
population < 150000

 SELECT SUM(population) FROM bbc WHERE region


= 'Europe‟

 SELECT region, COUNT(name) FROM bbc GROUP BY


region

 SELECT region, COUNT(name) FROM bbc where


population>10,000,000 GROUP BY region
 SELECTregion FROM bbc GROUP BY region HAVING
SUM(area)>1,000,000

 SELECT AVG(population) FROM bbc WHERE name


IN ('Poland', 'Germany', 'Denmark')

 SELECT region, SUM(population)/SUM(area) AS


density FROM bbc GROUP BY region

 SELECT name, population FROM bbc WHERE


population = (SELECT MAX(population) FROM bbc)
 CREATE TABLE new_table AS (SELECT * FROM old_table);

 For Example:
CREATE TABLE suppliers AS (SELECT * FROM companies
WHERE id > 1000);
 This would create a new table called suppliers that
includes all columns from the companies table
 If there were records in the companies table, then the
new suppliers table would also contain the records
selected by the SELECT statement.

 CREATE TABLE new_table AS (SELECT column_1,


column2, ... column_n FROM old_table); //for copying
some columns
 How can I create an SQL table from another
table without copying any values from the
old table?
 Answer:
CREATE TABLE new_table AS (SELECT * FROM
old_table WHERE 1=2);

You might also like