0% found this document useful (0 votes)
29 views45 pages

Practical Book For Mysql

Uploaded by

Sri kanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views45 pages

Practical Book For Mysql

Uploaded by

Sri kanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

MYSQL Installation on Linux

Mysql has two major type of distribution

1. Community

2. Enterprise

under each distribution there are different type of installation files are available. for example

1. tar ball installation also called the binary distribution or no-install installation

2. RPM installation

Binary Installation
About MySQL Binary Installation

MySQL binary installation is the easiest way of installing MySQL. If you have very little
knowledge of linux you will be able to do this installation comfortably.

Steps For Binary Installation

Download the suitable binary package from mysql.com (as per the OS requirement)

1. create mysql user and mysql group


2. groupadd mysql
3. useradd -r -g mysql mysql
4. untar the binary package which you have downloaded from internet.
5. tar zxvf /path-to-tar-file/mysql-version-package.tar.gz
6. Put the untarred Directory in any directory other than / or /root/
7. Create symbolic link
8. ln -s path-to-untarred-mysql/mysql-version mysql (this will let you communicate with
original untarred mysql directory without specifying long complete directory name
i.e. mysql-5.5.9-linux...... )
9. cd mysql
10. Change to ownership of mysql directory
11. chown -R mysql .
12. chgrp -R mysql .
13. Run the mysql_install_db script to create necessary file and system files which are
required to run mysql
14. path-to-mysql/scripts/mysql_install_db --user=mysql
or

go to scripts directory in the mysql directory

./mysql_install_db --user=mysql

With this mysql installation is complete. Above mentioned steps are mandatory for mysql
installation and following steps are optional.

1. cp mysql/support-files/my.cnf /etc/my.cnf
(my.cnf is the configuration file through with you can customize the mysql environment)
2. bin/mysqld_safe --user=mysql &
(this will start mysql server)
3. cp support-files/mysql.server /etc/init.d/mysql.server

Mysql RPM Installation


download the required rpm package (different Operating System have different kind of rpms
available ) from mysql.com

1. download MySQL-5.6.27-1.el6.i686.rpm-bundle.tar

2. Untar the MySQL-5.6.27-1.el6.i686.rpm-bundle.tar

3. it will have following files after untarring

1. MySQL-client-5.6.27-1.el6.i686.rpm
2. MySQL-devel-5.6.27-1.el6.i686.rpm
3. MySQL-embedded-5.6.27-1.el6.i686.rpm
4. MySQL-server-5.6.27-1.el6.i686.rpm
5. MySQL-shared-5.6.27-1.el6.i686.rpm
6. MySQL-shared-compat-5.6.14-1.el6.x86_64.rpm
7. MySQL-shared-compat-5.6.27-1.el6.i686.rpm
8. MySQL-test-5.6.27-1.el6.i686.rpm

Directory Contents of Directory


/usr/bin Client programs and scripts
/usr/sbin The mysqld server
/var/lib/mysql Log files, databases
/usr/share/info MySQL manual in Info format
/usr/share/man Unix manual pages
/usr/include/mysql Include (header) files
/usr/lib/mysql Libraries
Miscellaneous support files, including error messages, character set files,
/usr/share/mysql sample configuration files, SQL for database installation
4. execute in the following sequence

1. rpm -ivh MySQL-shared-compat-5.6.27-1.el6.i686.rpm


2. rpm -ivh MySQL-devel-5.6.27-1.el6.i686.rpm
3. rpm -ivh MySQL-embedded-5.6.27-1.el6.i686.rpm
4. rpm -ivh MySQL-server-5.6.27-1.el6.i686.rpm
5. rpm -ivh MySQL-client-5.6.27-1.el6.i686.rpm

Note : while executing step #4 you may encounter few errors like

file /usr/share/mysql/czech/errmsg.sys from install of MySQL-server-5.6.27-1.el6.i686


conflicts with file from package mysql-libs-5.1.66-2.el6_3.i686
file /usr/share/mysql/danish/errmsg.sys from install of MySQL-server-5.6.27-1.el6.i686
conflicts with file from package mysql-libs-5.1.66-2.el6_3.i686

this is because your current rpm package is conflicting with any existing package. to find out
that execute following command
rpm -qa | grep -i mysql

this will list the existing mysql packages installed on your operating system. Although you
have not manually installed these but they might have come bundled with operating system.
the output of previous command will be as follows

MySQL-devel-5.6.27-1.el6.i686
MySQL-shared-compat-5.6.27-1.el6.i686
Mysql-libs-5.1.66-2.el6_3.i686
MySQL-embedded-5.6.27-1.el6.i686

highlighted one is the package which is conflicting. we will need to remove it for successful
installation.

rpm -e --nodeps mysql-libs-5.1.73-5.el6_6.i686

this command will remove mysql-libs-5.1.73-5.el6_6.i686 and re-execute step 4.

Advantages of Binary installation over RPM


1. More control over the location settings of different files
2. can create multiple mysql installations
Storage Engines supported by your MySQL

The following command display the status information of the server's storage
engines.
mysql> SHOW ENGINES;

+--------------------+---------+--------------------------------------------------------------
--+--------------+------+------------+

| Engine | Support | Comment


| Transactions | XA | Savepoints |

+--------------------+---------+--------------------------------------------------------------
--+--------------+------+------------+

| FEDERATED | NO | Federated MySQL storage engine


| NULL | NULL | NULL |

| MRG_MYISAM | YES | Collection of identical MyISAM tables


| NO | NO | NO |

| MyISAM | YES | MyISAM storage engine


| NO | NO | NO |

| BLACKHOLE | YES | /dev/null storage engine (anything you write to it disappears


) | NO | NO | NO |

| CSV | YES | CSV storage engine


| NO | NO | NO |

| MEMORY | YES | Hash based, stored in memory, useful for temporary tables
| NO | NO | NO |

| ARCHIVE | YES | Archive storage engine


| NO | NO | NO |

| InnoDB | DEFAULT | Supports transactions, row-level locking, and foreign keys


| YES | YES | YES |

| PERFORMANCE_SCHEMA | YES | Performance Schema


| NO | NO | NO |

+--------------------+---------+--------------------------------------------------------------
--+--------------+------+------------+

9 rows in set (0.28 sec)

Setting the Storage Engine


In CREATE TABLE STATEMENT you can add ENGINE table option to mention a storage
engine. See the following CREATE TABLE statements, where different engines have used :
CREATE TABLE t1 (i INT) ENGINE = INNODB;

CREATE TABLE t2 (i INT) ENGINE = CSV;

CREATE TABLE t3 (i INT) ENGINE = MEMORY;

In MySQL 5.6, the default engine is InnoDB. The default storage engine is used if you do not
mention the other engine name in ENGINE option. You can specify the default engine by
using the --default-storage-engine server startup option (Command-Line Format), or by
setting the default-storage-engine option in the my.cnf configuration file.
You can set the default storage engine for the current session by setting the
default_storage_engine variable using set command.
SET default_storage_engine=ARCHIVE;

