Why DBA Tuning for Oracle SQL Query is Crucial in Databases

SQL tuning is an extensive topic in itself that deserves coverage in books dedicated to stored programming. This is because it is considered as a vital skill for those who create stored programs in MySQL or Oracle.

There are several other reasons as well, which we will discuss in this blog. 

DBA Tuning of SQL Queries – Why They are Important

Take a look at some reasons why SQL tuning is so important – 

  • Those who are not convinced about the importance of DBA tuning need to remember a simple fact that SQL statement execution takes up the most time when stored program execution time is analyzed. 
  • Additionally, a database that is insufficiently tuned or not tuned at all is tremendously slow by comparison. 
  • An untuned database cannot scale well with the growth in data volumes. This means that although your program appears to perform acceptably well at the moment, chances are, it will face serious performance issues in the future without proper tuning.

Database Query Optimization – An Informative Example

Given below is an example that explains the necessity of SQL query tuning in overall system performance. Let us consider a query that performs a straightforward join between two tables:

SELECT sum(sale_value),x.sales_id

FROM tx_10000 x,ty_10000 y

 WHERE x.sales_id=y.sales_id

GROUP by x.sales_id;

As data gets collected every day, the size of the tables also increases. At first, there may not be any visible change in performance, but that will change just after some days. After about seven days, the application will become nearly inoperable if the query plan is not correctly selected by the database SQL optimizer, and that’s when the need for a DBA SQL tuning is realized. 

On closer analysis, the DBA shall uncover a proportional relationship between table size and elapsed time. It is also observed that along with the worsening query performance as the tables expand, there is also an acceleration in the rate of increase.

The DBA may project the estimated time to be around twenty hours as the size of the tables approaches their peak sizes, around a million rows, which is truly a poor performance trend. 

The issue and solution both seem obvious once the SQL statements used in the application are assessed, and the solution is to perform database query optimization by supporting the join with an index, which can be created in this manner: 

CREATE INDEX i_ty_1000 ON ty_1000 (sales_id);

This brings a remarkable improvement in the performance trend, with over 99 percent decrease in elapsed time for the mentioned query. Furthermore, the database is over a hundred times quicker and it can now scale well with the raise in table data volumes. 

In Conclusion

Such dramatic changes cannot be achieved through hardware upgrades, stored program tuning, or any amount of server enhancement. Even if any of these were to be carried out, it wouldn’t make much of a difference in the long run. 

This is because the rapid degradation would ultimately quash any performance improvements attained by other techniques. This is why DBA tuning is more important than any other mode of optimization and should be performed first. 

Oracle or MySQL SQL query tuning is the most essential aspect of application performance in general, so make sure that SQL is tuned before any other sort of optimization activities are carried out.

MySQL SQL Performance Tuning: Confusing MySQL Server Variables

MySQL Server contains a wide variety of variables that can be modified according to different uses or to enhance performance. However, despite their detailed documentation, there is plenty of confusion regarding which of these variables are suitable only for storage engines and which ones are utilized on SQL layer, and are applicable for all storage engines as well. 

An important factor to consider during MySQL SQL performance tuning is the storage engine in use. Keeping that in mind, this blog features a list of variables that are sometimes mistaken with similar variables.

MySQL Database and SQL: List of Confusing Variables

