Intro a MySQL
Intro a MySQL
1
MySQL
MySQL is a very popular, open source DBMS
MySQL databases are relational
Officially pronounced “my Ess Que Ell” (not my sequel).
Handles very large databases;
very fast performance; reliable.
MySQL is compatible with standard SQL
Why are we using MySQL?
Free (much cheaper than Oracle!)
Each student can install MySQL locally.
Multi-user access to a number of
databases offered
Easy to use Shell for creating tables, querying tables, etc.
Easy to use with Java JDBC
MySQL is frequently used by PHP and Perl
6
Commercial version of MySQL is also provided (including
support)
History of MySQL
• Founded and developed by David Axmark, Allan
Larsson, and Michael “Monty” Widenius
• Named after Monty's daughter, My
• MySQL Dolphin logo is “Sakila”, the name of
a town in Arusha, Tanzania
• Written in C and C++
• Works on many different platforms
• Sun acquired MySQL AB in Jan 2008 for $1
billion dollars
MySQL Products Overview
MySQL: characteristics
MySQL Server works in:
• client/server systems → a system that consists
of a multi-threaded SQL server that supports
different backends, several different client
programs and libraries, administrative tools,
and a wide range of application programming
interfaces (APIs).
• embedded systems → provide MySQL Server
as an embedded multi-threaded library that can
be linked into an application to get a smaller,
faster, easier-to-manage standalone product.
MySQL: Features & Benefits
MySQL: Features & Benefits
MySQL: Architecture
MySQL: Community & Customers
MySQL: Workbench
MySQL Workbench enables:
a DBA, developer, or data architect
to visually design, generate, and manage
all types of databases
including Web, OLTP, and data warehouse
databases
It includes everything a data modeler needs for
creating complex ER models, and also
delivers key features for performing difficult
change management and documentation
tasks that are normally time consuming
MySQL: Workbench
Some characteristics
Forward and Reverse Engineering
• A visual data model can easily be transformed
into a physical database on a target MySQL
Server with just a few mouse clicks.
• it can also import SQL scripts to build models
and export models to DDL scripts that can
be run at a later time.
Change Management
MySQL Workbench
Database Documentation
– Documenting database designs can be a time-
consuming process. MySQL Workbench
includes DBDoc that enables a DBA or
developer to deliver point-and-click database
documentation.
– Models can be documented in either HTML or
plain text format, and includes all the objects
and models in a current MySQL Workbench
session
Resources
• General starting point
> http://www.mysql.com/
• Developer focused
> http://dev.mysql.com/
Installing MySQL
Dr. C. d'Amat
MySQL: Installation
Conventions
Connecting to
MySQL
MySQL provides an interactive shell for
creating tables, inserting data, etc.
On Windows, just go to c:\mysql\bin,
and type:
Mysql or
mysql -u user -p;
Or, click on the Windows icon
18
Dr. C. d'Amat
Sample Session
For example:
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
19
Dr. C. d'Amat
Connecting to
HowMySQL
to use the mysql client
mysql is an interactive program that
enables you to:
connect to a MySQL server,
Run queries,
view the results
mysql may also be used in batch
mode:
place your queries in a file beforehand, then tell
mysql to execute the contents of the file
To see amysql
shell> list of--help
options provided by24mysql
Dr. C. d'Amat
MySQL commands
help \h
Quit/exit \q
Cancel the command \c
Change database use
…etc
Dr. C. d'Amat
Basic Queries
Once logged in, you can try some simple queries.
For example:
23
Dr. C. d'Amat
Basic Queries
Keywords may be entered in any lettercase.
The following queries are equivalent:
24
Dr. C. d'Amat
Basic Queries
Here's another query. It demonstrates that
you can use mysql as a simple calculator:
25
Dr. C. d'Amat
Basic Queries
You can also enter multiple statements on a single
line. Just end each one with a semicolon:
26
Dr. C. d'Amat
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_D
ATE;
+------------
--------
+------------
--+
| USER() 27
Dr. C. d'Amat
Command prompt
prompt meaning
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>
33
Dr. C. d'Amat
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 (and for which
the user has privileges):
Using a Database
View Users (Before MySQL 5.7.6)
mysql> SELECT User, Host, Password
FROM mysql.user;
Changing password for a user
After 5.7.6, use SET PASSWORD
mysql> ALTER USER user IDENTIFIED BY
'new_password';
Ex.: ALTER USER 'root'@'localhost'
IDENTIFIED BY 'new_password';
Before 5.7.6, use SET
PASSWORD:
PASSWORD('new_password');
mysql> SET PASSWORD FOR 37
Dr. C. d'Amat
Using a Databases
Create a user
mysql> CREATE USER user
[IDENTIFIED BY 'new-password'];
See “help CREATE USER”
Remove a user
mysql> DROP USER user;
34
Dr. C. d'Amat
Using a Database
Creating a Table
36
Dr. C. d'Amat
Creating a Table
Let’s create a table for storing pets.
Table: pets
name: VARCHAR(20)
owner:
species: VARCHAR(20)
sex:
birth: VARCHAR is
VARCHAR(20)
usually used
date: CHAR(1) to store string
DATE data.
DATE
37
Dr. C. d'Amat
Creating a Table
To create a table, use the CREATE TABLE
command:
38
Dr. C. d'Amat
Showing Tables
To verify that the table has been created:
mysql> show tables;
+------------------+
| Tables_in_test |
+------------------+
| pet |
+------------------+
1 row in set (0.01 sec)
39
Dr. C. d'Amat
Describing Tables
To view a table structure, use the DESCRIBE
command:
40
Dr. C. d'Amat
Deleting a Table
41
Dr. C. d'Amat
Loading
Data
Use the INSERT statement to enter data into
a table.
For example:
42
Dr. C. d'Amat
More data…
name owner species sex birth death
43
Dr. C. d'Amat
44
Dr. C. d'Amat
To Load pet.txt:
45
D r. C. d ' A m a t
For each of the examples ,
assume the following set of data.
name owner species sex birth death
46
Dr. C. d'Amat
Manipulating Instances
of Tables of a
Database
Dr. C. d'Amat
52
Dr. C. d'Amat
Querying Tables
of a
Database
Dr. C. d'Amat
SQL Select
SELECT what_to_select
FROM which_table
WHERE
conditions_to_satisfy
50
Dr. C. d'Amat
Selecting All
Data
The simplest form of SELECT retrieves everything
from a table
51
Dr. C. d'Amat
without
Try the
●
sametheselect:
last (“)
●
without the last (“) and (;)
●
Try with \c 56
Dr. C. d'Amat
54
Dr. C. d'Amat
55
Dr. C. d'Amat
Sorting Data
To sort a result, use an ORDER BY clause.
Example: view animal birthdays, sorted by date:
56
Dr. C. d'Amat
Sorting Data
Sorting Data
58
Dr. C. d'Amat
●
Find out who owns pets (without duplicate)
SELECT DISTINCT owner FROM pet;
59
Dr. C. d'Amat
60
Dr. C. d'Amat
61
Dr. C. d'Amat
62
Dr. C. d'Amat
Pattern Matching
MySQL provides:
standard SQL pattern matching
regular expression pattern matching
SQL Pattern matching:
To perform pattern matching, use the LIKE or NOT LIKE
comparison operators
By default, patterns are case insensitive
Special Characters:
_ Used to match any single character.
% Used to match an arbitrary number of characters.
63
Dr. C. d'Amat
64
Dr. C. d'Amat
65
Dr. C. d'Amat
66
Dr. C. d'Amat
67
Dr. C. d'Amat
68
Dr. C. d'Amat
Regular Expressions
Some characteristics of extended regular expressions:
“.” matches any single character.
A character class [...] matches any character within the
brackets.
• Example: [abc] matches a, b, or c.
• To name a range of characters, use a
dash.
• [a-z] matches any lowercase letter
• [0-9] matches any digit.
“*” matches zero or more instances of the thing
preceding it.
• Example: x* matches any number of x
characters
• [0-9]* matches any number of digits
of the pattern.
• .* matches any number of anything. 73
Dr. C. d'Amat
Reg Ex Example
Find names beginning with b,
70
Dr. C. d'Amat
Reg Ex Example
Find names ending with `fy',
71
Dr. C. d'Amat
Counting Rows
Databases often used to answer the question,
– "How often does a certain type of data occur
in a table?"
– Example: 1) how many pets are sored
– 2) how many pets each owner has
Counting the total number of animals you have is the
same question as “How many rows are in the pet
table?” because there is one record per pet.
The COUNT() function counts the number of non-
NULL results
72
Dr. C. d'Amat
73
Dr. C. d'Amat
●
Find out number of animals per sex
SELECT sex, count(*) FROM pet GROUP BY sex;
75
Dr. C. d'Amat
76
Dr. C. d'Amat
Batch Mode
MySQL used interactively
– to enter queries and view the results.
MySQL can be run in batch mode.
– put the commands you want to run in
a file, then tell mysql to read its input
from the file:
– The created file is script file that
is requested to be executed
shell> mysql < batch-file
●
shell> mysql -t < batch-
Dr. C. d'Amat
Exercise 1
Create a new DB or a table shop in an
existing DB
CREATE TABLE shop (
article INT(4) UNSIGNED ZEROFILL DEFAULT '0000'
NOT NULL,
dealer VARCHAR(20) DEFAULT '' NOT NULL,
price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
PRIMARY KEY(article, dealer));
(3,'C',1.69),(3,'D',1.25),(4,'D',19.95)8;2
Dr. C. d'Amat
Exercise 1
●
Find out the highest item article
SELECT MAX(article) AS article FROM shop;
●
Find the article, dealer, and price of the
most expensive article.
SELECT article, dealer, price
FROM shop
WHERE price=(SELECT
MAX(price) FROM shop);
Exercise 1
●
Find the highest price per article.
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article;
●
For each article, find the dealer(s)with
the most expensive price.
SELECT article, dealer, price
FROM shop s1
WHERE price=(SELECT
MAX(s2.price)
FROM shop s2
WHERE s1.article
= s2.article);
Dr. C. d'Amat
Exercise 2
See Sec. 3.6.9 of
Create the following tables the tutorial for
more details
CREATE TABLE person (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(60) NOT NULL,
PRIMARY KEY (id) );
Exercise 2
Populate the tables
INSERT INTO person VALUES (NULL, 'Antonio Paz');
SELECT @last := LAST_INSERT_ID();
INSERT INTO shirt VALUES
(NULL, 'polo', 'blue', @last),
(NULL, 'dress', 'white', @last),
(NULL, 't-shirt', 'blue', @last);
Exercise 2
●
Find out person names containing
“Lilliana” as a string and having a shirt
of any color but not white
SELECT s.*
FROM person p INNER JOIN shirt s ON s.owner =
p.id
WHERE p.name LIKE '%Lilliana%' AND s.color <>
'white';
83
Dr. C. d'Amat
Exercise 3
●
Build the DB having the following tables
Supervision Head Employee
Employees Matricola Name Age Salary
210 101
101 Mario Rossi 34 4000
210 103
103 Mario Bianchi 23 3500
210 104
104 Luigi Neri 38 6100
231 105
105 Nico Bini 44 3800
301 210
210 Marco Celli 49 6000
301 231
231 Siro Bisi 50 6000
375 252
252 Nico Bini 44 7000
301 Sergio Rossi 34 7000
375 Mario Rossi 50 6500
84
Dr. C. d'Amat
Exercise 3: Queries
Q: Find out matriculation number, name, age,
salary of the employees earning more
than 4000 Euro
(Write the SQL query)