If you want to convert a table form one storage engine to another, use an ALTER TABLE
statement. See the following statement :
ALTER TABLE table1 ENGINE = InnoDB;

To store the table and column definitions for a new table, MySQL always creates an .frm file.
Depending on the storage engine the table's index and data may be stored in one or more
other files. The server creates the .frm file above the storage engine level.

MYSQL: INNODB STORAGE ENGINE

InnoDB is a storage engine for MySQL that balances high reliability and high
performance. As of MySQL 5.5 and later, it is the default storage engine.

Feaures of InnoDB storage engine :

Storage limits 64TB Transactions Yes Locking granularity

MVCC (Multiversion concurrency control) Yes Geospatial data type support Yes Geospatial indexing support

B-tree indexes Yes T-tree indexes No Hash indexes

Full-text search indexes Yes Clustered indexes Yes Data caches


Index caches Yes Compressed data Yes Encrypted data

Cluster database support No Replication support Yes Foreign key support

Backup / point-in-time recovery Yes Query cache support Yes Update statistics for data dictionary

Advantages of InnoDB storage engine


 InnoDB has maximum performance when processing large data volumes.

 Its DML operations (add, update and delete data) is ACID (atomic, consistent, isolated
and durable) model compatible, with transactions featuring commit, rollback, and crash-
recovery capabilities to protect user data.

 Row-level locking (locks are placed on single records (rows)) system increase multi-user
concurrency and performance. All InnoDB locks held by a transaction are released when
the transaction is committed or aborted.

 InnoDB tables arrange your data on disk to optimize queries based on primary keys.

 InnoDB supports FOREIGN KEY constraints to maintain data integrity. Therefore inserts,
updates, and deletes are all checked to ensure they do not result in inconsistencies
across different tables.

 It is possible to mix InnoDB tables with tables from other MySQL storage engines within
the same statement. For example, you can use a join operation to combine data from
InnoDB and MEMORY tables in a single query.

Creating InnoDB tables :


Use CREATE TABLE statement to create am InnoDB table without any special clauses. As
of MySQL 5.5, it is the default MySQL storage engine. In MySQL 5.6, issuing the CREATE
TABLE statement without an ENGINE= clause creates an InnoDB table. Here is an example
:
mysql> CREATE TABLE table1 (col1 INT, col2 CHAR(30), PRIMARY KEY (col1));

Query OK, 0 rows affected (1.11 sec)

mysql> DESC table1;

+-------+----------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |


+-------+----------+------+-----+---------+-------+

| col1 | int(11) | NO | PRI | 0 | |

| col2 | char(30) | YES | | NULL | |

+-------+----------+------+-----+---------+-------+

2 rows in set (0.21 sec)

The following SHOW TABLE STATUS statement shows the properties of the tables (belongs
to 'tutorial' database).
mysql> SHOW TABLE STATUS FROM tutorial;

+--------+--------+---------+------------+------+----------------+-------------+---
--------------+--------------+-----------+----------------+---------------------+--
-----------+------------+-----------------+----------+----------------+---------+

| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Ma


x_data_length | Index_length | Data_free | Auto_increment | Create_time | U
pdate_time | Check_time | Collation | Checksum | Create_options | Comment |

+--------+--------+---------+------------+------+----------------+-------------+---
--------------+--------------+-----------+----------------+---------------------+--
-----------+------------+-----------------+----------+----------------+---------+

| table1 | InnoDB | 10 | Compact | 0 | 0 | 16384 |


0 | 0 | 0 | NULL | 2014-02-14 12:08:34 | N
ULL | NULL | utf8_general_ci | NULL | | |
+--------+--------+---------+------------+------+----------------+-------------+---
--------------+--------------+-----------+----------------+---------------------+--
-----------+------------+-----------------+----------+----------------+---------+
1 row in set (0.00 sec)

Handling AUTO_INCREMENT in InnoDB :

InnoDB provides a method that improves scalability and performance of SQL statements
that insert rows into tables with AUTO_INCREMENT columns. To use the
AUTO_INCREMENT mechanism with an InnoDB table, an AUTO_INCREMENT column
(col1 in the example) must be defined as part of an index. See the following example :
mysql> CREATE TABLE table1 (col1 INT(10) NOT NULL AUTO_INCREMENT,

col2 CHAR(30), PRIMARY KEY (col1));

Query OK, 0 rows affected (0.50 sec)


Handling FOREIGN KEY Constraints in InnoDB :

MySQL supports foreign keys, which let you cross-reference related data across tables, and
foreign key constraints, which help keep this spread-out data consistent. Foreign key
definitions for InnoDB tables are subject to the following conditions :

 InnoDB permits a foreign key to reference any index column or group of columns. However,
in the referenced table, there must be an index where the referenced columns are listed as
the first columns in the same order.

 InnoDB does not currently support foreign keys for tables with user-defined partitioning. This
means that no user-partitioned InnoDB table may contain foreign key references or columns
referenced by foreign keys.

 InnoDB allows a foreign key constraint to reference a non-unique key. This is an InnoDB
extension to standard SQL.

Limitation: InnoDB table :


 Maximum 1017 columns are allowed in a table (raised in MySQL 5.6.9 from the earlier limit
of 1000).

 Maximum 64 secondary indexes are allowed in a table. Secondary indexes is a type of


InnoDB index that represents a subset of table columns.

 By default, an index key for a single-column index can be up to 767 bytes. The same length
limit applies to any index key prefix.

 The InnoDB internal maximum key length is 3500 bytes, but MySQL itself restricts this to
3072 bytes (combined index key in a multi-column index).

 The maximum row length except for variable-length columns (VARBINARY, VARCHAR,
BLOB and TEXT), is about 8000 bytes for the default page size of 16KB.

 Internally InnoDB supports row sizes larger than 65,535 bytes, but MySQL itself imposes a
row-size limit of 65,535 for the combined size of all columns.

 The maximum table space size is four billion database pages (64TB) and the minimum table
space size is slightly larger than 10MB.

MySQL: MyISAM Storage Engine


MyISAM storage engine is based on the older ISAM storage engine (not
available now) but has many useful extensions.
Features of MyISAM storage engine :

Storage limits 256TB Transactions No Locking granularity

MVCC (Multiversion concurrency control) No Geospatial data type support Yes Geospatial indexing support

B-tree indexes Yes T-tree indexes No Hash indexes

Full-text search indexes Yes Clustered indexes No Data caches

Index caches Yes Compressed data Yes Encrypted data

Cluster database support No Replication support Yes Foreign key support

Backup / point-in-time recovery Yes Query cache support Yes Update statistics for data dictionary

Each MyISAM table is stored on disk in three files.

 An .frm file stores the table format.

 The data file has an .MYD (MYData) extension.

 The index file has an .MYI (MYIndex) extension.