Let’s take a look at some variables that may seem confusing to users in terms of their applications (whether they are storage engine specific or used with the SQL layer) – 

  • Read_buffer_size/read_rnd_buffer_size – These variables are used in certain tables for full table scanning and for viewing rows in a sorted manner respectively. However, they are not compatible with all storage engines. 
  • Sort_buffer_size – This buffer is applied when the user needs the result set to be sorted, and is used on the SQL Layer, so it’s applicable for all storage engines and may even be helpful for performance tuning in SQL MySQL. 
  • Bulk_insert_buffer_size – This variable is only applicable for MyISAM tables for optimizing inserts in a large quantity or with numerous values. It is quite helpful when the user needs to insert hundreds or thousands of values in a single insert statement, and there are several such statements.
  • Join_buffer_size – This buffer is used for specific cases, such as joins that do not include indexes. It can be utilized for all the storage engines. 
  • Max_write_lock_count – A variable that is applicable across memory and MyISAM tables, it is suitable for table locks and prevents read starvation in case of numerous table writes. 
  • Key_buffer_size – This is applied in the case of Index Blocks solely for MyISAM tables or, in rare cases, restricted to a range of 4-32MB for temporary tables.
  • Delayed_insert_limit/delayed_insert_timeout, delayed_queue_size – These are used for inserting configuration and are not exactly dependent on any storage engine, yet it lacks support from some of them, such as InnoDB. 
  • Delay_key_write – This is used to improve MySQL database performance in MyISAM tables by extending the time for index updates. However, this variable may lead to table corruption, if a crash occurs. 
  • Low_priority_updates – This provides higher priority to select queries by putting the updates on low priority. It can be enabled when LOCK TABLES are in use, which is why it is storage engine-specific. 
  • Large_pages – This variable enables the utilization of large pages if big global areas need to be allocated, and is also storage engine-specific, such as Innodb and MyISAM. However, it can be used by certain SQL level components like Query Cache in MySQL database and SQL.
  • Key_cache_age_threshold/key_cache_block_size/key_cache_division_limit Key Cache/Key Buffer – The Key_Buffer variable is only applicable to MyISAM. It is used for making changes to algorithm configuration. 
  • Ft_boolean_syntax/ft_max_word_len/ft_min_word_len/ft_query_expansion_limit/ft_stopword_file – These are search variables related to FullTEXT search. Again, these are only useful for limited storage engines for MySQL database and SQL. 
  • Flush/flush_time – Initially designed for MyISAM tables, this variable impacts all the tables once the query is over or for certain flush_time set intervals. 
  • Preload_buffer_size – Another buffer that is only useful for MyISAM tables in key preloading. 
  • Timed_mutexes – This variable has been designed to use on all storage engines to show the mutex status. 
  • Tmp_table_size – It is used to specify the maximum limit in size for implicit temporary tables. These are tables that are created automatically at the time of each execution. 

Conclusion

These were some variables whose application is often confused by some users. Knowing more about these may turn out to be useful from the point of view of MySQL SQL performance tuning. 

On a related topic, if you are in search of tools for improving MySQL database performance that don’t require expert knowledge about the database, then Tosska’s tools for database tuning can be a great fit for your organization. Our tools have been designed with cutting edge AI technology to make query tuning as easy as pointing and clicking. 

So, make sure to explore all of our tools and find the right variant for your requirements, and if you aren’t sure about anything, just get in touch with our experts and have your SQL performance tuning related queries resolved today!

How to Tune SQL with OR statements?

Tosska Chat Box

It is common that the performance is not good if a SQL statement with OR conditions. Let’s have an example show you how to tune those SQL statements in certain situations. Here is an example SQL that extract records from EMPLOYEE table if (emp_grade < 1050 or emp_id<730000). Emp_grade and emp_id are indexed and they are not null field.

select * from employee
where emp_grade < 1050 or emp_id<730000

You can see MySQL SQL Optimizer use an Index Merge of emps_grade_inx and employee_pk to process the SQL, the performance is not good as expected since the result set is quite big for sort_union operation. It takes more than 40 seconds to finish the data retrieval. Let me rewrite the OR condition into the following UNION ALL statement, please make sure the emp_grade and emp_id are not null column, otherwise it may generate error result. The rewrite is simple that the first part extract data with emp_grade<1050, the second part of the UNION ALL retrieve records that satisfied with emp_id<730000, but it is not retrieved in the first part of the UNION ALL.

select    *
from       employee
where    emp_grade < 1050
union all
select    *
from       employee
where    not ( emp_grade < 1050 )
                  and emp_id < 730000

