Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Tuesday, 20 September 2016

MySQL: Architecture..!

Ah..! That's a very basic topic and I'm writing about it now..!! That's because it never lasts in my memory for long time. It always rolls back from my mind , might be because I never felt it's importance - apart from that of interviews !
However, after a brief Googling, here is an overview of MySQL's architecture in my words.

Unlike MS SQL Server or other RDBMS, MySQL doesn't have a standard architecture diagram that we can refer to. Or may be, couldn't find out from the official site of MySQL. 

Anyhow, I was able to get one of the know logical architecture diagram which describes MySQL well and easy to understand is :




That's a 3 layer logical architecture. 

The topmost layer facing the incoming connections/clients includes authentication, security related things.

The second layer is the most important one, which includes Parser, Query Cache and Optimizer.
Parser creates a Parse tree for every query that's been executed by the client. It uses Lex and Yacc compilers (What are they ? That's another big story..,may be in the next to next post..!?!) 
Then the Optimizer tries to optimize this Parse tree by applying different execution plans or by re-writing the query itself. 

This Optimized Parse Tree will be passed on to the third layer which comprise of the Storage engines. Storage engines just gives back the result and don't do any optimization to the query.

Meanwhile, the result sent back will be stored in the query cache to serve the repeating queries.

That's the briefest MySQL architecture, as I understood! Hope that gives an idea of how MySQL works.





Wednesday, 7 September 2016

MySQL: High-Availability - Replication


MySQL being one of the best open-source light weight database, comes with the in-built data replication feature. In fact, this feature made MySQL more and more popular in the data world.

Replication in MySQL do mean – The data flow from one server to the other remote server through network, due to which, both of them will be identical to each other. It’s basically having an exact copy of data at a remote place, while, the data being updated dynamically with respect to the source.
The MySQL Replication includes below terminologies:
  •         Master – The source server from where the data is being replicated. Applications usually pointed to this server for write operations.

  •        Slave – This is the destination for replication. Slave is the actual remote mirror copy of Master server.

o   I/O Thread – This is one of the basic component of replication. This thread is responsible for reading the Master’s Binary log content and write it into the Slave’s Relay log.
The performance of this thread is the key factor of Replication speed and it solely depends on the Network Bandwidth.
o   SQL Thread – This is the other important replication component, which is responsible for reading Slave’s Relay logs and execute  them into the Slave Databases. This is always slower, compared to I/O thread and this decides the Delay in Replication/Replication Lag.


  •        Binary Logs – These binary files logs every committed changes on Master. Every modification on the Master server is being written to these files, which are used by slaves for replication. And, also they are used for recovery purposes.

  •         Relay Logs – These are the  Slave’s version of Binary Logs. They are generated only for Slave servers.



Below is the pictorial representation of MySQL Replication with Master-Slave Hierarchy :

Please note that there can be Multiple Slaves connected to Single Master. However, that doesn’t affect Master’s performance.



There are 3 types of replication MySQL supports:
·        Asynchronous Replication

This is MySQL Default. Any flavor of MySQL should support this type of replication. Asynchronous Replication is contrast to Synchronous Replication.
Here, Master sends the committed transactions to it’s Binary Logs and DO NOT wait for the Slave to read this data.
So, while using this type, we can’t be 100% sure that all the data from Master is replicated to Slave!


  •         Semi-synchronous Replication

MySQL 5.5 or above supports this type of Replication. In this type, the Master sends the committed transactions to the Binary Logs and waits for the acknowledgement from at least one of the Slaves that the replicated data is received.
If no Slaves returns an acknowledgement, the Master switch back to Asynchronous mode after timeout, until at least one of the Slaves synchronized.
Using this type of replication ensures the replication is up-to-date, but, it slows the performance.


  •         Synchronous Replication


This type of replication is not available with the normal version of MySQL. This is a part of MySQL Cluster.
In this type , the Master waits until all the Slaves receive and commit the data.  This is much more costlier w.r.t. performance.

Please note that, MySQL Replication is not complete High Availability solution. Because, if the Master goes down, the Slave should be made as new Master , Manually. 
This leads opts for downtime until the manual process completes!