Creating MyISAM tables :


Use CREATE TABLE statement to create am MyISAM table with ENGINE
clause. As of MySQL 5.6, it is necessary to use ENGINE clause to specify the
MyISAM storage engine because InnoDB is the default engine. Here is an
example :
mysql> CREATE TABLE table2 (col1 INT, col2 CHAR(30)) ENGINE = MYISAM;
Query OK, 0 rows affected (0.19 sec)
The following SHOW TABLE STATUS statement shows the properties of the
tables (belongs to 'tutorial' database).
mysql> SHOW TABLE STATUS FROM tutorial;
+--------+--------+---------+------------+------+----------------+-------------+---
----------------+--------------+-----------+----------------+---------------------+
---------------------+------------+-----------------+----------+----------------+--
-------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Ma
x_data_length | Index_length | Data_free | Auto_increment | Create_time |
Update_time | Check_time | Collation | Checksum | Create_options | C
omment |
+--------+--------+---------+------------+------+----------------+-------------+---
----------------+--------------+-----------+----------------+---------------------+
---------------------+------------+-----------------+----------+----------------+--
-------+
| table1 | InnoDB | 10 | Compact | 0 | 0 | 16384 |
0 | 0 | 0 | 1 | 2014-02-14 13:16:16 |
NULL | NULL | utf8_general_ci | NULL | |
|
| table2 | MyISAM | 10 | Fixed | 0 | 0 | 0 | 26
740122787512319 | 1024 | 0 | NULL | 2014-02-14 15:29:18 |
2014-02-14 15:29:18 | NULL | utf8_general_ci | NULL | |
|
+--------+--------+---------+------------+------+----------------+-------------+---
----------------+--------------+-----------+----------------+---------------------+
---------------------+------------+-----------------+----------+----------------+--
-------+
2 rows in set (0.07 sec)

Main characteristics of MyISAM tables :


 Up to 63-bit file length large files are supported on file systems and operating systems that
support large files.

 (232)2(1.844E+19) rows are allowed in a MyISAM table.


 Maximum 64 number of indexes and 16 number of columns per index are allowed.

 The maximum key length is 1000 bytes.

 Internal handling of one AUTO_INCREMENT column per table is supported.

 You can put the data file and index file in different directories on different physical devices to
get more speed with the DATA DIRECTORY and INDEX DIRECTORY table options to
CREATE TABLE

 BLOB and TEXT columns can be indexed.

 NULL values are permitted in indexed columns. This takes 0 to 1 bytes per key.

 Each character column can have a different character set.

 Support for a true VARCHAR type; a VARCHAR column starts with a length stored in one or
two bytes.

 Tables with VARCHAR columns may have fixed or dynamic row length.

 The sum of the lengths of the VARCHAR and CHAR columns in a table may be up to 64KB.

 Arbitrary length UNIQUE constraints.


Corrupted MyISAM Tables :
MyISAM table format is very reliable, but in some occasion you can get
corrupted tables if any of the following events occur :

 The mysqld (Known as MySQL Server) process is killed in the middle of a write.

 Hardware failures.

 An unexpected computer shutdown occurs.

 Using an external program to modify a table

 A software bug in the MySQL or MyISAM code.

MySQL: MEMORY Storage Engine


The MEMORY storage engine creates tables that are stored in memory.
Because the data can be crashed due to hardware or power issues, you can
only use these tables as temporary work areas or read-only caches for data
pulled from other tables. When the MySQL server halts or restarts, the data in
MEMORY tables is lost.

Features of MEMORY storage engine :

Storage limits RAM Transactions No Locking granularity Table

MVCC No Geospatial data type support No Geospatial indexing support No

B-tree indexes Yes T-tree indexes No Hash indexes Yes

Full-text search indexes No Clustered indexes No Data caches N/A

Index caches N/A Compressed data No Encrypted data Yes

Cluster database support No Replication support Yes Foreign key support No

Backup / point-in-time recover Yes Query cache support Yes Update statistics for data dictionary Yes
Creating MEMORY tables :
Use CREATE TABLE statement to create am MEMORY table with ENGINE
clause. As of MySQL 5.6, it is necessary to use ENGINE clause to specify the
MEMORY storage engine because InnoDB is the default engine. The
following example shows how to create and use a MEMORY table :
mysql> SELECT * FROM hr.departments;

+---------------+----------------------+------------+-------------+

| DEPARTMENT_ID | DEPARTMENT_NAME | MANAGER_ID | LOCATION_ID |

+---------------+----------------------+------------+-------------+

| 10 | Administration | 200 | 1700 |

| 20 | Marketing | 201 | 1800 |

| 30 | Purchasing | 114 | 1700 |

| 40 | Human Resources | 203 | 2400 |

| 50 | Shipping | 121 | 1500 |

| 60 | IT | 103 | 1400 |

| 70 | Public Relations | 204 | 2700 |

| 80 | Sales | 145 | 2500 |

| 90 | Executive | 100 | 1700 |

| 100 | Finance | 108 | 1700 |

| 110 | Accounting | 205 | 1700 |

| 120 | Treasury | 0 | 1700 |

|- - - - - - - -|- - - - - - - - - - - |- - - - - - |- - - - - - -|

|- - - - - - - -|- - - - - - - - - - - |- - - - - - |- - - - - - -|

+---------------+----------------------+------------+-------------+

27 rows in set (0.01 sec)


mysql> CREATE TABLE test7 ENGINE = MEMORY SELECT * FROM hr.departments;

Query OK, 27 rows affected (0.06 sec)

Records: 27 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM test7 WHERE LOCATION_ID>1700;

+---------------+------------------+------------+-------------+

| DEPARTMENT_ID | DEPARTMENT_NAME | MANAGER_ID | LOCATION_ID |

+---------------+------------------+------------+-------------+

| 20 | Marketing | 201 | 1800 |

| 40 | Human Resources | 203 | 2400 |

| 70 | Public Relations | 204 | 2700 |

| 80 | Sales | 145 | 2500 |

+---------------+------------------+------------+-------------+

4 rows in set (0.00 sec)

The following SHOW TABLE STATUS statement shows the properties of the
tables (belongs to 'tutorial' database).
mysql> SHOW TABLE STATUS FROM tutorial;

+--------+--------+---------+------------+------+----------------+-------------+---
----------------+--------------+-----------+----------------+---------------------+
---------------------+------------+-----------------+----------+----------------+--
-------+

| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Ma


x_data_length | Index_length | Data_free | Auto_increment | Create_time |
Update_time | Check_time | Collation | Checksum | Create_options | C
omment |

+--------+--------+---------+------------+------+----------------+-------------+---
----------------+--------------+-----------+----------------+---------------------+
---------------------+------------+-----------------+----------+----------------+--
-------+
| table1 | InnoDB | 10 | Compact | 0 | 0 | 16384 |
0 | 0 | 0 | 1 | 2014-02-14 13:16:16 |
NULL | NULL | utf8_general_ci | NULL | |
|