Here the following is the query plan of this SQL, it takes 12.46 seconds to finish. The query shows two “Index Range Scan” of EMPLOYEE_PK and EMPS_GRADE_INX to the employee table.

This kind of rewrites can be achieved by Tosska SQL Tuning Expert for MySQL automatically, it shows that the rewrite is more than 3 times faster than the original SQL. There are some other rewrites shown in this screen with comparable results too.

https://tosska.com/tosska-sql-tuning-expert-tse-for-mysql-2/

How to Tune SQL with COUNT(*) statements ?

sql performance monitoring

It is common that we used to count the number of records in a table.  You may encounter unexpected performance degradation in certain situations. Here is an example SQL that count number of records from EMPLOYEE table. There are number of indexes are built such as emp_id, emp_dept, emp_grade, emp_hire_date and etc….

SELECT COUNT(*)
   FROM EMPLOYEE;

You can see MySQL SQL Optimizer use a Full Index Scan of EMP_HIRE_DATE index, the performance is bad since unnecessary random reads is needed and it takes 3 minutes and 6 seconds to count a 3 million records in my computer.  I want to make use of Index Range Scan for specific index, let me rewrite the above SQL into the following syntax. If you know EMP_GRADE is indexed and it is not a nullable column, you can add a dummy condition EMP_GRADE>=’’. It fools MySQL SQL optimizer to consider using EMP_GRADE range index to retrieve the records and it is successfully generate a new plan in the following:

select    COUNT(*)
from       EMPLOYEE
where    EMP_GRADE >=  ‘ ‘

Here the following is the query plan of this SQL, it takes 2.6 seconds to finish. The query shows an “Index Range Scan” of employee table.

This kind of rewrites can be achieved by Tosska SQL Tuning Expert for MySQL automatically, it shows that the rewrite is almost 71 times faster than the original SQL. There are some other rewrites shown in this screen with comparable results too.

https://tosska.com/tosska-sql-tuning-expert-tse-for-mysql-2/

How to Tune substr(emp_name,5,4) SQL Statement?

sql performance monitoring

There may be some business requirements that need to compare certain part of a column as a data retrieval criteria. Here is an example SQL that retrieves data from EMPLOYEE table employee’s name with a string pattern “Acco” start from 5 character of the emp_name.

select    *
  from    employee
where    substr(emp_name,5,4)=‘Acco’

Here the following are the query plans of this SQL, it takes 17 seconds to finish. The query shows a “Full Table Scan Employee”  

You can see that this SQL cannot utilize index scan even the emp_name is indexed field. Let me add a “Force Index(emp_name_inx)“ hints to the SQL and hope it can help MySQL SQL optimizer to use index scan, but it fails to enable the index scan anyway, so I add one more dummy condition emp_name >= ‘ ‘ , it is an always true condition that emp_name should be greater or equal to a smallest empty character.

select    *
from       employee force index(emp_name_inx)
where    substr(emp_name,5,4) = ‘Acco’
                 and emp_name >= ‘ ‘

Here is the query plan of the rewritten SQL and it is running faster. The new query plan shows that an Index Range Scan is used now.

This kind of rewrite can be achieved by Tosska SQL Tuning Expert for MySQL automatically, it shows that the rewrite is almost 6 times faster than the original SQL.

https://tosska.com/tosska-sql-tuning-expert-tse-for-mysql-2/

How to Tune “order by rand() limit 1” SQL Statement ?

sql performance monitoring

There may be some business requirements that needs to retrieve only some rows from a table (or join tables) randomly. This kind of SQL is normally hard to tune.

For example the following SQL retrieve one row from two tables join of Employee and Department, where Employee’s department code is ‘AAA’, and both Emp_dept and Dpt_id columns are indexed.

select  *
  from employee ,department
where emp_dept=dpt_id
and emp_dept = ‘AAA’
order by rand()
limit 1

Here the following is the query plan of this SQL, it takes 3.126 seconds to finish. The query shows a nested loop from Department table to Employee table to extract all records with ‘AAA’ department code. An Order operation is executed followed from the join result.