Friday, 8 January 2016

MySQL: Innodb Log Buffer and REDO Logs


Actually, the definition of sys variable innodb_log_buffer_size was confusing me very much. 
What actually this buffer is meant for? 
Is it a part of Innodb buffer pool?

And after extensive googling(!) I got a clear picture of it. 
Here's what I got:

 No doubt, REDO logs are the unsung heroes. But, how exactly it's generated? 

When any DML request comes in, the storage engine reads out the corresponding page from the disk into the memory(innodb buffer pool). 
So, there are now 2 copies of this page: one is in  disk and the other in memory. The page in the memory, which is not yet flushed to disk is called Dirty Page.

For this dirty page, an redo log will be generated locally, in the mini transaction buffer. Which is very internal thing and not of our concern to worry! 
This log is then transferred to the global redo log buffer. And, this redo log buffer size is decided by the variable innodb_log_buffer_size ! This is a separate memory taken from the host.

So, the redo logs in this buffer is written or flushed to redo log files on disk(iblog files) as soon as the buffer is full or a commit happens. 

If we're performing long transactions, it's recommended to increase the size of this buffer to avoid the unnecessary I/Os.

The redo logs will be flushed to the disk before the corresponding dirty pages are flushed.

For a clear insight on how InnoDB works, go through the below link:
https://blogs.oracle.com/mysqlinnodb/entry/redo_logging_in_innodb

Wednesday, 6 January 2016

MySQL: REDO Logs and UNDO Logs


Most of the DBAs like me, haven't cared about the them..! But, they are the Unsung heroes of MySQL..!!

Yes, UNDO and REDO logs are the 2 different kind of logs; each with it's own purpose and you shouldn't get confused between them ..!!

As the name indicates, REDO logs are for Re-doing things..! 
They hold the transactions which were already executed, but not committed to the disks..! So, the REDO log records every transaction, holds until it gets committed and if needed, it will be used for crash recovery.

By default, there will be 2 REDO logs, named, ib_logfile0 and iblogfile1. 
As of version 5.6 or later, we can have up to 100 REDO logs using the System Variable  innodb_log_files_in_group . 
Since, these logs are overwritten as soon as all the files are full, it is advised to have more files or files with larger size. By default, each log file will be 5 MB and the size can be set using the system variable  innodb_log_file_size. 

The maximum allowed combined size of all the files is 512 GB(innodb_log_file_size * innodb_log_files_in_group <= 512 GB).

The REDO log files location can be set using the variable innodb_log_group_home_dir , if not specified, default directory will be used.


Let's talk about UNDO logs..:

This log stores copy of data that is being modified by any current transaction. So that, at the same time if any other transaction queries for the original data, this log will serve the purpose..!! 
These logs are also called Rollback Segments.

In the earlier versions, these logs were invisible as, UNDO logs were the part of System table space, i.e., ibdata1 and ibdata2. But, as of 5.6 and later, you can create multiple and separate UNDO log files(table space files).

Use variable innodb_undo_tablespaces  to set the number of table space files. Max value is 126 and minimum 0. 
The Undo logs set by the variable innodb_undo_logs will be divided between the set table spaces. Maximum you can create 128 undo logs and it is the default value.

The path of the UNDO log table space can be set by the variable innodb_undo_directory.






Wednesday, 4 March 2015

MySQL: Enabling GTIDs

With MySQL 5.6, Oracle has introduced  a new concept of GTIDs. 

So, what's GTID? And, how's it useful for me??

GTID stands for Global Transaction ID. That means, each committed transaction will be logged in with an Unique Identification ID, called, GTID.

GTID = source_id : transaction_id

Where in,
source_id --> Originating server's UUID
transaction_id --> Sequence number in which the transactions are being committed.


The main advantage of GTID is, you don't have to track Master's binlog file and position to resume/setup the replication process. The sync will happen automatically, if both master and slaves are GTID enabled.

And, there's no disadvantage in enabling the GTID, except, you can't follow the traditional way to skip certain transactions and restore ad-hoc data from master. You need to follow different methodology.

