sqladminon September 26, 2018

In a DBA’s day to day activities, we are doing Archive operation on our transnational database servers to improve your queries and control the Disk space. The archive is a most expensive operation since its involved a huge number of Read and Write will be performed. So its mandatory to run the archive queries in chunks. The archive is depended on business use. Many of us need a copy of the data on an archive database to refer later. To perform the archive we can just simply run the delete query with the limit. But we need to run the query again and again until the matched rows count is 0. We can create a procedure to do this in a while loop. I have created one such procedure to archive many tables.

Image Source: Brent Ozar Unlimited

Why Archive is an expensive operation?

Generally how we are arching the data is delete from table_name where column_name <= some_value; If you are running on a table which needs to be deleted around 15million records, then you need the undo log file to hold all of these records. There will be a heavy IO happening in the Disk. And lt’ll lock the rows and some other locks will be held until the Archive complete. Replication may delay because of this.

When Archive is going to mess up the production?

  • Running archive commands on a heavy traffic time.
  • Archive without a proper where clause.
  • Delete data without limit.
  • Performing archive contrition on a not indexed column.
  • Continuously run the delete query in chunks on a replication environment. {without sleep(1 or few seconds}.

How to perform the archive properly?

  • To do this, the first condition is use limit in the delete.
  • Create an index on the where clause.
  • At least do sleep 1sec for each chuck which will be good for a replication infra.
  • Set autocommit=1
  • Optional: Set transaction isolation to Read Committed.
  • Do not mention the number of loops without knowing the actual loop counts to process the complete delete.

My approach to this:

Inspired by Rick James’s Blog, I have prepared a single stored procedure to perform archive on multiple tables. We just need to pass the table name, date column and then date to archive. I have tested with datetime and Primary key column.

Archive a single table:

The below procedure will perform delete on table test and remove older than 10 days records.

use sqladmin;

DROP PROCEDURE
IF EXISTS archive;
delimiter //
CREATE PROCEDURE
archive()
begin
DECLARE rows INT;
DECLARE rows_deleted INT;
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET rows = 1;
SET rows_deleted = 10000;
WHILE rows > 0
do
SET autocommit=1;
DELETE
FROM test
WHERE dop < DATE(Date_sub(Now(), INTERVAL 10 day))
LIMIT 10000;
SET rows = row_count();
select sleep(1);
commit;
END WHILE;
END //
delimiter ;

Archive multiple tables:

This procedure will help you to archive multiple tables, you just need to pass the table name, column name and the date for the archive. I love to use this 

use sqladmin;

DROP PROCEDURE
IF EXISTS sqladmin_archive;
delimiter //
CREATE PROCEDURE
sqladmin_archive(IN archive_dbname varchar(100), IN archive_table varchar(100), IN archive_column varchar(100), IN archive_date varchar(100)) begin
DECLARE rows INT;
DECLARE rows_deleted INT;
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
SET rows = 1;
SET rows_deleted = 10000;
WHILE rows > 0
do
SET autocommit=1;
SET @query =CONCAT('DELETE FROM ',archive_dbname,'.',archive_table,' WHERE ',archive_column,' <= "',archive_date ,'" LIMIT 10000;');
PREPARE arcive_stmt FROM @query;
EXECUTE arcive_stmt;
SET rows = row_count();
SET rows = row_count();
select sleep(1);
commit;
DEALLOCATE PREPARE arcive_stmt;
END WHILE;
END //
delimiter ; -- Execute this procedure
CALL sqladmin_archive ('mydb','test_table','created_at','2018-09-12');

Take dump before archive with where clause:

This script is my favorite one, but this depends on the above stored procedure. This shell script will take the dump of the table with where clause of the date that we want to archive. You can customize this as per your requirement.

#!/bin/bash

# pass variables
archive_dbname=$1
archive_table=$2
archive_column=$3
days_to_archive=$4
archive_date="'"`date +'%Y-%m-%d' --date="-$days_to_archive day"`"'"
where_clause=$archive_column'<='$archive_date
dump_file=$archive_table_`date +'%Y-%m-%d' --date="-$days_to_archive day"`".sql" # Dump the table
echo "DUMP Starting for the table $archive_table ....."
mysqldump -u root $archive_dbname $archive_table --where=$where_clause > $dump_file
echo "DUMP Done......" # Archive the data
echo "Deleting the data on the table $archive_table ....."
mysql -u root sqladmin -e"CALL sqladmin_archive('$archive_dbname','$archive_table','$archive_column',$archive_date);"
echo "Deleting is Done ....."

Example Archive:

This example, Im going to archive a table called test. The column started_at contains the timestamp value. I want to remove older than 15 days data in the table. This table is located in the database name called sqladmin.

./archive_script.sh sqladmin test started_at 15

Archive MySQL Data In Chunks Using Stored Procedure的更多相关文章

  1. JDBC连接执行 MySQL 存储过程报权限错误:User does not have access to metadata required to determine stored procedure parameter types. If rights can not be granted,

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...

  2. Net连接mysql的公共Helper类MySqlHelper.cs带MySql.Data.dll下载

    MySqlHelper.cs代码如下: using System; using System.Collections.Generic; using System.Linq; using System. ...

  3. How To Call Stored Procedure In Hibernate

    How To Call Stored Procedure In Hibernate In this tutorial, you will learn how to call a store proce ...

  4. [转]Mapping Stored Procedure Parameters in SSIS OLE DB Source Editor

    本文转自:http://geekswithblogs.net/stun/archive/2009/03/05/mapping-stored-procedure-parameters-in-ssis-o ...

  5. 关于Linux和Windows下部署mysql.data.dll的注册问题

    mysql ado.net connector下载地址: http://dev.mysql.com/downloads/connector/net/ 选择版本: Generally Available ...

  6. Stored Procedure 里的 WITH RECOMPILE 到底是干麻的?

    在 SQL Server 创建或修改「存储过程(stored procedure)」时,可加上 WITH RECOMPILE 选项,但多数文档或书籍都写得语焉不详,或只解释为「每次执行此存储过程时,都 ...

  7. [转]Dynamic SQL & Stored Procedure Usage in T-SQL

    转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...

  8. Retrieving Out Params From a Stored Procedure With Python

    http://www.rodneyoliver.com/blog/2013/08/08/retrieving-out-params-from-a-stored-procedure-with-pytho ...

  9. [转]Easy Stored Procedure Output Oracle Select

    本文转自:http://www.oraclealchemist.com/oracle/easy-stored-procedure-output/ I answered a question on a ...

随机推荐

  1. 如何设置httpd-mpm-conf的参数

    原文链接:http://blog.sina.com.cn/s/blog_626998030102wohs.html 首先确定apache是使用哪种工作模式是prefork模式还是worker模式查看方 ...

  2. Android so 文件进阶<二> 从dlsym()源码看android 动态链接过程

    0x00  前言 这篇文章其实是我之前学习elf文件关于符号表的学习笔记,网上也有很多关于符号表的文章,怎么说呢,感觉像是在翻译elf文件格式的文档一样,千篇一律,因此把自己的学习笔记分享出来.dls ...

  3. 【IT笔试面试题整理】寻找二叉树两节点的最近的公共祖先

    [试题描述] 求二叉树中任意两个节点的最近公共祖先也称为LCA问题(Lowest Common Ancestor). 二叉查找树 如果该二叉树是二叉查找树,那么求解LCA十分简单. 基本思想为:从树根 ...

  4. vscode浏览器打开html vscode修改默认浏览器

    vscode怎么浏览器打开html预览?这里大家可以通过安装open in browser插件解决. 1.vscode怎么浏览器预览 1.点击拓展 2.输入open in browser,选择第一个 ...

  5. c语言-遍历pci设备(2)mmio访问

    前言 今天其实我在公司也没有做什么,但是昨天就把pcie遍历的mmio形式做了出来,赞扬公司的台湾服务器,至少我可以使用google来去搜索我想要的资料和答案,有一位大神在台湾的论坛上发布了一片博文, ...

  6. SpringMVC之使用Servlet原生API作为参数

    SpringMVC的handler接收如下的ServletAPI类型的参数: • HttpServletRequest • HttpServletResponse • HttpSession • ja ...

  7. Mac Hadoop的安装与配置

    这里介绍Hadoop在mac下的安装与配置. 安装及配置Hadoop 首先安装Hadoop $ brew install Hadoop 配置ssh免密码登录 用dsa密钥认证来生成一对公钥和私钥: $ ...

  8. glob 在webpack中的使用。

    glob 在webpack中对文件的路径处理非常之方便,比如当搭建多页面应用时就可以使用glob对页面需要打包文件的路径进行很好的处理. 官方文档地址 : https://www.npmjs.com/ ...

  9. Oracle数据库操作---入门(一)

    由于工作原因,近期可能会开始多复习一些数据库相关的知识了,想深入了解的,也可以一起复习.学习~ 前期先巩固一下基础操作,后期会一点点的加深向运维方向深入.开篇主要介绍一些数据库理论知识,不感兴趣的可以 ...

  10. JVM调优命令-jmap

    jmap JVM Memory Map命令用于生成heap dump文件,如果不使用这个命令,还可以使用-XX:+HeapDumpOnOutOfMemoryError参数来让虚拟机出现OOM的时候自动 ...