You can see the most expensive step is to extract all Employee data with department code “AAA”, if there is an unique key such Employee ID (EMP_ID) which can uniquely identify a row from the query, you can use the With common table expressions in MySQL version 8 to randomly select rows from the KEY column only with the same conditions given by the original query, for example the following blue colored SQL text in “With” clause, it randomly select 1 row of EMP_ID from the join query. It not only significantly reduces the size of the data retrieved from Employee table, but it also shrank the size of Order By operation. And then the main query will use the selected EMP_ID to extract specific row from original query, so the whole query will run faster with this new rewrite syntax.

with DT1
     as (select  EMP_ID
        from   employee,
         department
        where   emp_dept = dpt_id
         and emp_dept = ‘AAA’
        order by rand() limit 1
)
      select    *
      from       employee,
     department
      where    emp_dept = dpt_id
     and emp_dept = ‘AAA’
     and EMP_ID in (select EMP_ID
             from   DT1)
      order by rand() limit 1

/* Remark:  “order by rand() limit 1” is used to make sure that only 1 row will be selected if the EMP_ID cannot uniquely identify only one row */

Here is the query plan of the rewritten SQL with less cost and run much faster.

This kind of rewrite can be achieved by Tosska SQL Tuning Expert for MySQL automatically, it shows that the rewrite is almost 100 times faster than the original SQL.

https://tosska.com/tosska-sql-tuning-expert-tse-for-mysql-2/

How to Tune “Order by Limit N” SQL Statement?

sql performance monitoring

There may be some business requirements that need to retrieve the first N number of rows from a join tables. Some people may encounter unexpected performance problem.

Here is an example SQL that retrieves first 1000 row from a join tables of Employee and Department in the order of dpt_id.  Where emp_dept and dpt_id columns are both indexed.

select *
     from employee ,department
where emp_dept=dpt_id
order by dpt_id
limit 1000

Here the following are the query plans of this SQL, it takes 1 mins and 8 seconds to finish. The query shows a nested loop from “Full Table Scan Employee” to “Unique Key Lookup Department” table to extract all records. An “Order by” operation of dpt_id of Department table is executed followed from this join result.

You can see the most expensive step is to extract all Employee data with Department data and then an Order by dpt_id  of Department table. Let’s see if we rewrite the original SQL text into the syntax that “order by dpt_id” is changed to “order by emp_dept”. It is a semantically eqvialent rewrite of original SQL statement since “emp_dept = dpt_id”.

select       *
from          employee,
                     department
where       emp_dept = dpt_id
order by    emp_dept
limit            1000

Here is the query plan of the rewritten SQL with less cost and run much faster. The new query plan shows that no “Use temporary; Using filesort” in Tabular Explain, it means the Nested Loop operation will be stop at the Limit 1000 records is done.

This kind of rewrite can be achieved by Tosska SQL Tuning Expert for MySQL automatically, it shows that the rewrite is almost 70 times faster than the original SQL.

https://tosska.com/tosska-sql-tuning-expert-tse-for-mysql-2/

How to Tune SQL with LIKE ‘%Mary%’ comparison?

sql performance monitoring

The LIKE is a logical operator that determines if a character string matches a specified pattern. A pattern may include regular characters and wildcard characters. The LIKE operator is used in the WHERE clause of the SELECT, UPDATE, and DELETE statements to filter rows based on pattern matching.

Here is an example SQL that retrieves data from EMPLOYEE table employee’s name with a string pattern like “Mary%”. If the emp_name is indexed, the following SQL will utilize Index Range Scan of the emp_name and the speed of the SQL will be fine.

select *
from employee
where emp_name like ‘Mary%’;

If user is looking for emp_name with pattern like ‘%Mary%’, MySQL SQL Optimizer cannot user emp_name index to speed up the process, full table scan is normally be used and the performance will be bad too.

select *
from employee
where emp_name like ‘Mary%’;

