IntrotoMySQL 2
IntrotoMySQL 2
Road Map
Introduction to MySQL
Connecting and Disconnecting
Entering Basic Queries
Creating and Using a Database
Attribution
Most of these slides are based directly
on the MySQL Documentation.
Most information comes from Chapter 3,
MySQL Tutorial:
http://www.mysql.com/documentation/
mysql/bychapter/
manual_Tutorial.html#Tutorial
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?
Connecting to MySQL
MySQL provides an interactive shell for
creating tables, inserting data, etc.
On igor, just go to the terminal app and
type:
mysql -h igor -u ma007xyz p
(replace ma007xyz with your username)
Connecting to MySQL
This command tells mysql to connect to
the MySQL server on host igor (-h igor)
as user ma007xyz (-u ma007xyz) and to
prompt for a password (-p).
My SQL password
A password for MySQL will be emailed
to you when your MySQL account is
created for you (your MySQL password
is separate from your normal
Goldsmiths network password).
Sample Session
10
Basic Queries
Once logged in, you can try some simple queries.
For example:
mysql> SELECT VERSION(), CURRENT_DATE;
+-----------+--------------+
| VERSION() | CURRENT_DATE |
+-----------+--------------+
| 3.23.49
| 2002-05-26
|
+-----------+--------------+
1 row in set (0.00 sec)
11
Basic Queries
Keywords may be entered in any lettercase.
The following queries are equivalent:
mysql> SELECT VERSION(), CURRENT_DATE;
mysql> select version(), current_date;
mysql> SeLeCt vErSiOn(), current_DATE;
12
Basic Queries
Here's another query. It demonstrates that
you can use mysql as a simple calculator:
mysql> SELECT SIN(PI()/4), (4+1)*5;
+-------------+---------+
| SIN(PI()/4) | (4+1)*5 |
+-------------+---------+
|
0.707107 |
25 |
+-------------+---------+
13
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 |
+---------------------+
14
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
|
+--------------------+--------------+
15
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>
16
MySQL prompts
notice the prompt. It switches back to
mysql> after you type \c, providing
feedback to indicate that mysql is ready
for a new command.
17
MySQL prompts
The following table shows each of the prompts you
may see and summarizes what they mean about the
state that mysql is in.
18
Typos
Multiple-line statements commonly
occur by accident when you intend to
issue a command on a single line, but
forget the terminating semicolon. In this
case, mysql waits for more input:
mysql> select user()
->
Enter a semicolon to complete the
statement, and mysql executes it
19
Wrong statement
mysql> SELECT * FROM my_table
WHERE name = 'Smith AND age <
30;
'>
Notice the prompt It tells you that mysql
expects to see the rest of an
unterminated string
20
corrections
At this point, what do you do? The
simplest thing is to cancel the
command. However, you cannot just
type \c in this case, because mysql
interprets it as part of the string that it is
collecting. Instead, enter the closing
quote character
'\c
21
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)
22
Using a Database
To create a new database, issue the
create database command:
mysql> create database ma007xyz_webdb;
(replacing ma007xyz with your username)
23
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.
24
Creating a Table
Let s create a table for storing pets.
Table: pets
name:
owner:
species:
sex:
birth:
date:
VARCHAR(20)
VARCHAR(20)
VARCHAR(20)
CHAR(1)
DATE
DATE
VARCHAR is
usually used
to store string
data.
25
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)
26
Showing Tables
To verify that the table has been created:
mysql> show tables;
+------------------+
| Tables_in_test
|
+------------------+
| pet
|
+------------------+
1 row in set (0.01 sec)
27
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)
28
Deleting a Table
Dont do this now ! But to
delete an entire table, use the DROP
TABLE command:
mysql> drop table pet;
Query OK, 0 rows affected (0.02 sec)
29
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);
30
31
Deleting a row
To delete a row from a table
mysql> delete from pet where
name = 'fluffy';
32
More data
name
owner
species
sex birth
Fluffy
Harold
cat
1993-02-04
Claws
Gwen
cat
1994-03-17
Buffy
Harold
dog
1989-05-13
Fang
Benny
dog
1990-08-27
Bowser
Diane
dog
1998-08-31
Chirpy
Gwen
bird
1998-09-11
Whistler
Gwen
bird
Slim
Benny
snake
death
1995-07-29
1997-12-09
m
1996-04-29
33
34
cat
cat
dog
dog
dog
bird
bird
snake
f
m
f
m
m
f
\N
m
1993-02-04
1994-03-17
1989-05-13
1990-08-27
1979-08-31
1998-09-11
1997-12-09
1996-04-29
\N
\N
\N
\N
1995-07-29
\N
\N
\N
35
36
37
owner
species
sex birth
Fluffy
Harold
cat
1993-02-04
Claws
Gwen
cat
1994-03-17
Buffy
Harold
dog
1989-05-13
Fang
Benny
dog
1990-08-27
Bowser
Diane
dog
1998-08-31
Chirpy
Gwen
bird
1998-09-11
Whistler
Gwen
bird
Slim
Benny
snake
death
1995-07-29
1997-12-09
m
1996-04-29
38
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
39
40
41
42
43
Queries
to find out who owns pets, use this
query:
mysql> SELECT owner FROM pet;
To retrieve each unique output record
just once by adding the keyword
DISTINCT:
mysql> SELECT DISTINCT owner
FROM pet;
45
Sorting Data
To sort a result, use an ORDER BY clause.
For example, to view animal birthdays, sorted by
date:
mysql> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name
| birth
|
+----------+------------+
| Buffy
| 1989-05-13 |
| Claws
| 1994-03-17 |
| Slim
| 1996-04-29 |
| Whistler | 1997-12-09 |
| Bowser
| 1998-08-31 |
| Chirpy
| 1998-09-11 |
| Fluffy
| 1999-02-04 |
| Fang
| 1999-08-27 |
+----------+------------+
8 rows in set (0.02 sec)
46
Sorting Data
To sort in reverse order, add the DESC
(descending keyword)
mysql> SELECT name, birth FROM pet ORDER BY birth DESC;
+----------+------------+
| name
| birth
|
+----------+------------+
| Fang
| 1999-08-27 |
| Fluffy
| 1999-02-04 |
| Chirpy
| 1998-09-11 |
| Bowser
| 1998-08-31 |
| Whistler | 1997-12-09 |
| Slim
| 1996-04-29 |
| Claws
| 1994-03-17 |
| Buffy
| 1989-05-13 |
+----------+------------+
8 rows in set (0.02 sec)
47
48
49
Pattern Matching
MySQL provides:
standard SQL pattern matching; and
regular expression pattern matching, similar to those used
by Unix utilities such as vi, grep and sed.
Special Characters:
_ Used to match any single character.
% Used to match an arbitrary number of characters.
50
51
52
53
54
55
Regular Expressions
Some characteristics of extended regular expressions
are:
. matches any single character.
A character class [...] matches any character within the
brackets. For example, [abc] matches a, b, or c. To name a
range of characters, use a dash. [a-z] matches any
lowercase letter, whereas [0-9] matches any digit.
* matches zero or more instances of the thing preceding it.
For example, x* matches any number of x characters, [0-9]*
matches any number of digits, and .* matches any number of
anything.
To anchor a pattern so that it must match the beginning or
end of the value being tested, use ^ at the beginning or $ at
the end of the pattern.
56
Reg Ex Example
To find names beginning with b, use ^ to match the
beginning of the name:
mysql> SELECT * FROM pet WHERE name REGEXP "^b";
+--------+--------+---------+------+------------+------------+
| name
| owner | species | sex | birth
| death
|
+--------+--------+---------+------+------------+------------+
| Buffy | Harold | dog
| f
| 1989-05-13 | NULL
|
| Bowser | Diane | dog
| m
| 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+
57
Reg Ex Example
To find names ending with `fy', use `$' to match the
end of the name:
mysql> SELECT * FROM pet WHERE name REGEXP "fy$";
+--------+--------+---------+------+------------+-------+
| name
| owner | species | sex | birth
| death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat
| f
| 1993-02-04 | NULL |
| Buffy | Harold | dog
| f
| 1989-05-13 | NULL |
+--------+--------+---------+------+------------+-------+
58
Counting Rows
Databases are often used to answer the question,
"How often does a certain type of data occur in a
table?"
For example, you might want to know how many pets
you have, or 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 nonNULL results.
59
60
Batch Mode
In the previous sections, you used
mysql interactively to enter queries and
view the results.
You can also run mysql in batch mode.
To do this, put the commands you want
to run in a file, then tell mysql to read its
input from the file:
shell> mysql < batch-file
61
62
Summary
SQL provides a structured language for
querying/updating multiple databases.
The more you know SQL, the better.
The most important part of SQL is learning to
retrieve data.
selecting rows, columns, boolean operators,
pattern matching, etc.
63