Anyhow, here's how to enable GTID:

* Make both Master and Slave as Read-only:

SET @@global.read_only=ON

* Restart/Start both Master and Slave with the below options:
--gtid-mode=ON
--log-bin
--log-slave-updates
--enforce-gtid-consistency 
--skip-slave-start   [Of course, Only for Slave]

Now, to start the replication, execute the below on slave:

CHANGE MASTER TO
MASTER_HOST=*****,
MASTER_PASSWORD=****,
MASTER_PORT=****,
MASTER_AUTO_POSITION=1;

Note that, Binlog info is not required.
Slave reads all the transactions, based on the GTID and skips if it's already been processed.


Monday, 24 November 2014

MySQL: Configuration File

When you install MySQL through RPM, before starting the the MySQL process, make sure /etc/my.cnf do exist. And, if it's not, do create one with the basic configuration values.

Below is a sample my.cnf file for a server with InnoDB as the default engine:


[mysqld]
performance_schema
skip-name-resolve
server-id                       = 1
innodb_file_per_table
max_connections                 = 1000
max_allowed_packet             = 512M

slow-query-log                  = 1
slow_query_log_file             = /var/lib/mysql/myServer_slow.log

sort_buffer_size                = 32M
read_buffer_size                = 32M
read_rnd_buffer_size            = 16M
join_buffer_size                = 32M

# innodb parameters
tmpdir                          = /var/lib/mysql
datadir                         = /var/lib/mysql
innodb_data_home_dir            = /var/lib/mysql
innodb_data_file_path           = ibdata1:10M:autoextend
innodb_log_group_home_dir       = /var/lib/mysql
innodb_log_files_in_group       = 2
innodb_buffer_pool_size         = 40G
innodb_additional_mem_pool_size = 64M
innodb_log_buffer_size          = 32M
innodb_log_file_size            = 2047M
innodb_change_buffering         = inserts
innodb_flush_method             = O_DIRECT


# parameters added for thread cache size, wait time out, interactive timeout and table open cache
wait_timeout                    = 28800
interactive_timeout            = 28800
table_open_cache               = 2000
thread_cache_size              = 1000

[mysql]
max_allowed_packet              = 512M



The explanations of these variables..I think I'll do in next posts..

Friday, 7 November 2014

MySQL: User Management

User Management in MySQL is one of the fundamental admin task and is quite easy, as well.

So, here are the basic commands regarding this:


** To list all the MySQL users: Users will be stored in the system table mysql.user. So, you need query this to fetch the users:


mysql> select user,host,password from mysql.user;

Output:

+-----------------+--------------+-------------------------------------------+
| user            | host         | password                                  |
+-----------------+--------------+-------------------------------------------+
| root            | localhost    | *0EF40B7834E1725C32C7EC640FC474ED72254B69 |
| dump            | 127.0.0.1    | *E1A36C05EDBEB86BF19531672613ECFC88F3DB2F |
| root            | 127.0.0.1    | *0EF40B7834E1725C32C7EC640FC474ED72254B69 |

| readonly        | %            | *9E1258A6F6806487E2BFA236472D4D28236F6215 |
+-----------------+--------------+-------------------------------------------+

4 rows in set (0.009 sec)


Note that, Password is encrypted here. This you've to take care while setting up password for any user by using PASSWORD(), a system function.


** To create new user and grant privilege: There are 3 ways to create an user:

1. Using CREATE command:

CREATE USER username@'host' IDENTIFIED BY 'password';
GRANT SELECT ON db.table TO 'username'@'host';
FLUSH PRIVILEGES;


2. Using GRANT command:

GRANT SELECT ON db.table TO 'username'@'host' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

The above command will create the user, if it is not present.


3. Inserting into mysql.user table:

INSERT INTO mysql.user(user,host,password) values ('usrename','host','encrypted_password');

GRANT SELECT ON db.table TO 'username'@'host' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

However, this is not a RECOMMENDED way. Make sure, this password is encrypted using below query:

SELECT PASSWORD('password');



**Removing User/Access:


To Revoke access:

