Monday, July 15, 2019

The ultimate guide to MySQL Stored Procedure


Do you want to learn MySQL stored procedure?
This post has every detail that a mysql expert would tell you about the stored procedure in MySQL.
So, let’s start right away!


MySQL stored procedure in a glance
An SQL query batch is known as a stored procedure if it can be included in the storage of the server.
Initial approval and execution of the stored procedure allow a batch to get optimized and securely saved on a server. After that, you can simply use the designated name of the stored procedure to get the whole batch of queries for execution quickly in a secured manner.
Importance of utilizing stored procedure
ü  Increased pace of execution: 
The inclusion of a stored procedure allows the server to optimize and safely secure that particular batch of queries. This stored query set becomes available for future execution right away without making any effort. Hence, it saves time and increases the pace of form execution.
ü  Reduced redundancy of work: 
Instead of doing the same thing again and again, you can use the stored procedure to smartly utilize your work. The compilation of queries becomes a one-time task. Then, it gets stored for every situation when you need to execute the same batch of queries.
ü  Decreased communication costs: 
Communicating the statement lines becomes easier across a network. The server and a client receive lesser traffic due to the batch of queries. A single line statement communicates the whole stored procedure. Otherwise, the network has to process every query individually.
ü  Improved security: 
When it comes to preventing SQL injection, this process serves exceptionally. The optimization of queries in batches and storage safety delivers excellent security.
ü  Authenticated access: 
The security factor also improves due to the limited direct access provided to a user to tables. A user’s role is defined, which grants limited access to a particular procedure. This way, a user can access a procedure, even if that particular user has no direct accessibility in the created tables in a database.
Using MySQL stored procedure
With MySQL 5.0 or going beyond it, you can get the support of the stored procedure. These are the steps required to utilize stored procedure:
§   The statement “Create Procedure” is used to design one stored procedure. You need to specify the database name as well as the name of the stored procedure when creating.
§   Generally, a stored procedure gets surrounded by a command called DELIMITER. The purpose of this step is to ensure that MySQL uses a separate delimiter whenever creating a stored procedure. For that, the last semicolon in the command gets replaced with 2 forward slashes.
§   Run the created statement, and then, crate the proc_name of the stored procedure. Then, you can use the CALL statement to bring the stored procedure for execution.
§   The statement DROP PROCEDURE proc_name; allows you to eliminate a procedure that is not being used.
The use of stored procedure along with parameters
When using stored procedures in MySQL, it is possible to use three parameters.
1. IN
This mode of parameter requires your application to surpass the value of this parameter whenever you call a particular stored procedure. The parameters stay protected, which allows the stored procedure to retain its original value after every execution. The changes in the value of a stored procedure occur only in regards to its parameter. This works as the default parameter mode. So, if you don’t add any parameter, the server uses IN parameter mode.
2. OUT
The OUT parameter allows the change of its value within a stored procedure. Then, the value reaches the calling application.
3. INOUT
As the name suggests, this parameter mode combines the features of the IN as well as OUT modes. It is possible to surpass the initial value and the utilized stored procedure holds the ability to change it. Also, the value reaches a particular calling application.
Now, you have a better understanding of how the stored procedure works in your favor. However, it would be wise to get in touch with a mysql database consultant to get a strategy prepared regarding your specific needs related to the use of MySQL stored procedure. Choose an experienced consultant to ensure the best utilization. 

Wednesday, June 12, 2019

How to fix MySQL high CPU usage?

MySQL is quite popular with open source web applications, but if it is susceptible to performance problems, if not correctly maintained. Performance problems mainly occur through fragmentation of the table, unoptimized memory configurations, and more. All this can lead to elevated utilization of the MySQL CPU and mistakes in the implementation. High server loads are very often linked to high CPU usage. That's not always the case. Because of bottlenecks in any resource, server load can go high. Memory, disk I/O, network or CPU may be included. Memory or I/O fatigue is the main reason for MySQL caused server load. If the bottleneck is caused by I/O, the percentage WA (called waiting average) will have the largest percentage of CPUs. If it is a load caused by memory, on the other hand, the "free" memory would be restricted to a few MBs.
Fixing high CPU usage
1.      Enable InnoDB to manage a large amount of simultaneous links – check MySQL "PROCESSLIST," and if you see a lot of queries in "LOCK" status, it implies that a lot of queries are placed on hold as MyISAM tables manage other transactions. To solve this, convert the tables to an InnoDB engine that promotes locking at row-level.
2.      Enable persistent links – Enabling permanent MySQLconnections can enhance efficiency if you only have a single application that gets thousands of links per hour. This may not operate if the server has various apps (such as a shared internet hosting server).
3.      Block abusive procedures – An abnormally large amount of links could be developed in a brief moment when a website is under assault (such as DoS, commenting on spamming, etc.). To recognize top users and prevent access to abusive links, use the "PROCESSLIST" in MySQL.
4.      Optimize database queries – It is known that some internet apps use complicated queries to show data about the site. These queries can take a long time to run, causing loading of the CPU. Get the list of such queries from the "slow query log" and decrease in a single query the amount of joins and other table manipulations.
5.      Check for "leap second bug" – A leap second to the standard UTC time was added on July 1, 2015. This is seen to cause elevated MySQL load on servers running ancient versions of the Linux kernel and using time servers. If you have an ancient Linux system, use the command date -s "$(date)" to reset the time.

Preventing high CPU usage