| table2 | MyISAM | 10 | Fixed | 0 | 0 | 0 | 26


740122787512319 | 1024 | 0 | NULL | 2014-02-14 15:29:18 |
2014-02-14 15:29:18 | NULL | utf8_general_ci | NULL | |
|

| test7 | MEMORY | 10 | Fixed | 27 | 39 | 59400 |


16357770 | 0 | 0 | NULL | 2014-02-17 11:06:46 |
NULL | NULL | utf8_general_ci | NULL | |
|
+--------+--------+---------+------------+------+----------------+-------------+---
----------------+--------------+-----------+----------------+---------------------+
---------------------+------------+-----------------+----------+----------------+--
-------+
3 rows in set (0.00 sec)

Remove a MEMORY table :


mysql> DROP TABLE TEST7;
Query OK, 0 rows affected (0.00 sec)
Indexes : The MEMORY storage engine supports both HASH and BTREE
indexes. Adding a USING clause you can specify one or the other for a given
index. See the following examples :
CREATE TABLE test

(id INT, INDEX USING HASH (id))

ENGINE = MEMORY;

CREATE TABLE test

(id INT, INDEX USING BTREE (id))

ENGINE = MEMORY;

When to Use MEMORY storage engine :


 Operations involving transient, non-critical data such as session management or caching.

 In-memory storage for fast access and low latency. Data volume can fit entirely in memory
without causing the operating system to swap out virtual memory pages.
 By default, an index key for a single-column index can be up to 767 bytes. The same length
limit applies to any index key prefix.

 The InnoDB internal maximum key length is 3500 bytes, but MySQL itself restricts this to
3072 bytes (combined index key in a multi-column index).

 The maximum row length except for variable-length columns (VARBINARY, VARCHAR,
BLOB and TEXT), is about 8000 bytes for the default page size of 16KB.

 Internally InnoDB supports row sizes larger than 65,535 bytes, but MySQL itself imposes a
row-size limit of 65,535 for the combined size of all columns.

 The maximum tablespace size is four billion database pages (64TB) and the minimum
tablespace size is slightly larger than 10MB.

MySQL: MERGE Storage Engine


The MERGE storage engine (also known as MRG_MyISAM) is a collection of
identical MyISAM tables (identical column and index information with same
order) that can be used as single table. You must have SELECT, DELETE,
and UPDATE privileges on the MyISAM tables that you map to a MERGE
table.
Creating MERGE tables :
To create a MERGE table, you must specify a UNION=(list-of-tables) option
(indicates which MyISAM tables to use) in the CREAE TABLE statement. The
following example at first we have created three tables with two rows then
merge it into one table use MERGE storage engine :
mysql> CREATE TABLE tabl1 (rollno INT NOT NULL AUTO_INCREMENT PRIMARY KEY, class CH
AR(5), student_name CHAR(40)) ENGINE = MyISAM;

Query OK, 0 rows affected (0.07 sec)

mysql> CREATE TABLE tabl2 (rollno INT NOT NULL AUTO_INCREMENT PRIMARY KEY, class CH
AR(5), student_name CHAR(40)) ENGINE = MyISAM;

Query OK, 0 rows affected (0.06 sec)

mysql> CREATE TABLE tabl3 (rollno INT NOT NULL AUTO_INCREMENT PRIMARY KEY, class CH
AR(5), student_name CHAR(40)) ENGINE = MyISAM;
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO tabl1 (class, student_name) VALUES ('V','Steven'), ('V', 'Neena'
);

Query OK, 2 rows affected (0.07 sec)

Records: 2 Duplicates: 0 Warnings: 0