REVOKE SELECT ON db.table FROM 'username'@'host';
FLUSH PRIVILEGES;


To Remove user:

DROP USER 'username'@'host';
FLUSH PRIVILEGES;

or

DELETE FROM mysql.user WHERE USER='username' and host='host';
FLUSH PRIVILEGES;


FLUSH PRIVILEGES -- This command is to Reload the privileges of all the user(reloads from mysql.user table)

Sunday, 5 October 2014

MySQL : Replication Error 1062

It's been a pretty long time without posts. So, there's a lot to blog it!

One of the common error in MySQL Replication is 'Duplicate Entry' - Error 1062. This pop-ups only if there are any manual intervention.
The SQL Thread stops with this error. Just check the record in the error on both master and slave. If you understand the exact cause, you may delete the record in slave and start replication. Or else, just skip ignore the insert statement using the below command:


mysql> STOP SLAVE;
mysql> SET GLOBAL SQL_SLAVE_SKIP_COUNTER = 1; 
mysql> START SLAVE; 

This will skip 1 statement and continues replication. If you're getting lot of such errors, again and again, just add the below entry in Slave's my.cnf and restart MySQL:

[mysqld]

slave_skip_errors    = 1062


This will keep on skipping duplicate entries whenever it occurs.

Please note that, you can use this for any other error, as well. 

Friday, 21 February 2014

MySQL: SELECT / LOAD in Batch

Here's are the MySQL commands to extract data from  table and to load data into tables.
Unlike other DBMS, MySQL offers SELECT..INTO.. and LOAD DATA.. commands are quite faster and convenient. Data would be fetched and loaded in bacthes.


Sample query to extract data from a table:

SELECT *
FROM tmp.my_table
INTO OUTFILE '/file_path/filename.csv'
FIELDS TERMINATED BY '|$|'
LINES TERMINATED BY '\n';

You can select particular columns, instead of  '*' .

OUTFILE should be given with file path and name. By default, file will be created inside data directory.
Important thing to be noted here is, the file will be generated inside the local host only.
Means, if you're executing above query on server S2, fetching data from S1, the file will be generated inside S1 itself.

Also, to execute above command, it requires FILE Privilege for MySQL user and the destination directory should also be having server level MySQL user privilege.

Below is the query that an be used to load data in batches:

LOAD DATA LOCAL 
INFILE '/file_path/filename.csv' 
INTO TABLE tmp.my_table 
CHARACTER SET utf8 
FIELDS TERMINATED '|$|' 
LINES TERMINATED BY '\n';

You can use, 'IGNORE INTO' instead of 'INTO', to ignore the duplicate records.
CHARACTER SET is mentioned explicitly as the data being loaded is having local languages(like kannada, hindi, telugu,..). Without this, data won't be visible - scrambled.

Wednesday, 12 February 2014

MySQL: RPM Installation

Before going through this post, I would recommend you to have glance on my previous post related to this - 'MySQL - Before Installation..

So, here is the steps to install MySQL through RPMs:

* First of all download Server and Client RPMs. 
You can download the latest GA release from MySQL site or version you want from Oracle e-delivery.

Below are the RPMs, I downloaded:

[root@localhost Desktop]# ls -lhrt
total 70M
-rwxrw-rw-. 1 theray theray 52M Feb 12 05:14 MySQL-server-5.6.16-1.el6.x86_64.rpm
-rwxrw-rw-. 1 theray theray 18M Feb 12 05:14 MySQL-client-5.6.16-1.el6.x86_64.rpm


* Make sure that there is not previously installed MySQL, using the below command :

[root@localhost Desktop]# rpm -qa | grep -i mysql
mysql-libs-5.1.47-4.el6.x86_64

If already there, us below command to remove it:

[root@localhost Desktop]# rpm -e rpm_package_name


* Install RPMs:

[root@localhost Desktop]# ls -lrht
total 70M
-rwxrw-rw-. 1 theray theray 52M Feb 12 05:14 MySQL-server-5.6.16-1.el6.x86_64.rpm
-rwxrw-rw-. 1 theray theray 18M Feb 12 05:14 MySQL-client-5.6.16-1.el6.x86_64.rpm