1.      MySQL efficiency tuning – For the execution of queries, MySQL utilizes different buffers and cache schemes. The server configurations need to be adjusted for optimum results as the quantity and complexity of database queries change. There are numerous instruments for identifying any configurations that need to be adjusted, such as mysql tuner.
2.      Security audit and hardening – a database server can readily be overwhelmed by spamming and DoS assaults. To stop attackers from influencing server uptime, implement web application firewalls such as ModSecurity and DoS firewalls such as ModEvasive.
3.      Implementing load balancing – It may be necessary to divide the load into various servers as the server traffic increases. For master-master and master-slave replication, MySQL can be configured to allow queries to be served from any cluster server.
4.      Optimizing database queries – No quantity of database optimization will solve the server load if internet apps are badly coded. Monitor the "slow query log" of MySQL and decrease the amount of JOINs in order to speed up the database.
5.      Because of the manner it processes queries, using high-performance solutions such as Percona – MySQL has many memory / CPU bottlenecks. These problems are solved by MySQL spin-offs like MariaDB and Percona and help to attain greater stability.
How to keep MySQL servers stable
Our technicians audit the server efficiency when a client signs up and optimize the MySQL server settings to solve any resource bottlenecks that pre-exist. After analyzing the type and traffic of the website, we modify the key settings in MySQL servers to ensure optimal use of the resource. This involves link boundaries, buffer size, cache size of query, MySQL Performance Optimization and more.
Commenting on spamming, brute forcing, bot attack or even a legitimate traffic boost can trigger a heavy MySQL load. That's why monitoring server metrics is significant 24/7. The server admins track MySQL health 24/7. It enables us to immediately identify a spike in the use of the CPU or abusive program and solve it before the whole server crashes.
Databases increase over time, and when website traffic changes, the load on them shifts. This is why monitoring and re-optimization are critical to maintaining the stability of the MySQL server. A key task of our Dedicated Server Administrators is to frequently audit client servers and find out bottlenecks of mysql performance improvement before they occur and solve them before any clients are impacted.

Wednesday, May 29, 2019

What is the simplest way to optimize MySQL Database Performance?

Like all relational databases, MySQL can prove to be a complicated beast that can halt at a time, leaving your applications in the lurch and your business on the line. The truth is, most MySQL performance issues are underlying common mistakes. It is important to eliminate these errors, which are often obscured by some subtlety in your workload or configuration trap, in order to ensure that your MySQL server hums along at top speed, providing stable and consistent performance. 


Fortunately, many MySQL performance optimization issues turn out to have similar solutions, making it a manageable task to troubleshoot and tun MySQL.


Here are 10 tips from MySQL expert for great performance:

Profile the workload - Profiling the workload of the server is the best way to understand how your server spends its time. You can expose the costliest queries for further tuning by profiling your workload. Time is the most important metric here because you care very little about anything except how quickly it completes when you issue a query against the server.
The best way to profile your workload is by using a tool like the query analyzer for MySQL Enterprise Monitor or the Percona Toolkit pt-query-digest. These tools capture server queries and return a task table sorted by decreasing response time order, instantly bubbling up to the top of the most expensive and time-consuming tasks so you can see where to focus your efforts.

Understand the fundamental resources - Four basic resources are needed for a database server to function: CPU, memory, disk, and network. If any of these are weak, erratic, or overloaded, it is highly likely that the database server will perform poorly. Understanding the basic resources is important in two specific areas: hardware selection and troubleshooting.
Ensure good-performing components all around when selecting MySQL hardware. Just as important, they are fairly well balanced against each other. Organizations often choose servers that have fast CPUs and disks but are hungry for memory. In some cases, adding memory is a cheap way to increase performance by magnitude orders, particularly on disk-bound workloads. This may seem counterintuitive, but disks are overused in many cases because there is not enough memory to hold the working data set of the server.

Avoid using MySQL as a queue - Queues and access patterns like queues can sneak into your application without your knowledge. For example, if you set an item's status so that it can be claimed by a particular worker process before acting on it, then you create a queue unwittingly. It is a common example to mark emails as unsent, send them, then mark them as sent.
Queues cause problems for two main reasons: they serialize your workload, preventing parallel tasks, and often result in a table that includes processing work as well as historical data from long processed jobs. Both add application latency and load MySQL.

Filter the results by the cheapest first - A great way to optimize MySQL is first to do cheap, imprecise work, then hard, accurate work on the smaller, resulting data set. Suppose you're looking for something within a given geographic point radius, for example. The first tool in the toolbox of many programmers is the "Haversine" formula for computing distance along a sphere's surface. The problem with this technique is that the formula requires a lot of very CPU-intensive trigonometric operations. Great-circle calculations tend to run slowly and skyrocket the machine's use of the CPU.
Before applying the formula of the great circle, set your records to a small subset of the total and adjust the resulting set to an accurate circle. A square containing the circle is an easy way to do this (precisely or inaccurately). Thus, with all those expensive trig functions, the world outside the square is never hit.

Know the scalability death traps - Scalability isn't as vague as you might think. There are, in fact, precise mathematical scalability definitions expressed as equations. These equations emphasize why systems are not as scaleful as they should be. Take the Universal Scalability Law, a definition useful to express and quantify the scalability characteristics of a system. It explains problems of scaling in terms of two basic costs: serialization and crosstalk.
Their scalability is inherently limited in parallel processes that must be stopped for something to take place serialized. Likewise, they limit each other if the parallel processes have to chat with each other all the time to coordinate their work. Evite serialization and crosstalk, and it will scale your application much better. What translates into MySQL's inside? It varies, but there are some examples that would avoid exclusive row locks. That is why Queues, point 3 above, tend to scale poorly.


Indexing is probably the most misunderstood topic in databases as there are so many ways to get confused about how indexes work and how they are used by the server. To really understand what is going on, it takes a lot of effort.