MySQL Overview
MySQL Overview
Isha Narang
MySQL Introduction
• MySQL is an SQL based relational database management system (DBMS)
• Free and Open source SQL (Structured Query Language) database server.
• MySQL is a multi-user, multi-threaded SQL database server.
• MySQL is a client/server implementation consisting of a server daemon
(mysqld) and many different client programs and libraries.
• MySQL runs on more than 20 Platform including Linux/UNIX, Windows X, AIX
and Mac OS X.
• licensed with the GNU General public license. http://www.gnu.org/
• Handles large databases, in the area of 50,000,000+ records, no memory
leaks, secure and host based authentication.
Why MySQL?
Features & Benefits
MySQL reduces the total cost of ownership of database software by
reducing database licensing costs by over 90 percent and cutting systems
downtime by 60 percent. At the same time, it lowers hardware
expenditures by 70 percent and reduces administration, engineering, and
support costs by up to 50 percent.
World's Most popular open source database due to consistent fast
performance, high reliability and ease of use.
Used to save time, money and high volume websites.
Used in Most popular sites like Yahoo, google, YouTube, Nokia, Lucent,
Zappos.com
Database Engine
Many DB engines are available which acts as handlers for different table types. It includes both those handle
transaction-safe tables and non transaction-safe tables.
Types of DB Engines:
• My ISAM – It is the default DB engine. Provides high speed storage and retrieval as well as full text searching
capabilities.
• InnoDB – It is a transaction-safe storage engine with commit, Rollback and crash recovery capabilities.
Support foreign key referential integrity constraints. Provides maximum performance on performing large
volume of data
• Memory/HEAP – provides in memory table.
• ARCHIVE – used for storing large amount of data without indexes.
• CSV – stores data in text files using comma separated values format.
• BLACKHOLE – accepts but doesn't store data and retrieval always return an empty set.
• BDB(BerkeleyDB) – Greater chance of surviving crashes and capable of COMMIT and ROLLBACK operation
on transactions.
• FEDERATED – stores data in remote DB
Basic MySQL Operations
Create table
Insert records
Load data
Retrieve records
Update records
Delete records
Modify table
Join table
Drop table
Optimize table
Count, Like, Order by, Group by
More advanced ones (sub-queries, stored procedures, triggers,
views …)
How MySQL stores data
A MySQL server can store several databases
Databases are stored as directories
Default is at /usr/local/mysql/var/
Tables are stored as files inside each
database (directory)
For each table, it has three files:
table.FRM file containing information about the
table structure
table.MYD file containing the row data
table.MYI containing any indexes belonging with
this table, as well as some statistics about the
table.
Login
mysql –h hostname –u username –p
[password]
Example
% mysql -u usrname -p
Enter password: passowrd
Welcome to the MySQL monitor. Commands end with ;
or \g. Your MySQL connection id is 23 to server version:
3.23.41.
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
Create User and Database
mysql>use mysql;
Use database mysql, used by the system
mysql>insert into user (Host, User,
Password) values (‘localhost’, ‘test1’,
password(‘pass1’));
Create a new database user test1
An alternative
GRANT USAGE ON *.* TO ‘test1’@’localhost‘
IDENTIFIED BY ‘pass1’;
Create User and Database
(cont.)
mysql>insert into db (Host, Db, User, Select_priv,
Insert_priv, Update_priv, Delete_priv, Create_priv,
Drop_priv) values (‘localhost’, ‘testdb’, ‘test1‘, ‘Y’, ‘Y’,
‘Y’, ‘Y’, ‘Y’, ‘Y’);
Create a new database testdb for user test1
mysql>flush privileges
Reloads the privileges from the grant tables in the
database mysql
An alternative
GRANT SELECT, INSERT, UPDATE, DELETE,
Logout MySQL
mysq> quit;
Bulk Load
Load batch data instead of inserting records
one by one
Example
mysql>LOAD DATA LOCAL INFILE '/mysql/HT_E_COLL_270309.txt'
INTO TABLE PAYMENT_HISTORY
FIELDS TERMINATED BY '|'
ESCAPED BY '\\'
LINES TERMINATED BY "\n"
(CONSUMER_NO, RECEIPT_NO, AMT_RECD, PAYMENT_DATE,
MODE_OF_PAYMENT, CHEQ_DD_NO, CHEQ_DD_DATE,
CHEQ_DISHONOUR_FLG, @BILL_TYPE )
set BILL_TYPE = 2;
Query OK, 21 rows affected (0.01 sec)
Records: 21 Deleted: 0 Skipped: 0 Warnings: 0
More Table Retrieval
OR
mysql> select name from student where major = 'BCB' OR major = 'CS';
COUNT (Count query results)
mysql> select count(name) from student where major = 'BCB' OR major = 'CS';
ORDER BY (Sort query results)
mysql> select name from student where major = 'BCB' OR major = 'CS‘ ORDER
BY name;
mysql> select name from student where major = 'BCB' OR major = 'CS‘ ORDER
BY name DESC;
mysql> select * from student where major = 'BCB' OR major = 'CS‘ ORDER BY
student_id ASC, name DESC
LIKE (Pattern matching)
mysql> select name from student where name LIKE "J%";
DISTINCT (Remove duplicates)
mysql> select major from student;
mysql> select DISTINCT major from student;
Group By
Cluster query results based on different
groups
Example
mysql> select major, count(*) from student GROUP BY major;
+---------+----------+
| major | count(*) |
+---------+----------+
| BBMB | 3|
| BCB | 3|
| Chem | 1|
| CS | 5|
| IG | 2|
| Math | 2|
| MCDB | 3|
| Stat | 2|
+---------+------------+
8 rows in set (0.00 sec)
NULL
No Value
Can not use the usual comparison operators (>, =, != …)
Use IS or IS NOT operators to compare with
Example
Id animal food
1 Cat Milk
2 Dog Bone
3 Cow Grass
4 Horse Grass
Table Join
Left Join
Syntax:
SELECT <column_name> FROM <Table1>
LEFT JOIN <Table2>
ON Table1.column = Table2.column
Left join is same as inner join only difference is that it will fetch
records from table1 even if no data in table2
Table Join
Right Join
Syntax:
SELECT <column_name> FROM <Table1>
RIGHT JOIN <Table2>
ON Table1.column = Table2.column
Right will fetch records from table2 even if no data in table1
Table Join
Using
Syntax:
SELECT <column_name> FROM <Table1>
LEFT JOIN <Table2> USING (<column_name>)
Instead of on can use USING if column name is common
Joining Multiple Table
mysql> SELECT artists.Artist, cds.title, genres.genre
-> FROM cds
-> LEFT JOIN genres
-> ON cds.genreID = genres.genreID
-> LEFT JOIN artists
-> ON cds.artistID = artists.artistID;
Join in Update and Delete query.
Table Join
Union
UNION is used to combine the result from multiple SELECT statements into a
single result set.
Example
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;
UNION DISTINCT : The default behavior for UNION is that duplicate rows
are removed from the result
UNION ALL : Duplicate-row removal does not occur and the result includes
all matching rows from all the SELECT statements.
MySQL Optimization
Index
Index columns that you search for
Example
mysql> alter table student add index (name);
Query OK, 22 rows affected (0.00 sec)
Records: 22 Duplicates: 0 Warnings: 0
mysql> describe student;
+---------------+----------------------+--------+-------+---------+---------+
| Field | Type | Null | Key | Default | Extra |
+---------------+----------------------+--------+-------+---------+---------+
| student_ID | int(10) unsigned | | PRI | 0 | |
| name | varchar(20) | | MUL | | |
| major | varchar(10) | YES | | NULL | |
| project_ID | int(10) unsigned | YES | | NULL | |
+--------------+-----------------------+--------+-------+---------+---------+
4 rows in set (0.00 sec)
MySQL Optimization (cont.)
EXPLAIN
Find what is going on a slow query
Example
mysql> EXPLAIN select * from student s,
project p where s.project_ID = p.project_ID
order by p.level;