Here the following are the query plan of this SQL, it takes 18.8 seconds to finish. The query shows a “Full Table Scan” of employee table.

You can see that this SQL cannot utilize index scan even the emp_name is indexed. Let me add a “Force Index(emp_name_inx)“ hints to the SQL and hope it can help MySQL SQL optimizer to use index scan, but it fails to enable the index scan anyway, so I add one more dummy condition emp_name >= ” , it is an always true condition that emp_name should always greater or equal to a smallest empty character.

select *
from   employee force index(emp_name_inx)
where  emp_name like ‘%Mary%’
       and emp_name >= ‘ ‘;

Here is the query plan of the rewritten SQL and it is running faster. The new query plan shows that an Index Range Scan is used now.

This kind of rewrites can be achieved by Tosska SQL Tuning Expert for MySQL automatically, it shows that the rewrite is almost 5 times faster than the original SQL.

https://tosska.com/tosska-sql-tuning-expert-tse-for-mysql-2/

Improve MySQL Database Performance by Controlling Partitions

If you have been dealing with large MySQL data for a while, you may have faced an interesting case like this at some point – one which involves a table with data merged with INSERT IN DUPLICATE KEY queries. 

Even if you haven’t faced such a situation so far, you may be able to tell that such a table will show an extremely slow performance, and the culprit most definitely is the multitude of partitions that have been made every day for this table. In this blog, we will examine if changing the number of partitions can improve MySQL database performance.   

Improve MySQL Database Performance by Paying Attention to Partitions!

Surprisingly, the statements are also affected differently from each other, and this is something that also impacts performance.

To understand this problem a bit more clearly, let us consider an example where we create a test table – 

CREATE TABLE `Partition` (

    `number` int(10) unsigned NOT NULL,

    `name`  int(10) unsigned NOT NULL,

     PRIMARY KEY (`number`),

     KEY(name)

     ) ENGINE=InnoDB

     PARTITION BY RANGE(number) (

     PARTITION p100000 VALUES LESS THAN(100001),

PARTITION p200000 VALUES LESS THAN(200001),

PARTITION p300000 VALUES LESS THAN(300001),

PARTITION p400000 VALUES LESS THAN(400001),

PARTITION p500000 VALUES LESS THAN(500001),

PARTITION p600000 VALUES LESS THAN(600001),

PARTITION p700000 VALUES LESS THAN(700001),

PARTITION p800000 VALUES LESS THAN(800001),

PARTITION p900000 VALUES LESS THAN(900001),

PARTITION p1000000 VALUES LESS THAN(1000001)

   );

In this example, we are varying the quantity of partitions between 1 and 1000. We are also loading the table with one million sequential values through bulk insert queries, where the number and name columns are set the same and there are a thousand rows in each table.

Time Taken to Load in Different Scenarios:

  • This data ends up taking around 10 seconds for loading a single partition, 11 seconds for ten partitions, 17 seconds for a hundred partitions and 24 seconds for a thousand partitions. 
  • Also, every time the number of partitions increases by a thousand, the loading speed decreases 2.5 times. 
  • Such regression is slightly unexpected, given the lack of data insertion into the partitions in every insert statement. Moreover, it worsens when the user tests an update statement with a condition – “set name=name+1”; the loss in performance is at least five times with a change in the pattern, and it is way more drastic as the user moves from a hundred to a thousand partitions than it was in the case where we only used the insert command. 
  • Finally, the difference magnifies when the user eliminates the index on column C. The UPDATE aspect of the INSERT ON DUPLICATE KEY UPDATE statement takes 23 seconds for a single partition and more than 240 seconds for a thousand partitions. This is more than ten times the original time!

This issue with partitions impacts both MyISAM and Innodb, where the update query in MyISAM without indices can take ten seconds for 1 partition and upwards of fifty seconds for 1000 partitions. 

Why is this Happening?

The dramatically increased load times may be caused by one of two suspects – either the overhead of statements creating the partitions for execution or the overhead created by executing each row. 