--Installing Client:

[root@localhost Desktop]# rpm -ivh MySQL-client-5.6.16-1.el6.x86_64.rpm
Preparing...                ########################################### [100%]
   1:MySQL-client           ########################################### [100%]


--Installing Server:

[root@localhost Desktop]# rpm -ivh --force MySQL-server-5.6.16-1.el6.x86_64.rpm
Preparing...                ########################################### [100%]
   1:MySQL-server           ########################################### [100%]
2014-02-12 05:39:06 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2014-02-12 05:39:06 32621 [Note] InnoDB: Using atomics to ref count buffer pool pages
2014-02-12 05:39:06 32621 [Note] InnoDB: The InnoDB memory heap is disabled
2014-02-12 05:39:06 32621 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
.
.
.


* Now, create /etc/my.cnf file(its the basic configuration file) with the necessary configurations in it:

[root@localhost Desktop]# cat /etc/my.cnf
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid




* Start MySQL process :

[root@localhost Desktop]# /etc/init.d/mysql start
Starting MySQL......................................................................................................
.......... SUCCESS!

* Once its started, use the below command to remove anonymous users and make the installations secure:


[root@localhost Desktop]# /usr/bin/mysql_secure_installation


Now the MySQL is ready for use!

MySQL: Slave Status - SECONDS_BEHIND_MASTER



We often execute the below command to check the replication status:

mysql> SHOW SLAVE STATUS \G

This will show all the details regarding replication. Out of which, the field SECONDS_BEHIND_MASTER is the one is the curious one.

It is the time in Seconds, which indicates actual amount of lag between Master and Slave.

In actual words, it's the calculation in seconds between the relay log's latest query event time stamp(which is already executed on master and queued on slave) and the current time stamp of the slave.

So, if the time set on Master's host and Slave's host are different, then, you'll see a scary value for this field.

Friday, 7 February 2014

MySQL: Clustered Index


Clustered Index is the InnoDB term for a primary key index. 

InnoDB table storage is organized based on the values of the primary key columns, to speed up queries and sorts involving the primary key columns. 

If you do not define a PRIMARY KEY for your table, MySQL locates the first UNIQUE index where all the key columns are NOT NULL and InnoDB uses it as the clustered index.

If the table has no PRIMARY KEY or suitable UNIQUE index, InnoDB internally generates a hidden clustered index on a synthetic column containing row ID values. 


The rows are ordered by the ID that InnoDB assigns to the rows in such a table. The row ID is a 6-byte field that increases monotonically as new rows are inserted.
Thus, the rows ordered by the row ID are physically in insertion order. 


All indexes other than the clustered index are known as secondary indexes.
In InnoDB, each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index. 


InnoDB uses this primary key value to search for the row in the clustered index.


Physical Strcuture:
All InnoDB indexes are B-trees where the index records are stored in the leaf pages of the tree. 
The default size of an index page is 16KB. 
When new records are inserted, InnoDB tries to leave 1/16 of the page free for future insertions and updates of the index records.

The page size can be specified for all InnoDB tablespaces in a MySQL instance by setting the innodb_page_size configuration option before creating the instance.
 

Once the page size for a MySQL instance is set, you cannot change it.
Supported sizes are 16KB, 8KB, and 4KB, corresponding to the option values 16k, 8k, and 4k.

A MySQL instance using a particular InnoDB page size cannot use data files or log files from an instance that uses a different page size.

MySQL: B-Tree Index

 When any CREATE TABLE is executed, InnoDB internally creates a clustered B-tree index  representing the table. 
If no primary key is explicitly given, internally a primary key is added. 

Each node of B-tree is represented by one page (which is by default is of size 16KB). 


Below is an useful set of info, copied from other blog
(guptavikas.wordpress.com/2012/12/17/b-tree-index-in-mysql/):


B-Tree is the default index for most storage engines in MySql. 

The general idea of a B-Tree is that all the values are stored in order, and each leaf page is the same distance from the root.