mysql> INSERT INTO tabl2 (class, student_name) VALUES ('VI','Lex'), ('VI', 'Alexand
er');

Query OK, 2 rows affected (0.02 sec)

Records: 2 Duplicates: 0 Warnings: 0

mysql> INSERT INTO tabl3 (class, student_name) VALUES ('VII','Bruce'), ('VII', 'Dav
id');

Query OK, 2 rows affected (0.01 sec)

Records: 2 Duplicates: 0 Warnings: 0

mysql> CREATE TABLE allclass (rollno INT NOT NULL, class CHAR(5), student_name CHAR
(40)) ENGINE = MERGE UNION = (tabl1, tabl2, tabl3) INSERT_METHOD = LAST;

Query OK, 0 rows affected (0.09 sec)

mysql> select * from allclass;

+--------+-------+--------------+

| rollno | class | student_name |

+--------+-------+--------------+
| 1 | V | Steven |

| 2 | V | Neena |

| 1 | VI | Lex |

| 2 | VI | Alexander |

| 1 | VII | Bruce |

| 2 | VII | David |

+--------+-------+--------------+

6 rows in set (0.00 sec)

The following SHOW TABLE STATUS statement shows the properties of the
tables (belongs to 'tutorial' database).
mysql> SHOW TABLE STATUS FROM tutorial;

+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+

| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_lengt


h | Max_data_length | Index_length | Data_free | Auto_increment | Create_time
| Update_time | Check_time | Collation | Checksum | Create_optio
ns | Comment |

+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+

| allclass | MRG_MYISAM | 10 | Fixed | 6 | 140 | 84


0 | 0 | 0 | 0 | NULL | NULL
| NULL | NULL | utf8_general_ci | NULL |
| |
| tabl1 | MyISAM | 10 | Fixed | 2 | 140 | 28
0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
3:52 | 2014-02-17 14:42:21 | NULL | utf8_general_ci | NULL |
| |
| tabl2 | MyISAM | 10 | Fixed | 2 | 140 | 28
0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
4:01 | 2014-02-17 14:43:09 | NULL | utf8_general_ci | NULL |
| |
| tabl3 | MyISAM | 10 | Fixed | 2 | 140 | 28
0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
4:22 | 2014-02-17 14:43:59 | NULL | utf8_general_ci | NULL |
| |
| table1 | InnoDB | 10 | Compact | 0 | 0 | 1638
4 | 0 | 0 | 0 | 1 | 2014-02-14 13:1
6:16 | NULL | NULL | utf8_general_ci | NULL |
| |
| table2 | MyISAM | 10 | Fixed | 0 | 0 |
0 | 26740122787512319 | 1024 | 0 | NULL | 2014-02-14 15:2
9:18 | 2014-02-14 15:29:18 | NULL | utf8_general_ci | NULL |
| |
| test7 | MEMORY | 10 | Fixed | 27 | 39 | 5940
0 | 16357770 | 0 | 0 | NULL | 2014-02-17 11:0
6:46 | NULL | NULL | utf8_general_ci | NULL |
| |
+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+
7 rows in set (0.16 sec)
Security issue : If a user has access to MyISAM table, say t1, that user can
create a MERGE table m1 that accesses t1. However, if the administrator
revokes the user's privileges on t1, the user can continue to access the data of
t1 through m1.
Top

MySQL: CSV Storage Engine


The CSV storage engine stores data in text files using comma-separated
values format and the CSV storage engine is always compiled into the MySQL
server. The server creates a table format file (.frm extension) and a data file
(.csv extension) in the database directory when you create a CSV table. Both
.frm and .csv files name begins with the table name. The data file is a plain
text file and the storage engine saves data in comma-separated values
format. The following example shows how to create and use a CSV table :
mysql> CREATE TABLE color (slno INT NOT NULL, cname CHAR(30) NOT NULL,

ccode CHAR(6) NOT NULL) ENGINE = CSV;

Query OK, 0 rows affected (0.12 sec)

mysql> INSERT INTO color VALUES(1, 'IndianRed', 'CD5C5C'),


(2, 'LightCoral', 'F08080'), (3, 'Salmon', 'FA8072');

Query OK, 3 rows affected (0.02 sec)

Records: 3 Duplicates: 0 Warnings: 0

mysql> SELECT * from color;

+------+------------+--------+

| slno | cname | ccode |

+------+------------+--------+

| 1 | IndianRed | CD5C5C |

| 2 | LightCoral | F08080 |

| 3 | Salmon | FA8072 |

+------+------------+--------+

3 rows in set (0.00 sec)

You can can read, modify the 'color.CSV' file by spreadsheet applications
such as Microsoft Excel or StarOffice Calc.
CSV Limitations :
 Does not support indexing.

 Does not support partitioning.

 All columns must have the NOT NULL attribute in a CSV table.

The following SHOW TABLE STATUS statement shows the properties of the
tables (belongs to 'tutorial' database).
mysql> SHOW TABLE STATUS FROM tutorial;

+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+

| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_lengt


h | Max_data_length | Index_length | Data_free | Auto_increment | Create_time
| Update_time | Check_time | Collation | Checksum | Create_optio
ns | Comment |

+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+

| allclass | MRG_MYISAM | 10 | Fixed | 6 | 140 | 84


0 | 0 | 0 | 0 | NULL | NULL
| NULL | NULL | utf8_general_ci | NULL |
| |

| color | CSV | 10 | Fixed | 3 | 0 |


0 | 0 | 0 | 0 | NULL | NULL
| NULL | NULL | utf8_general_ci | NULL |
| |
| tabl1 | MyISAM | 10 | Fixed | 2 | 140 | 28
0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
3:52 | 2014-02-17 14:42:21 | NULL | utf8_general_ci | NULL |
| |
| tabl2 | MyISAM | 10 | Fixed | 2 | 140 | 28
0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
4:01 | 2014-02-17 14:43:09 | NULL | utf8_general_ci | NULL |
| |
| tabl3 | MyISAM | 10 | Fixed | 2 | 140 | 28
0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
4:22 | 2014-02-17 14:43:59 | NULL | utf8_general_ci | NULL |
| |
| table1 | InnoDB | 10 | Compact | 0 | 0 | 1638
4 | 0 | 0 | 0 | 1 | 2014-02-14 13:1
6:16 | NULL | NULL | utf8_general_ci | NULL |
| |
| table2 | MyISAM | 10 | Fixed | 0 | 0 |
0 | 26740122787512319 | 1024 | 0 | NULL | 2014-02-14 15:2
9:18 | 2014-02-14 15:29:18 | NULL | utf8_general_ci | NULL |
| |
| test7 | MEMORY | 10 | Fixed | 27 | 39 | 5940
0 | 16357770 | 0 | 0 | NULL | 2014-02-17 11:0
6:46 | NULL | NULL | utf8_general_ci | NULL |
| |
+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+
8 rows in set (0.00 sec)
Top
MySQL: ARCHIVE Storage Engine
The ARCHIVE storage engine is used to store large amounts of unindexed
data in a very small footprint. The storage engine is included in MySQL binary
distributions. To enable this storage engine (if you build MySQL from source),
invoke CMake with the -DWITH_ARCHIVE_STORAGE_ENGINE option.
When you create an ARCHIVE table, the server creates a table format file
(.frm extension) in the database directory.

Features of ARCHIVE storage engine :

Storage limits None Transactions No Locking granularity Table

MVCC No Geospatial data type support Yes Geospatial indexing support No

B-tree indexes No T-tree indexes No Hash indexes No

Full-text search indexes No Clustered indexes No Data caches No

Index caches No Compressed data Yes Encrypted data Yes

Cluster database support No Replication support Yes Foreign key support No

Backup / point-in-time recovery Yes Query cache support Yes Update statistics for data dictionary Yes

ARCHIVE storage engine supports


 INSERT and SELECT.

 ORDER BY operations

 BLOB columns

 AUTO_INCREMENT column attribute. The AUTO_INCREMENT column can have either a


unique or nonunique index.

 AUTO_INCREMENT table option in CREATE TABLE statements

ARCHIVE storage engine does not support


 DELETE, REPLACE, or UPDATE
 Inserting a value into an AUTO_INCREMENT column less than the current maximum column
value.

ARCHIVE storage engine : Storage & Retrieval


 The ARCHIVE engine uses zlib lossless data compression (see http://www.zlib.net/).

 Rows are compressed as they are inserted.

 On retrieval, rows are uncompressed on demand; there is no row cache.

MySQL: EXAMPLE Storage Engine


The EXAMPLE storage engine is a stub engine that does nothing and serve
as an example in the MySQL source code that clarify how to begin writing new
storage engines. To examine the source for the EXAMPLE engine, look in the
storage/example directory of a MySQL source distribution. When you create
an EXAMPLE table :

 The server creates a table format file (.frm extension) in the database directory.

 No other files are created

 No data can be stored into the table.

 Retrievals return an empty result.

 Does not support indexing.

To enable the EXAMPLE storage engine if you build MySQL from source,
invoke CMake with the -DWITH_EXAMPLE_STORAGE_ENGINE option.

MySQL: BLACKHOLE Storage Engine


The BLACKHOLE storage engine acts as a "black hole" that accepts data but
returns an empty result. To enable the BLACKHOLE storage engine (in case
of MySQL build from source), invoke CMake with the -
DWITH_BLACKHOLE_STORAGE_ENGINE option. When you create
a BLACKHOLE table, the server creates a table format file (.frm) in the
database directory. The BLACKHOLE storage engine supports all kinds of
indexes. Here is an example :
mysql> CREATE TABLE test10 (slno INT, message CHAR(40)) ENGINE = BLACKHOLE;
Query OK, 0 rows affected (0.16 sec)

mysql> INSERT INTO test10 VALUES(1, 'message1'), (2, 'message2');

Query OK, 2 rows affected (0.04 sec)

Records: 2 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM test10;

Empty set (0.03 sec)

The following SHOW TABLE STATUS statement shows the properties of the
tables (belongs to 'tutorial' database).
mysql> SHOW TABLE STATUS FROM tutorial;

+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+

| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_lengt


h | Max_data_length | Index_length | Data_free | Auto_increment | Create_time
| Update_time | Check_time | Collation | Checksum | Create_optio
ns | Comment |

+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+

| allclass | MRG_MYISAM | 10 | Fixed | 6 | 140 | 84


0 | 0 | 0 | 0 | NULL | NULL
| NULL | NULL | utf8_general_ci | NULL |
| |

| color | CSV | 10 | Fixed | 2 | 0 |


0 | 0 | 0 | 0 | NULL | NULL
| NULL | NULL | utf8_general_ci | NULL |
| |

| tabl1 | MyISAM | 10 | Fixed | 2 | 140 | 28


0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
3:52 | 2014-02-17 14:42:21 | NULL | utf8_general_ci | NULL |
| |

| tabl2 | MyISAM | 10 | Fixed | 2 | 140 | 28


0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
4:01 | 2014-02-17 14:43:09 | NULL | utf8_general_ci | NULL |
| |

| tabl3 | MyISAM | 10 | Fixed | 2 | 140 | 28


0 | 39406496739491839 | 2048 | 0 | 3 | 2014-02-17 14:3
4:22 | 2014-02-17 14:43:59 | NULL | utf8_general_ci | NULL |
| |

| table1 | InnoDB | 10 | Compact | 0 | 0 | 1638


4 | 0 | 0 | 0 | 1 | 2014-02-14 13:1
6:16 | NULL | NULL | utf8_general_ci | NULL |
| |

| table2 | MyISAM | 10 | Fixed | 0 | 0 |


0 | 26740122787512319 | 1024 | 0 | NULL | 2014-02-14 15:2
9:18 | 2014-02-14 15:29:18 | NULL | utf8_general_ci | NULL |
| |

| test10 | BLACKHOLE | 10 | Fixed | 0 | 0 |


0 | 0 | 0 | 0 | NULL | NULL
| NULL | NULL | utf8_general_ci | NULL |
| |
| test7 | MEMORY | 10 | Fixed | 0 | 39 |
0 | 16357770 | 0 | 0 | NULL | 2014-02-19 11:4
2:17 | NULL | NULL | utf8_general_ci | NULL |
| |
+----------+------------+---------+------------+------+----------------+-----------
--+-------------------+--------------+-----------+----------------+----------------
-----+---------------------+------------+-----------------+----------+-------------
---+---------+
9 rows in set (1.05 sec)

MySQL: FEDERATED Storage Engine


The FEDERATED storage engine is used to access data from a remote
MySQL database without using replication or cluster technology. Querying a
local FEDERATED table automatically pulls the data from the remote
(federated) tables. No data is stored on the local tables. To include the
FEDERATED storage engine (in case of MySQL build from source), invoke
CMake with the -DWITH_FEDERATED_STORAGE_ ENGINE option.
To enable FEDERATED (not enabled by default in the running server), you
must start the MySQL server binary using the --federated option. To check the
source for the FEDERATED engine, look in the storage/ federated directory of
a MySQL source distribution.
Create a FEDERATED table
You can create a FEDERATED table in the following ways :

 Using CONNECTION

 Using CREATE SERVER

Using CONNECTION : To use this method, you must specify the


CONNECTION string after the engine type in a CREATE TABLE statement.
See the following example :
CREATE TABLE federated_table (

roll_no INT(3) NOT NULL AUTO_INCREMENT,

stu_name VARCHAR(42) NOT NULL DEFAULT '',

total_marks INT(5) NOT NULL DEFAULT '0',

PRIMARY KEY (roll_no),

INDEX stu_name (stu_name),

INDEX total_marks (total_marks)

ENGINE=FEDERATED

DEFAULT CHARSET=latin1

CONNECTION='mysql://feduser@remote_host:9306/federated/test10_table';

The format of the connection string is as follows :


scheme://user_name[:password]@host_name[:port_num]/db_name/tbl_name

Where :

 scheme : A recognized connection protocol. Only mysql is supported as the scheme value at
this point.

 The user name for the connection, must have been created on the remote server, and have
suitable privileges to perform the required actions like SELECT, INSERT, UPDATE, and so
forth on the remote table.
 The password for user_name. (Optional)

 host_name: The host name or IP address of the remote server.

 port_num: The port number (default : 3306) for the remote server. (Optional)

 db_name: The name of the database holding the remote table.

 tbl_name: The name of the remote table.

Using CREATE SERVER : To use this method, you must specify the
CONNECTION string after the engine type in a CREATE TABLE statement.
See the following example :
CREATE SERVER

server_name

FOREIGN DATA WRAPPER wrapper_name

OPTIONS (option [, option] ...)

The server_name is used in the connection string when creating a new


FEDERATED table.

Differences between InnoDB and MyISAM

Feature InnoDB MyISAM

Storage limits 64TB 256TB

Transactions Yes No

Locking granularity Row Table

MVCC Yes No

Geospatial data type support Yes Yes

Geospatial indexing support No Yes

B-tree indexes Yes Yes

T-tree indexes No No

Hash indexes No No
Feature InnoDB MyISAM

Full-text search indexes Yes Yes

Clustered indexes Yes No

Data caches Yes No

Index caches Yes Yes

Compressed data Yes Yes

Encrypted data Yes Yes

Cluster database support No No

Replication support Yes Yes

Foreign key support Yes No

Backup / point-in-time recovery Yes Yes

Query cache support Yes Yes

Update statistics for data dictionary Yes Yes

Feature InnoDB MyISAM

Storage limits 64TB 256TB

Transactions Yes No

Locking granularity Row Table

MVCC Yes No

Geospatial data type support Yes Yes

Geospatial indexing support No Yes

B-tree indexes Yes Yes

T-tree indexes No No

Hash indexes No No

Full-text search indexes Yes Yes


Feature InnoDB MyISAM

Clustered indexes Yes No

Data caches Yes No

Index caches Yes Yes

Compressed data Yes Yes

Encrypted data Yes Yes

Cluster database support No No

Replication support Yes Yes

Foreign key support Yes No

Backup / point-in-time recovery Yes Yes

Query cache support Yes Yes

Update statistics for data dictionary Yes Yes


MYSQL ADMINISTRATION

Start and test MySQL Instance


$ /etc/init.d/mysqld start
$ mysql -u root -e "SELECT VERSION()"
Stop MySQL Instance
$ /etc/init.d/mysqld stop

MySQL Installation Layout for Linux RPM Packages:

Directory Contents of Directory

/usr/bin Client programs and scripts


/usr/sbin The mysqld server

/var/lib/mysql Log files, databases


/usr/share/info Manual in Info format
/usr/share/man Unix manual pages
/usr/include/mysql Include (header) files
/usr/lib/mysql Libraries
/usr/share/mysql Miscellaneous support files, including error
messages, character set files, sample
configuration files, SQL for database installation
/usr/share/sql-bench Benchmarks

TYPES OF LOGS IN MYSQL


• Error log : It records the problems encountered in starting, running and
stopping of mysql.
log-error=/var/log/mysqld.log
• General query log : Records established connections and statements
received from clients.
log=/var/log/mysql.general.log
• Binary logs : records statements that change data
log-bin=/var/log/mysql-log
• Slow query logs : records queries that take more than a minute to execute.
log-slow-queries=/var/log/mysqld-slow.log
DATABASE ADMINISTRATION

1. Connecting to mysql server:


/usr/bin/mysqladmin -u root password 'mysql123'
$mysql –u root –p {it will ask for password}
(or)
$mysql –u root –ppassword {here we are directly giving password}
(or)
$mysql –u root –p <database name> {here we connecting directly to
database
in mysql server}

2. Command to create a new database:


Mysql>create database <database name>

3. Command to see which STORAGE ENGINE mysql is using


Mysql>show engines;

4. To see the history of commands we executed at MYSQL prompt:


# Open the file .mysql_history in the root home location.

5. Query for seeing all the databases in mysql server:


Mysql>show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
+--------------------+
3 rows in set (0.00 sec)
Information_schema and mysql are the default databases created when mysql is
installed.

6. To see the current user:


Mysql>select user();

7. To see on which database user is working on:


Mysql>select database();
If it showing null then select any database for usage;
Mysql>use <database>;

8. To drop a database :
Mysql>Drop database <database name>

9. Using multiple queries in an single query:


Mysql>select database();select user();

10. Syntax for creating table:


Mysql>Create table testtab (eno int,ename varchar(20),
address varchar(20)) engine=MYISAM;

11. To see the syntax for a table :


Mysql>Show create table <tablename>;

12. To see the parameters available in mysql:


Mysql>show variables; show variables like ‘data%’;

13. To change the parameters {global|session} when database is running.


Mysql>Set GLOBAL storage_engine=innodb;
{changing the parameter permanently}
Mysql>set SESSION storage_engine=innodb;
{changing the parameter temporarly}
(or)
We can change the parameter directly in configuration file but we need to bounce
back the server.

14. For changing in configuration file


$ mysql --help | grep Default -A 1
It will display in what order mysql will read configuration files.
$ Vi /etc/my.cnf
log=/var/log/mysql.general.log
default-storage-engine = innodb
After writing changes to the file restart the mysql demon.

15. To see the tyes of engines supported by mysql server;


Mysql>show engines;
When we create a table in a database it will be created with a default storage
engine what mysql is using.

16. To see the location where the physical files are stored.
Mysql>show variables like ‘%data%’;
USER MANAGEMENT

1. Creating user in mysql accessible only for localhost:


Mysql>Create user <username>@localhost identified by password;

2. Grant privileges on all databases and its tables to user:


Mysql>grant all privileges on *.* to <username>;

3. Creating user in mysql accessible for all hosts:


Mysql>Create user <username>@% identified by password;

4. Grant privileges on all particular databases and its tables to user:


Mysql>grant all privileges on <database name>.* to <username>;

5. Creating a super user in mysql w/o password:


Mysql>create user administrator@localhost;
Mysql> grant all privileges on *.* to administrator

6. To see all the privileges a user is having:


Mysql>show grants for <username>@localhost;

7. To change password of a existing user:


Mysql>set password for <username>@localhost=password(‘new
password’);
8. To create user with INSERT command
shell> mysql --user=root mysql mysql> INSERT INTO user ->
VALUES('localhost','monty',PASSWORD('some_pass'), ->
'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');

mysql> INSERT INTO user SET Host='localhost',User='admin', ->


Reload_priv='Y', Process_priv='Y';

mysql> INSERT INTO user (Host,User,Password) ->


VALUES('localhost','dummy','');
mysql> FLUSH PRIVILEGES;
When you create accounts with INSERT, it is necessary to use FLUSH
PRIVILEGES to tell the server to reload the grant tables. Otherwise, the
changes go unnoticed until you restart the server. With CREATE USER,
FLUSH PRIVILEGES is unnecessary.
The reason for using the PASSWORD() function with INSERT is to encrypt
the password. The CREATE USER statement encrypts the password for you,
so PASSWORD() is unnecessary.

9. To see users who logged on to MYSQL SERVER:


$ Mysqladmin –p processlist
(or)
Mysql>show processlist;

10. To see status of MYSQL SERVER:


$Mysqladmin –p status

11. Limiting access to the users:


Mysql>GRANT ALL ON customer.* TO @<username>localhost WITH
MAX_QUERIES_PER_HOUR 20
MAX_UPDATES_PER_HOUR 10
MAX_CONNECTIONS_PER_HOUR 5
MAX_USER_CONNECTIONS 2;
SHOW COMMANDS IN MYSQL

SHOW BINARY LOGS


SHOW BINLOG EVENTS
SHOW CHARACTER SET
SHOW COLLATION
SHOW COLUMNS
SHOW CREATE DATABASE
SHOW CREATE FUNCTION
SHOW CREATE PROCEDURE
SHOW CREATE TABLE
SHOW CREATE VIEW
SHOW DATABASES
SHOW ENGINE
SHOW ENGINES
SHOW ERRORS
SHOW FUNCTION CODE
SHOW FUNCTION STATUS
SHOW GRANTS
SHOW INDEX
SHOW INNODB STATUS
SHOW LOGS
SHOW MASTER STATUS
SHOW MUTEX STATUS
SHOW OPEN TABLES
SHOW PRIVILEGES
SHOW PROCEDURE CODE
SHOW PROCEDURE STATUS
SHOW PROCESSLIST
SHOW PROFILE
SHOW PROFILES
SHOW SLAVE HOSTS
SHOW SLAVE STATUS
SHOW STATUS
SHOW TABLE STATUS
SHOW TABLES
SHOW TRIGGERS
SHOW VARIABLES
SHOW WARNINGS
BACKUP AND RECOVERY

Physical backup: cold backup:-


First stop the mysql server by issuing the following command
Shell> service mysqld stop
Go to data directory location and copy all the tablespaces and log files and format
files for INNODB storage engine and .MRD, .MYI and .frm files for MYISAM storage
engines to a directory in other location.

For innodb tables:


$cd /var/lib/mysql
$mkdir –p COLD/INNODB
$cp ibdata1 ib_logfile0 ib_logfile1 /var/lib/mysql/COLD/INNODB
And copy .frm files for tables created with INNODB storage engine.
$cd <database name>
$cp * /var/lib/mysql/COLD/INNODB

For myisam tables:


$mkdir –p /var/lib/mysql/COLD/MYISAM
$cd <database name>
$cp * /var/lib/mysql/COLD/MYISAM (copy .frm , .MYI, .MYD files)
Remove the files of a particular table in a database from datadir
directory and restore the files to their back to datadir location.

LOGICAL BACKUPS:
We use MYSQL DUMP and MYSQL IMPORT utilities for taking logical
backups.in logical backups we can take backup of all databases , a single database
and even a single table backup . MYSQL DUMP is similar to EXPORT in oracle and
MYSQL IMPORT is similar to IMPORT in oracle.
$MYSQLDUMP –u root –p –all-databases > alldb.sql {full database backup}
$MYSQLDUMP –u root –p <database name> outfile.sql { single database
backup}
$MYSQLDUMP –u root –p <database name> <table name> > outfile.sql
{backing up a single table}

If we want a backup of table into a text file then use the following:
Connect to any database
Mysql>select * from <table name> into outfile ‘outfile.txt’;
When taking the backup into TEXT file from sql prompt the particular file will
be stored in DATADIR location. When taking backup into .SQL file the file is stored in
OS location from where we issue the MYSQLDUMP command.

RESTORING TABLES FROM THE BACKUP:


Using text file we can directly load data into empty tables.(just like using SQL
LOADER In oracle.) syntax is as follows:
Mysql>Load data local infile '/PATH/outfile.txt’ into table <table name>;
To load data from a .sql file
$ mysql –p database name < outfile.sql {If we want to restore a dropped or lost
database}

USING MYSQL HOTCOPY:


MYSQLHOTCOPY is utility in mysql, using which we can take a backup when
the database is ONLINE.
$ /usr/bin/mysqlhotcopy -u <usr name> –p <password> <db name> <backup
location path> --allowold –keepold.

To restore a single table from full backup in Mysql:

1. sed -n -e '/CREATE TABLE.*bcd/,/UNLOCK TABLES/p' all_databases.sql >


table1.sql
2. Change character set to utf8 and then restore
/*!40101 SET character_set_client = 'utf8' */;
Restore the table back into some student database
3. mysql -u root -p student < table1.sql
CORRUPTION IN MYISAM TABLES

For checking MYISAM table we use MYSQLCHECK.


$Mysqlcheck <dbname> <table name> -p
$Mysqlcheck –databases <db1> <db2> -p
$Mysqlcheck –all-databases –p {it will check all tables created on MYISAM &
INNODB engines in all databases}

FOR REPAIRING A CORRUPTED TABLE FOLLOW THE STEPS:


Take a backup of table (using mysqldump).Drop the particular table .Recreate the
table.

$MYSQLDUMP –u root –p <database name> <table name> > outfile.sql


Mysql>Use database <database name>;
Mysql>drop table <table name>;
$Mysqlimport –p <database name> < outfile.sql
REPLICATION IN MYSQL

Replication is the most trusted and tested way of making your data redundant. using
replication you can overcome the problem of SPOF (single point of failure). A slave
can be used in multiple way

1. slave server can be used for taking backups

2. slave server can be used as a DR

3. slave server can be used to serve read only queries

Master - Slave Replication


Following are the steps to be followed for creating a simple master - slave based
replication

1. enable binary logging : put the parameter log-bin in the my.cnf and restart the
instance

2. assign a server id to the mysql instance : put server_id = <some_number> in


my.cnf

3. create a replication user : "grant replication slave on *.* to <user>@'host' identified


by 'password'"

4. take a full backup from master : mysqldump -u<user_id> -p<password> --master-


data=2 <database_name> > filename.sql

5. copy the backup to other server

6. restore the backup : mysql -u<user_id> -p<password> <dbname> < filename.sql

7. execute the command change master to as : "change master to master_host =


'192.168.6.140',master_port=3306,
master_user='repl',master_password='repl',MASTER_LOG_FILE='vm1-bin.000001',
MASTER_LOG_POS=407;"

8. start the slave : start slave

9. check the replication status by : 'show slave status \G'

if the replication is successfully started you will see the following output
*************************** 1. row ***************************

Slave_IO_State: Waiting for master to send event


Master_Host: 192.168.6.140
Master_User: repl
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: vm1-bin.000001
Read_Master_Log_Pos: 1040
Relay_Log_File: localhost-relay-bin.000002
Relay_Log_Pos: 914
Relay_Master_Log_File: vm1-bin.000001
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 1040
Relay_Log_Space: 1091
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
Last_IO_Errno: 0
Last_IO_Error:
Last_SQL_Errno: 0
Last_SQL_Error:
Replicate_Ignore_Server_Ids:
Master_Server_Id: 1
Master_UUID: 56703c76-891d-11e5-8ba0-000c2907ea66
Master_Info_File: /software/mysql56/data/master.info
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O
thread to update it
Master_Retry_Count: 86400
Master_Bind:
Last_IO_Error_Timestamp:
Last_SQL_Error_Timestamp:
Master_SSL_Crl:
Master_SSL_Crlpath:
Retrieved_Gtid_Set:
Executed_Gtid_Set:
Auto_Position: 0
Now we know how to setup the basic replication.

1. master logs the changes into the binary log

2. slave reads the binary logs and puts the changes into relay log with IO thread

3. slave executes the contents of relay logs with SQL thread.

SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;

IO Thread : responsible for making coinnection with the master and reading binary
logs and writing into the relay log. it fails when there is a problem connecting to the
master either because of network issues like physical network break or the firewall or
if the master server is down because of any reason.

SQL thread : sql thread executes the contents of relay log. if there is problem at the
data level at the slave thew sql thread will fail to update or carry on the replication.
1. object does not exist : database / table

2. key not found : if the primary is there in the table and if somone has by mistake or
intentionally removed the row from the slave and the statment on the same key
comes from the master. if slave already has a primary key which is not there at the
master yet and later the same key value comes from the master.

Types of Replication in Mysql:

1. master - slave

2. master

slave slave

3. master - slave - slave


4. master - master

Edit the /etc/mysql/my.cnf file on each of the Linodes. Add or modify the following
values:
Server 1:
/etc/mysql/my.cnf

1server_id =1
2log_bin = /var/log/mysql/mysql-bin.log
3log_bin_index = /var/log/mysql/mysql-bin.log.index
4relay_log = /var/log/mysql/mysql-relay-bin
5relay_log_index = /var/log/mysql/mysql-relay-bin.index
6expire_logs_days = 10
7max_binlog_size = 100M
8log_slave_updates = 1
9auto-increment-increment = 2
10auto-increment-offset = 1
Server 2:
/etc/mysql/my.cnf

1server_id =2
2log_bin = /var/log/mysql/mysql-bin.log
3log_bin_index = /var/log/mysql/mysql-bin.log.index
4relay_log = /var/log/mysql/mysql-relay-bin
5relay_log_index = /var/log/mysql/mysql-relay-bin.index
6expire_logs_days = 10
7max_binlog_size = 100M
8log_slave_updates = 1
9auto-increment-increment = 2
10auto-increment-offset = 2

You might also like