On testing the batch performance with varying numbers of rows in the batches, the batch performance was not found to be significantly different among batches with 100 rows and those with 10000, which is why the answer here is the per row overhead.

Additionally, this test reveals that update statements for CPU bound workload can prove to be about five times slower than insert statements. 

Final Thoughts

Users must certainly keep an eye on the number of partitions being used and think about future use while creating idle partitions. This simple step can improve MySQL database performance to a large extent, but if this is not the case with you, it might be wise to consider tuning tools for MySQL, such as Tosska SQL Tuning Expert (TSEM™) for MySQL. 

This is because load times and other such results are highly dependent on workloads and every case is different. Nevertheless, these tools will prove indispensable for improving your database’s performance.  

Analyzing the Inner Works of MySQL SQL Performance Tuning and Oracle Database

When it comes to MySQL, slow performance in large tables is one of the main sources of complaints. It is true that some users face problems as their database fails to sufficiently handle a more than a certain number of rows.

However, there also are many corporations that use MySQL for millions, even billions of rows of data and yet they successfully deliver excellent promise. So, why is there a contradiction between these two cases? The answer lies in understanding the intricacies of table designing in MySQL, and with the help of MySQL SQL performance tuning, how to make them work in your favour.    

What to Consider During MySQL SQL Performance Tuning

There are three major aspects of the database that can have an impact on databases with huge amounts of data. Let’s take a look at two of them now:

Buffers

The first thing to consider with any database management system is that you must have an estimate of the memory, even as you progress in terms of data accumulation. It is important for the memory to be sufficient because performance suffers greatly if it isn’t, so don’t be surprised if a drop in performance is greater than you anticipated because you may have lost track of the growth in data size and subsequently, the need for more memory space. This applies to the other aspects covered in this blog as well. Once data outgrows the memory, everything can be expected to slow down, and MySQL database and SQL becomes a necessity.

One way to ensure the memory remains sufficient for your data is to practice data partitioning. In this process, old data that is no longer required as often as recent data, is separated and stored in other servers. There are various other ways of ensuring sufficient space which we will talk about in another blog.

Indices

Indices, or indexes, are known by most of us to be a useful tool in improving the accessing speed of the database. An important thing to remember is that their usefulness depends a lot on exclusivity, i.e., the ability to select a number of rows that match with specific index ranges or values. Also, the nature of the workload – specifically whether it is cached or not – determines how much it will benefit from the use of an index.

This is actually overlooked by even MySQL optimizer at present and may need to be checked by other MySQL SQL performance tuning tools. Workload indices have a chance of much quicker access even if the size of the data being accessed is as large as fifty percent of the entire number of rows, as long as they are in-memory. On the other hand, for disk IO bound access, you may have greater success in fetching data through a full table scan irrespective of the number of rows you are requesting access to.

Since indices can differ from each other in many ways, they need to be used differently in order to effectively use them. For instance, you can place them either in a well-organized manner or at random spots, resulting in significant changes in their speed. Innodb also includes clustered keys which work by merging data and index access – such keys end up conserving IO that will prove invaluable for workloads that are entirely disk-bound.

In Conclusion

Designing table structures smartly involves taking into consideration all the abilities and disabilities of MySQL. This is especially important if you have to handle different kinds of databases in your organization.

The main reason why your organization has different databases in the first place is because of their different capabilities and shortcomings. So, the same design concepts won’t bring the same results in say, MS SQL or Oracle that they did in MySQL and vice versa. The same is true for their storage engines – each can have a different effect on the performance.

Once you have applied the right application architecture to plan your tables, you will be able to create applications that can easily handle huge data sets on the basis of MySQL.

Proper MySQL SQL performance tuning involves optimizations that can greatly boost the rate at which indices are accessed or scanned. There already are tools by Tosska Technologies Limited for this purpose like Tosska SQL Tuning Expert (TSEM™) for MySQL which you can download and start using today. Contact our team for further information or enquiries.