A B-Tree index speeds up data access because the storage engine doesn’t have to scan the whole table to find the desired data. 
Instead, it starts at the root node. The slots in the root node hold pointers to child nodes, and the storage engine follows these pointers.

It finds the right pointer by looking at the values in the node pages, which define the upper and lower bounds of the values in the child nodes. 

Eventually, the storage engine either determines that the desired value doesn’t exist or successfully reaches a leaf page. Leaf pages are special, because they have pointers to the indexed data instead of pointers to other pages.

u00320020206brl05_01

MySQL: InnoDB doublewrite buffer

That's an useful piece of information, so did a copy-paste from MySQL site:

InnoDB uses a novel file flush technique called doublewrite. 

Before writing pages to the data files, InnoDB first writes them to a contiguous area called the doublewrite buffer. Only after the write and the flush to the doublewrite buffer have completed, does InnoDB write the pages to their proper positions in the data file. 

If the operating system crashes in the middle of a page write, InnoDB can later find a good copy of the page from the doublewrite buffer during crash recovery.

Although data is always written twice, the doublewrite buffer does not require twice as much I/O overhead or twice as many I/O operations. Data is written to the buffer itself as a large sequential chunk, with a single fsync() call to the operating system.

To turn off the doublewrite buffer, specify the option innodb_doublewrite=0.



Wednesday, 29 January 2014

MySQL: SUBSTRING_INDEX - Select Patterns

Consider, a MySQL table having values in a column like below:

SELECT location  FROM geo LIMIT 3;

"location"
"India.Karnataka.Shimoga.Gopala"
"India.Karnataka.Bengaluru.BTM"
"India.Karnataka.Chikmaglore.Koppa"

My requirement is to take only 4th value from each of the rows(such as, Gopala,BTM,Koppa). 
I don't want to display remaining values. 
Its same as what 'cut' command will do in Linux.

For this, we can use SUBSTRING_INDEX function.

SELECT SUBSTRING_INDEX(location,'.',-1)  from geo LIMIT 3;
"location"
"Gopala"
"BTM"
"Koppa"

Syntax: SUBSTRING_INDEX(string,delimiter,count)
Here count means column number based on delimiter. 
Negative value indicates that the column numbers calculated from right side.

So, if I give '-2' instead of  '-1':

SELECT SUBSTRING_INDEX(location,'.',-2)  from geo LIMIT 3;
"location"
"Shimoga.Gopala"
"Bengaluru.BTM"
"Chikmaglore.Koppa"

MySQL: Master-Master Circular Replication

While MySQL is one of the simplest RDBMS, it gives vast opportunity to play around!

One of the common question asked in most of the interviews is about Master-Master Circular Replication(means, both servers are master and both are slaves), though its not so practical to be use in a environment where you need high performance.. !!


Here are the brief steps for setting up such a set up..! :

* Install MySQL on both the servers which are our masters

* Configure my.cnf with below options:

server-id = 2 
log_bin = /var/log/mysql/mysql-bin.log
log-slave-updates

[give your convenient values, but make sure server-id is unique]

Note: log-slave-updates-> Normally, a slave does not log to its own binary log any updates that are received from a master server. This option tells the 
slave to log the updates performed by its SQL thread to its own binary log.
This option is must in any chain replication, as well.


* Start MySQL on both the servers and make a note of 'SHOW MASTER STATUS' values.

* Using the above values of each, set the replication parameters on the other 
server. And start slave.

slave stop; 
CHANGE MASTER TO MASTER_HOST = '3.3.3.3', 
MASTER_USER = 'replicator', 
MASTER_PASSWORD = 'password',
MASTER_LOG_FILE = 'mysql-bin.000001',
MASTER_LOG_POS = 107; 
slave start;  

MySQL: Why Server ID ?


In any MySQL replication  set up, server ID will be a common variable seen in my.cnf. Ans usually it will be unique across the servers.

[mysqld]

server-id = 2

But why its so important?

For any normal Master-Slave setup, it doesn't matter whatever the number you set.
However, when you go for a Multi-master or circular replication, its a basic need.

Consider an  example, we have 3 servers A, B and C. Their server ids are accordingly 11, 22 and 33. 
They are replicating in circular manner (multi-master) like A is master of B server, B is master of C server and C is master of A server.

Now when any mysql client will execute insert/update/delete statement on A server, it will be logged in the binary of A server with server id 11.

As that statement logged in binary of A server, it will go to B server (because B is slave of A), executed there and logged in binlog of B server with the same server id 11.  (why same server id? because originally that statement initiated by A server with server id 11 and on B server its executed by sql thread not regular mysql client).

Now again this statement will go to C server (because C is slave of B), executed there and logged in the binlog of C server with the same server id 11.

As C is master for A server, when the statement will come to A server via binlog of C server, sql thread of A server will compare the server id and will find that its same 11 means this statement is originally initiated by the server itself and no need to execute so finally sql thread will skip that statement.

If sever ID wasn't unique, this setup would have entered into  an endless loop state..!

Saturday, 14 December 2013

MySQL - Before Installation..

So, while you have a basic idea about MySQL, I would recommend the real-time trial and error than just reading out.

For that, download a latest stable community version of MySQL from the official website.
Though MySQL is platform independent, its best suited for Linux/Unix environment. 
So, better have Linux on VM and install MySQL.
(All my posts mostly will be based on the same combination.)

There are many ways to install MySQL on your Linux, based on its flavor. You may go for RPM installation or Binary installation  by downloading files, manually. 

Apart from that, you can get MySQL inbuilt in some of the Linux versions, if not, you can get it easily by updating the library(apt-get, yum installations)


Ubuntu:

sudo apt-get install mysql-server 


Non-Ubuntu: 

sudo yum install mysql-server



However, I prefer RPM way of installation. Just download MySQL stable Community edition RPM from official website. 
Make sure, you download both MySQL server and MySQL client RPMs.

MySQL Server - It is the actual MySQL software, which can be installed on any host.

MySQL Client - It is the client to connect to any MySQL server. Means, without this you can't access any MySQL server. While, this can be installed on any of the server through which you can access any MySQL server.

Hope that's not confusing..


MySQL - An Intro

I know, it might appear to you outdated if I start  telling about MySQL now, which is one of the world's best open source database. 

However, being a DBA, after making my hands dirty with it, I feel I must share my knowledge with the freshers who want to learn MySQL. Because, once I was struggling to learn it on my own.

So, here it is..

MySQL .. ?

MySQL is one of the widely used RDBMS, open source software. As you may aware, its now been owned and supported by Oracle. 

The latest and stable GA release is 5.6.15(as of 03 Dec 2013).


Why MySQL ..?

MySQL is basically very simple, lightweight DBMS. Having hands-on on MSSQL Server, I can assure you MySQL feels better. 

Physical structure, configurations and all other settings in MySQL is much simpler and pretty handy.
And mainly, its very 'flexy' with huge data.

If you ever want to develop an application which requires data to be stored in it, I would recommend MySQL, which also comes bundled version.

Apart from these, MySQL is being developed and supported by the most famous giant Oracle Corporation.

Hah, they must be understanding now, its not easy to sell which comes free ..!! :)



to be continued..



Sunday, 8 December 2013

MySQL Replication: Exclude an SQL from replicating


If you're using MySQL Replication, in rare cases you may require to skip a particular SQL statement from replicating - which is to be executed on Master and should not be on the Slave. 
Though, its not a good practice!

However, here's how to do it. 
MySQL has a variable sql_log_bin, by default its value will be 'ON' or '1', when we enable replication. 
That means, it replicates all the SQL statements from Master to Slave.So, if we want to disable this for a particular SQL, do as below:



SET SESSION sql_log_bin=0; sql statement;SET SESSION sql_log_bin=1;Example:
SET SESSION sql_log_bin=0;

DELETE FROM tab1 WHERE col1='NULL';

SET SESSION sql_log_bin=1;



However, after MySQL 5.5.5 version, no need to use SESSION. By default its a SESSION variable and it won't affect other user's transactions. 

Note: Executing this on Master would cause data inconsistency. Don't try this unless you are sure about what you are doing!