Optimizing Database Performance, part 5: Database Reorganization

Portions of this tip were excerpted from my book Database administration: The complete guide to DBA practices and procedures (2nd edition).

The first , second , third, and fourth parts of this series are also available.

Today’s topic is reorganization.

Relational technology and SQL make data modification easy. Just issue an INSERT, UPDATE, or DELETE statement with the appropriate WHERE clause and the DBMS takes care of the actual data navigation and modification. In order to provide this level of abstraction, the DBMS handles the physical placement and movement of data on disk. Theoretically, this makes everyone happy. The programmer’s interface is simplified, and the DBMS takes care of the hard part—manipulating the actual placement of data. However, things are not quite that simple. The manner in which the DBMS physically manages data can cause subsequent performance issues.

Every DBA has encountered the situation where a query or application that used to perform well slows down after it has been in production for a while. These slowdowns have many potential causes—perhaps the number of transactions issued has increased, or the volume of data has expanded. However, the performance problem might be due to database disorganization. Database disorganization occurs when a database’s logical and physical storage allocations contain many scattered areas of storage that are too small, not physically contiguous, or too disorganized to be used productively. Let’s review the primary culprits. Query or application slowdowns have many potential causes:

  • The first possibility is unclustered data. If the DBMS does not strictly enforce clustering, a clustered table or index can become unclustered as data is added and changed. If the data becomes significantly unclustered, the DBMS cannot rely on the clustering sequence. Because the data is no longer clustered, queries that were optimized to access data cannot take advantage of the clustering sequence. In this case, the performance of queries run against the unclustered table will suffer.
  • Fragmentation is a condition in which there are many scattered areas of storage in a database that are too small to be used productively. It results in wasted space, which can hinder performance because additional I/Os are required to retrieve the same data.
  • Row chaining or row migration occurs when updated data does not fit in the space it currently occupies, and the DBMS must find space for the row. With row chaining, the DBMS moves a part of the new, larger row to a location within the tablespace where free space exists. With row migrations, the full row is placed elsewhere in the tablespace. In each case, a pointer is used to locate either the rest of the row or the full row. Both row chaining and row migration will result in the issuance of multiple I/Os to read a single row. Performance will suffer because multiple I/Os are more expensive than a single I/O.
  • Page splits can cause disorganized databases, too. If the DBMS performs monotonic page splits when it should perform normal page splits, or vice versa, space may be wasted. When space is wasted, fewer rows exist on each page, causing the DBMS to issue more I/O requests to retrieve data. Therefore, once again, performance suffers.
  • File extents can negatively impact performance. An extent is an additional file that is “connected” to the original file and can be used only in conjunction with the original file. When the file used by a tablespace runs out of space, an extent is added for the file to expand. However, file extents are not stored contiguously with the original file. As additional extents are added, data requests will need to track the data from extent to extent, and the additional code this requires is unneeded overhead. Resetting the database space requirements and reorganizing can clean up file extents.

Depending on the DBMS, there may be additional causes of disorganization. For example, if multiple tables are defined within a single tablespace, and one of the tables is dropped, the tablespace may need to be reorganized to reclaim the space.

The need to access a table in a tablespace having any of these issues can cause a previously efficient application to perform worse.

Reorganizaing Disorganized Tablespaces

To correct disorganized database structures, the DBA can run a database or tablespace reorganization utility, or REORG, to force the DBMS to restructure the database object, thus removing problems such as unclustered data, fragmentation,  row chaining, etc. The primary benefit of reorganization is the resulting speed and efficiency of database functions because the data is organized in a more optimal fashion on disk. In short, reorganization maximizes availability and reliability for databases.

Both tablespaces and indexes can be reorganized. How the DBA runs a REORG utility depends on the specific DBMS in use. Some DBMS products ship with a built-in reorganization utility; others require the customer to purchase separate software or “roll their own.” Still others claim that the customer will not need the utility at all when using their DBMS. I have found the last claim to be untrue. Every DBMS incurs some degree of disorganization as data is added and modified.

To “roll your own,” DBAs can manually reorganize a database by completely rebuilding it. Accomplishing such a reorganization requires a complex series of steps as depicted below. reorg-process

Figure 1. Typical steps for a manual reorganization.

Of course, depending upon the DBMS and the specific options chosen for the object additional steps (such as decompression/recompression and/or sorting) may be necessary.

If a utility is available for reorganizing, from either the DBMS vendor or a third-party vendor, the process is greatly simplified. Sometimes the utility is as simple as issuing a command such as:

REORG TABLESPACE DB.TSNAME

A traditional reorganization requires the database (or at least the database object) to be offline. The high cost of downtime creates pressure both to perform and to delay preventive maintenance—a no-win situation familiar to most DBAs. Most modern REORG utilities are available that perform the reorganization while the database structures are online. Such a reorganization is accomplished by making a copy of the data. The online REORG utility reorganizes the copy while the original data remains online. When the copied data has been reorganized, an online REORG uses the database log to “catch up” by applying to the copy any data changes that occurred during the process. When the copy has caught up to the original, the online REORG switches the production tablespace from the original to the copy. Performing an online reorganization requires additional disk storage and a slow transaction window. If a large number of transactions occur during the online reorganization, REORG may have a hard time catching up.

Today, there are some next generation utilities being introduced that eliminate steps and adjust the manner in which the reorganization occurs based on the database object being reorged. Such modern software may be required for high availability, large volume applications.

Determining When to Reorganize

System catalog statistics can help to determine when to reorganize a database object. Each DBMS provides a method of reading through the contents of the database and recording statistical information about each database object. Depending on the DBMS, this statistical information is stored either in the system catalog or in special pages within the database object itself.

One statistic that can help a DBA determine when to reorganize is cluster ratio. Cluster ratio is the percentage of rows in a table that are actually stored in clustering sequence. The closer the cluster ratio is to 100 percent, the more closely the actual ordering of the rows on the data pages matches the clustering sequence. A low cluster ratio indicates bad clustering, and a reorganization may be required. A low cluster ratio, however, may not be a performance hindrance if the majority of queries access data randomly instead of sequentially.

Tracking down the other causes of disorganization can sometimes be difficult. Some DBMSs gather statistics on fragmentation, row chaining, row migration, space dedicated to dropped objects, and page splits; others do not.

One example: Oracle provides a plethora of statistics in dynamic performance tables that can be queried in a special group of tables called the Oracle Dynamic Performance Tables.

Tablespaces are not the only database objects that can be reorganized. Indexes, too, can benefit from reorganization. As table data is added and modified, the index too must be changed. Such changes can cause the index to become disorganized.

A vital index statistic to monitor is the number of levels. Most relational indexes are b-tree structures. As data is added to the index, the number of levels of the b-tree will grow. When more levels exist in the b-tree, more I/O requests are required to move from the top of the index structure to the actual data that must be accessed. Reorganizing an index can cause the index to be better structured and require fewer levels.

Another index statistic to analyze to determine wheher reorganization is required is the distance between the index leaf pages, or leaf distance. Leaf distance is an estimate of the average number of pages between successive leaf pages in the index. Gaps between leaf pages can develop as data is deleted from an index or as a result of page splitting. Of course, the best value for leaf distance is zero, but achieving a leaf distance of zero in practice is not realistic. In general, the lower this value, the better. Review the value over time to determine a high-water mark for leaf distance that will indicate when indexes should be reorganized.

Summary

Database reorganization is a very important component in the DBA’s aresenal of performance tools. Taking the time to understand how your DBMS supports reorganization will be an important part of the overall job of maintaining optimal database/application performance.

This series of blog posts is excerpted from Craig Mullins’ classic book Database administration: The complete guide to DBA practices and procedures. Consult the book for more in-depth information on any of these topics – and much, much more.

Posted in DBA | Tagged , , , | 1 Comment

Optimizing Database Performance, part 4: File Placement and Page Sizing


Portions of this tip were excerpted from my book Database administration: The complete guide to DBA practices and procedures (2nd edition).

The first , second , and third parts of this series are also available.

Today we start by discussing file placement and data set allocation.

File Placement and Allocation

The location of the files containing the data for the database can have an impact on performance. A database is very I/O intensive, and the DBA must make every effort to minimize the cost of physical disk reading and writing.

This discipline entails

  • Understanding the access patterns associated with each piece of data in the system
  • Placing the data on physical disk devices in such a way as to optimize performance

The first consideration for file placement on disk is to separate the indexes from the data, if possible. Database queries are frequently required to access data from both the table and an index on that table. If both of these files reside on the same disk device, performance degradation is likely. To retrieve data from disk, an arm moves over the surface of the disk to read physical blocks of data on the disk. If a single operation is accessing data from files on the same disk device, latency will occur; reads from one file will have to wait until reads from the other file are processed. Of course, if the DBMS combines the index with the data in the same file, this technique cannot be used.

Another rule for file placement is to analyze the access patterns of your applications and separate the files for tables that are frequently accessed together. DBAs should do this for the same reason they should separate index files from table files.

A final consideration for placing files on separate disk devices occurs when a single table is stored in multiple files (partitioning). It is wise in this case to place each file on a separate disk device to encourage and optimize parallel database operations. If the DBMS can break apart a query to run it in parallel, placing multiple files for partitioned tables on separate disk devices will minimize disk latency.

With modern disk systems such as RAID devices, precise file placement is often difficult, if not impossible, to achieve. RAID storage consists of arrays of disk drives, and the files stored on the device are split across multiple physical disk drives. Be sure to read the documentation for your specific DBMS and follow the guidance for the placement of critical system files (such as log and configuration files). And keep in mind that a hard disk drive with two partitions, one holding log files and the other partition holding data files, is not the same as two disks, each dedicated to either log or data files.

Database Transaction Log Placement

Placing the transaction log on a separate disk device from the actual data allows the DBA to back up the transaction log independently from the database. It also minimizes dual writes to the same disk. Writing data to two files on the same disk drive at the same time will degrade performance even more than reading data from two files on the same disk drive at the same time. Remember, too, that every database modification (write) is recorded on the database transaction log.

Distributed Data Placement

The goal of data placement is to optimize access by reducing contention on physical devices. Within a client/server environment, this goal can be expanded to encompass the optimization of application performance by reducing network transmission costs.

Data should reside at the database server where it is most likely, or most often, to be accessed. For example, Chicago data should reside at the Chicago database server, Los Angeles–specific data should reside at the Los Angeles database server, and so on. If the decision is not so clear-cut (e.g., San Francisco data if there is no database server in San Francisco), place the data on the database server that is geographically closest to where it will be most frequently accessed (in the case of San Francisco, L.A., not Chicago).

Be sure to take fragmentation, replication, and snapshot tables into account when deciding upon the placement of data in your distributed net-work.

Disk Allocation

The DBMS may require disk devices to be allocated for database usage. If this is the case, the DBMS will provide commands to initialize physical disk devices. The disk initialization command will associate a logical name for a physical disk partition or OS file. After the disk has been initialized, it is stored in the system catalog and can be used for storing table data.

Before initializing a disk, verify that sufficient space is available on the physical disk device. Likewise, make sure that the device is not already initialized.

Use meaningful device names to facilitate more efficient usage and management of disk devices. For example, it is difficult to misinterpret the usage of a device named DUMP_DEV1 or TEST_DEV7. However, names such as XYZ or A193 are not particularly useful. Additionally, maintain documentation on initialized devices by saving script files containing the actual initialization commands and diagrams indicating the space allocated by device.

Page Size (Block Size)

Sizing database blocks (or pages) is another important method that can be used to control and manage database and application performance.

Most DBMSs provide the ability to specify a page, or block, size. The page size is used to store table rows (or, more accurately, records that contain the row contents plus any overhead) on disk. For example, consider a table requiring rows that are 125 bytes in length with 6 additional bytes of overhead. This makes each record 131 bytes long. To store 25 records on a page, the page size would have to be at least 3,275 bytes. However, each DBMS requires some amount of page overhead as well, so the practical size will be larger. If page overhead is 20 bytes, the page size would be 3,295—that is, 3,275 + 20 bytes of overhead.

This discussion, however, is simplistic. In general practice, most table spaces will require some amount of free space to accommodate new data. Therefore, some percentage of free space will need to be factored into the equation.

To complicate matters, many DBMSs limit the page sizes that can be chosen. For example, DB2 for z/OS limits page size to 4K, 8K, 16K, or 32K; Microsoft SQL Server supports only an 8K page size. In the case of DB2, the DBA will need to calculate the best page size based on row size, the number of rows per page, and free space requirements.

Consider this question: “In DB2 for z/OS, what page size should be chosen if 0 percent free space is required and the record size is 2,500 bytes?”

The simplistic answer is 4K, but it might not be the best answer. A 4K page would hold one 2,500-byte record per page, but an 8K page would hold three 2,500-byte records. The 8K page could provide for more efficient sequential I/O processing, because reading 8K of data would return three rows, whereas reading 8K of data using two 4K pages would return only two rows.

Choosing the proper page size is an important DBA task for optimizing database I/O performance.

Summary

Page/block size and file/data set allocation can be important criteria for DBAs as they optimize and manage their database systems. Understanding the options available for your specific DBMS will allow you to become a better DBA and improve the performance of your databases, applications, and systems.

This series of blog posts is excerpted from Craig Mullins’ classic book Database administration: The complete guide to DBA practices and procedures. Consult the book for more in-depth information on any of these topics – and much, much more

 

Posted in database design, DBA, performance | 2 Comments

Optimizing Database Performance, part 3: Free Space and Compression

This tip is excerpted from my book Database administration: The complete guide to DBA practices and procedures.

The first and second parts of this series are also available.

Today we start by discussing free space.

Free Space

Free space, sometimes called fill factor, can be used to leave a portion of a table space or index empty and available to store newly added data. The specification of free space in a table space or index can reduce the frequency of reorganization, reduce contention, and increase the efficiency of access and insertion. Each DBMS provides a method of specifying free space for a database object in the CREATE and ALTER statements. A typical parameter is PCTFREE, where the DBA specifies the percentage of each data page that should remain available for future inserts. Another possible parameter is FREEPAGE, where the DBA indicates the specified number of pages after which a completely empty page is available.

Ensuring a proper amount of free space for each database object provides the following benefits:

  • Inserts are faster when free space is available.
  • As new rows are inserted, they can be properly clustered.
  • Variable-length rows and altered rows have room to expand, potentially reducing the number of relocated rows.
  • Fewer rows on a page results in better concurrency because less data is unavailable to other users when a page is locked.

However, free space also has several disadvantages.

  • Disk storage requirements are greater.
  • Scans can take longer.
  • Fewer rows on a page can require more I/O operations to access the requested information (when sequentially accessing many rows).
  • Because the number of rows per page decreases, the efficiency of data caching can decrease because fewer rows are retrieved per I/O.

The DBA should monitor free space and ensure that the appropriate amount is defined for each database object. The correct amount of free space must be based on:

  • Frequency of inserts and modifications
  • Amount of sequential versus random access
  • Impact of accessing unclustered data
  • Type of processing
  • Likelihood of row chaining, row migration, and page splits

Don’t define free space for a static table — that is not going to grow in size. Static tables do not need room in which to expand.

Compression

Another useful database performance tuning tactic is to deploy data compression.

Compression can be used to shrink the size of a database. By compressing data, the database requires less disk storage. Some DBMSs provide internal DDL options to compress database files; third-party software is available for those that do not provide such features.

When compression is specified, data is algorithmically compressed upon insertion into the database and decompressed when it is read. Reading and writing compressed data consumes more CPU resources than reading and writing uncompressed data: The DBMS must execute code to compress and decompress the data as users insert, update, and read the data.

So why compress data? Consider an uncompressed table with a row size of 800 bytes. Five of this table’s rows would fit in a 4K data page (or block). Now what happens if the data is compressed? Assume that the compression routine achieves 30% compression on average (a very conservative estimate). In that case, the 800-byte row will consume only 560 bytes (800 x 0.30 = 560). After compressing the data, seven rows will fit on a 4K page. Because I/O occurs at the page level, a single I/O will retrieve more data, which will optimize the performance of sequential data scans and increase the likelihood of data residing in the cache (or buffer pool) because more rows fit on a physical page.

Of course, compression requires a trade-off that the DBA must analyze. On the positive side, we have disk savings and the potential for reducing I/O cost. On the negative side, we have the additional CPU cost required to compress and decompress the data. Depending on the DBMS and hardware being used though, the CPU consumption may be nominal or not worth considering. For example, DB2 for z/OS takes advantage of an on-board chip for database compression operations which does not require taxing the general CPU and is very efficient.

However, compression is not an option for every database index or table. For smaller amounts of data, it is possible that a compressed file will be larger than an uncompressed file. This is so because some DBMSs and compression algorithms require an internal dictionary to manage the compression. The dictionary contains statistics about the composition of the data that is being compressed. For a trivial amount of data, the size of the dictionary may be greater than the amount of storage saved by compression.

Summary

Free space and compression are two additional tools in the DBA’s arsenal for optimizing and controlling database performance. Understanding how each is handled for your specific DBMS will allow you to become a better DBA and improve the performance of your databases, applications, and systems.

This series of blog posts is excerpted from Craig Mullins’ classic book Database administration: The complete guide to DBA practices and procedures. Consult the book for more in-depth information on any of these topics – and much, much more

Posted in DBA | Tagged , , | 4 Comments

New API Security Survey Highlights Mobile Security Concerns

A new survey on API security titled Global State of API Security Survey 2015, conducted by API management vendor Akana, was released today. This is the first survey conducted by Akana on API Security. The survey offers up a lot of interesting findings for those interested in IT security.

The survey was the result of questioning more than 250 security practitioners, including CSOs, CISOs, and security architects. The primary results of the survey show that the majority of respondents are taking steps to secure API access, but only a few have actually taken steps to ensure that sensitive data is being securely handled in the Apps that access the APIs.

More than 65% of the respondents reported that they do not have processes in place to ensure that the data that is being accessed by applications consuming APIs is managed securely. With mobile apps and IoTs increasingly being API consumers, enterprises face exposure to threats of unauthorized access to data once accessed through an API.  Almost 60% of survey respondents indicated that they were not securing API consumers.

Interestingly — and appropriately — API security is as much an issue for the business as it is for IT, with 75 percent respondents indicating that API security was a CIO-level concern and 65 percent saying was an issue for business managers. As APIs are increasingly being adopted to drive digital initiatives, both business and IT see increasingly value in securing them.

Perhaps the most significant finding of the survey is that many businesses are not taking adequate measures to secure the API consumer. While attention is being paid to building controls and countermeasures into the API itself, many respondents appear to be neglecting a major point of vulnerability: the app that’s accessing that API. Almost 60 percent of respondents (see figure below) indicated that they did not have processes in place to check if the API consumer is handling the data and API securely.

API-fig

Figure. Do you have processes in place to check if the API consumer is handling the d ata and API securely?

Indeed, mobile jumps out as a particular point of concern. Because mobile devices can be jail broken they can present a high-impact threat to APIs. However, 65 percent of respondents who were asked if they used mobile device management technology to protect API credentials to mitigate the risk of a jail broken device answered “Not Applicable.” I would imagine this will change with time… or we’ll see a lot more mobile breaches.

The Bottom Line

Arkana’s survey confirms that API security is still a nascent concern and it is still very early in the adoption lifecycle. The survey shows a wide range of responses to concerns about security and a diversity of security practices. It will be interesting to watch future editions of this survey if Arkana continues to publish it annually.

Visit the Arkana web site to download your own copy of the survey results.

JSON Scheme, DDoS, Message-Level security, Encryption were amongst the top API security threats.

Posted in DBA | 1 Comment

Optimizing Database Performance, part 2: Denormalization and Clustering

In Part 1 of our series introducing database performance topics and considerations we tackled the issues of partitioning data and creating indexes. In Part 2, today, we will introduce the topic of denormalization and clustering.

Denormalization

Another way to optimize the performance of database access is to denormalize the tables. So before we address denormalization, let’s first briefly talk about normalization.

Normalization is the process of putting each fact in the most appropriate place. A normalized database implementation minimizes integrity problems and optimizes updating (perhaps at the expense of retrieval). When a fact is stored in only one place, retrieving many different but related facts usually requires going to many different places. This can slow the retrieval process. Updating is quicker, however, because the fact you’re updating exists in only one place. A brief introduction to normalization and the normal forms can be found here.

Most applications require very rapid data retrieval. Some applications require specific tinkering to optimize performance at all costs. To accomplish this, sometimes the decision is made to denormalize the physical database implementation. Just as normalization is the process of assembling data in an organized manner to eliminate redundancies, denormalization is the process of deliberately introducing redundancy to your data. In other words, denormalization can be thought of as the process of putting one fact in numerous places. This can have the effect of speeding up the data retrieval process, usually at the expense of data modification.

So briefly defined, denormalization, the opposite of normalization, is the process of putting one fact in many places. Denormalizing tables can be a good decision when a completely normalized design does not perform optimally. The only reason to ever denormalize a relational database design is to enhance performance. 

So the basic rule of thumb is to never denormalize data unless a performance need arises or your knowledge of the way your DBMS operates overrides the benefits of a normalized implementation. Individual DBMS products may have specific deficiencies and inefficiencies that may necessitate denormalizing for performance reasons. You should always consider the following issues before denormalizing:

  • Can the system achieve acceptable performance without denormalizing?
  • Will the performance of the system after denormalizing still be unacceptable?
  • Will the system be less reliable due to denormalization?

If the answer to any of these questions is yes, you should avoid denormalization because the benefits typically will not exceed the cost. If, after considering these issues, you decide to denormalize, be sure to adhere to the general guidelines that follow.

If enough disk space is available, consider creating two sets of tables: one set fully normalized and another denormalized. Populate the denormalized versions by querying the data in the normalized tables and loading or inserting it into the denormalized tables. Your application can access the denormalized tables in a read-only fashion and achieve performance gains, while at the same time modifying the normalized version and avoiding integrity problems in the base data. However, it is important to set up a controlled and scheduled population function to synchronize the normalized table with the denormalized.

If sufficient disk space is not available for two complete sets of tables, implement only the denormalized tables and maintain them programmatically. Be sure to update each denormalized table representing the same entity at the same time, or use database triggers to keep the redundant data synchronized.

When a column is replicated in many different tables, always update it everywhere simultaneously—or as close to simultaneously as possible—given the physical constraints of your environment. Triggers can be helpful to accomplish this. If the denormalized tables are ever out of sync with the normalized tables, be sure to inform end users that batch reports and online queries may not contain completely up-to-date data; if at all possible, this should be avoided. And be sure to design the application so that it can easily be converted from using denormalized tables to using normalized tables.

Every denormalization decision should be documented, including the reason behind the decision and the exact changes made from the normalized logical data model. Such a record will help to ensure that future database changes are made with appropriate knowledge. Documentation will also make it clear that you didn’t simply make a design or implementation mistake.

Types of Denormalization

If you must denormalize, there are several options that you can consider:

  • Prejoined tables — when the cost of joining is prohibitive.
  • Report table — when specialized critical reports are too costly to generate.
  • Mirror table — when tables are required concurrently by two types of environments.
  • Split tables — when distinct groups use different parts of a table. The split could be row-wise or column-wise depending upon the needs of the accessing applications.
  • Combined tables — to consolidate one-to-one or one-to-many relationships into a single table.
  • Speed table — to support hierarchies like bill-of-materials or reporting structures.
  • Physical denormalization — to take advantage of specific DBMS characteristics.

You might also consider

  • Storing redundant data in tables to reduce the number of table joins required.
  • Storing repeating groups in a row to reduce I/O and possibly disk space.
  • Storing derivable data to eliminate calculations and costly algorithms.

Clustering

There are multiple meaning for the term clustering when it comes to database management systems. The clustering context that we will discuss here pertains to how data is stored on disk.

A clustered table will store its rows physically on disk in order by a specified column or columns. Clustering usually is enforced by the DBMS with a clustering index. The clustering index forces table rows to be stored in ascending order by the indexed columns. The left-to-right order of the columns as defined in the index, defines the collating sequence for the clustered index. There can be only one clustering sequence per table (because physically the data can be stored in only one sequence).

cluster

Figure 1. Clustered versus Unclustered Data

The figure above (Figure 1) demonstrates the difference between clustered and unclustered data and indexes; the clustered index is on top, the unclustered index is on the bottom. As you can see, the entries on the leaf pages of the top index are in sequential order — in o­her words, they are clustered. Clustering enhances the performance of queries that access data sequentially because fewer I/Os need to be issued to retrieve the same data.

Depending on the DBMS, the data may not always be physically maintained in exact clustering sequence. When a clustering sequence has been defined for a table, the DBMS will act in one of two ways to enforce clustering:

  1. When new rows are inserted, the DBMS will physically maneuver data rows and pages to fit the new rows into the defined clustering sequence; or
  2. When new rows are inserted, the DBMS will try to place the data into the defined clustering sequence, but if space is not available on the required page the data may be placed elsewhere.

The DBA must learn how the DBMS maintains clustering. If the DBMS operates as in the second scenario, data may become unclustered over time and require reorganization. A detailed discussion of database reorganization appears later in this chapter. For now, though, back to our discussion of clustering.

Clustering tables that are accessed sequentially is good practice. In other words, clustered indexes are good for supporting range access, whereas unclustered indexes are better for supporting random access. Be sure to choose the clustering columns wisely. Use clustered indexes for the following situations:

  • Join columns, to optimize SQL joins where multiple rows match for one or both tables participating in the join
  • Foreign key columns because they are frequently involved in joins and the DBMS accesses foreign key values during declarative referential integrity checking
  • Predicates in a WHERE clause
  • Range columns
  • Columns that do not change often (reduces physically reclustering)
  • Columns that are frequently grouped or sorted in SQL statements

In general, the clustering sequence that aids the performance of the most commonly accessed predicates should be used to for clustering. When a table has multiple candidates for clustering, weigh the cost of sorting against the performance gained by clustering for each candidate key. As a rule of thumb, though, if the DBMS supports clustering, it is usually a good practice to define a clustering index for each table that is created (unless the table is very small).

Clustering is generally not recommended for primary key columns because the primary key is, by definition, unique. However, if ranges of rows frequently are selected and ordered by primary key value, a clustering index may be beneficial.

Page Splitting

When the DBMS has to accommodate inserts, and no space exists, it must create a new page within the database to store the new data. The process of creating new pages to store inserted data is called page splitting. A DBMS can perform two types of page splitting: normal page splits andmonotonic page splits. Some DBMSs support both types of page splitting, while others support only one type. The DBA needs to know how the DBMS implements page splitting in order to optimize the database.

split

Figure 2. How a typical page split works

Figure 2 (above) depicts a normal page split. To accomplish this, the DBMS performs the following tasks in sequence:

  1. Creates a new empty page in between the full page and the next
    page
  2. Takes half of the entries from the full page and moves them to the empty page
  3. Adjusts any internal pointers to both pages and inserts the row accordingly

A monotonic page split is a much simpler process, requiring only two steps. The DBMS

  • Creates a new page in between the full page and the next page
  • Inserts the new values into the fresh page

Monotonic page splits are useful when rows are being inserted in strictly ascending sequence. Typically, a DBMS that supports monotonic page splits will invoke it when a new row is added to the end of a page and the last addition was also to the end of the page.

When ascending rows are inserted and normal page splitting is used, a lot of space can be wasted because the DBMS will be creating half-full pages that never fill up. If the wrong type of page split is performed during database processing, wasted space will ensue, requiring the database object to be reorganized for performance.

Summary

Understanding normalization, denormalization techniques and clustering will help you as a DBA or performance analyst to be able to deliver much better database performance for your clients and applications.

This series of blog posts is excerpted from Craig Mullins’ classic book Database administration: The complete guide to DBA practices and procedures. Consult the book for more in-depth information on any of these topics – and much, much more.

Posted in DBA | Tagged , , , , | 5 Comments

Optimizing Database Performance, Part 1: Partitioning and Indexing

Today’s post is the start of a three multi-part series offering up an overview of the most important components of database performance that must be monitored and managed for any database implementation.

Database performance focuses on tuning and optimizing the design, parameters, and physical construction of database objects, specifically tables and indexes, and the files in which their data is stored. The actual composition and structure of database objects must be monitored continually and changed accordingly if the database becomes inefficient. No amount of SQL tweaking or system tuning can optimize the performance of queries run against a poorly designed or disorganized database.

Techniques for Optimizing Databases

The DBA must be cognizant of the features of the DBMS in order to apply the proper techniques for optimizing the performance of database structures. Most of the major DBMSs support the following techniques although perhaps by different names. Each of the following techniques can be used to tune database performance and will be discussed in subsequent sections.

  • Partitioning — breaking a single database table into sections stored in multiple files.
  • Raw partitions versus file systems — choosing whether to store database data in an OS-controlled file or not.
  • Indexing — choosing the proper indexes and options to enable efficient queries.
  • Denormalization — varying from the logical design to achieve better query performance.
  • Clustering — enforcing the physical sequence of data on disk.
  • Interleaving data — combining data from multiple tables into a single, sequenced file.
  • Free space — leaving room for data growth.
  • Compression — algorithmically reducing storage requirements.
  • File placement and allocation — putting the right files in the right place.
  • Page size — using the proper page size for efficient data storage and I/O.
  • Reorganization — removing inefficiencies from the database by realigning and restructuring database objects.

Partitioning

A database table is a logical manifestation of a set of data that physically resides on computerized storage. One of the decisions that the DBA must make for every table is how to store that data. Each DBMS provides different mechanisms that accomplish the same thing — mapping physical files to database tables. The DBA must decide from among the following mapping options for each table:

  • Single table to a single file. This is, by far, the most common choice. The data in the file is formatted such that the DBMS understands the table structure and every row inserted into that table is stored in the same file. However, this setup is not necessarily the most efficient.
  • Single table to multiple files. This option is used most often for very large tables or tables requiring data to be physically separated at the storage level. Mapping to multiple files is accomplished by using partitioned tablespaces or by implementing segmented disk devices.
  • Multiple tables to a single file. This type of mapping is used for small tables such as lookup tables and code tables, and can be more efficient from a disk utilization perspective.

Partitioning helps to encourage parallelism. Parallelism is the process of using multiple tasks to access the database in parallel. A parallel request can be invoked to use multiple, simultaneous read engines for a single SQL statement. Parallelism is desirable because it can substantially reduce the elapsed time for database queries.

Multiple types of parallelism are based on the resources that can be invoked in parallel. For example, a single query can be broken down into multiple requests each utilizing a different CPU engine in parallel. In addition, parallelism can be improved by spreading the work across multiple database instances. Each DBMS offers different levels of support for parallel database queries. To optimize database performance, the DBA should be cognizant of the support offered in each DBMS being managed and exploit the parallel query capabilities.

Raw Partition vs. File System

For a UNIX-based DBMS environment, the DBA must choose between a raw partition and using the UNIX file system to store the data in the database. A raw partition is the preferred type of physical device for database storage because writes are cached by the operating system when a file system is utilized. When writes are buffered by the operating system, the DBMS does not know whether the data has been physically copied to disk or not. When the DBMS cache manager attempts to writes the data to disk, the operating system may delay the write until later because the data may still be in the file system cache. If a failure occurs, data in a database using the file system for storage may not be 100% recoverable. This is to be avoided.

If a raw partition is used instead, the data is written directly from the database cache to disk with no intermediate file system or operating system caching. When the DBMS cache manager writes the data to disk, it will physically be written to disk with no intervention. Additionally, when using a raw partition, the DBMS will ensure that enough space is available and write the allocation pages. When using a file system, the operating system will not preallocate space for database usage.

From a performance perspective, there really is no advantage to having a secondary layer of caching at the file system or operating system level; the DBMS cache is sufficient. Actually, the additional work required to cache the data a second time consumes resources, thereby negatively impacting the overall performance of database operations.

Indexing

Creating the correct indexes on tables in the database is perhaps the single greatest performance tuning technique that a DBA can perform. Indexes are used to enhance performance. Indexes are particularly useful for:

  • Locating rows by value(s) in column(s)
  • Making joins more efficient (when the index is defined on the join columns)
  • Correlating data across tables
  • Aggregating data
  • Sorting data to satisfy a query

Without indexes, all access to data in the database would have to be performed by scanning all available rows. Scans are very inefficient for very large tables.

Designing and creating indexes for database tables actually crosses the line between database performance tuning and application performance tuning. Indexes are database objects created by the DBA with database DDL. However, an index is built to make SQL statements in application programs run faster. Indexing as a tuning effort is applied to the database to make applications more efficient when the data access patterns of the application vary from what was anticipated when the database was designed.

Before tuning the database by creating new indexes, be sure to understand the impact of adding an index. The DBA should have an understanding of the access patterns of the table on which the index will be built. Useful information includes the percentage of queries that access rather than update the table, the performance thresholds set within any service level agreements for queries on the table, and the impact of adding a new index to running database utilities such as loads, reorganizations, and recovery.

One of the big unanswered questions of database design is: “How many indexes should be created for a single table?” There is no set answer to this question. The DBA will need to use his expertise to determine the proper number of indexes for each table such that database queries are optimized and the performance of database inserts, updates, and deletes does not degrade. Determining the proper number of indexes for each table requires in-depth analysis of the database and the applications that access the database.

The general goal of index analysis is to use less I/O to the database to satisfy the queries made against the table. Of course, an index can help some queries and hinder others. Therefore, the DBA must assess the impact of adding an index to all applications and not just tune single queries in a vacuum. This can be an arduous but rewarding task.

An index affects performance positively when fewer I/Os are used to return results to a query. Conversely, an index negatively impacts performance when data is updated and the indexes have to be changed as well. An effective indexing strategy seeks to provide the greatest reduction in I/O with an acceptable level of effort to keep the indexes updated.

Some applications have troublesome queries that require significant tuning to achieve satisfactory performance. Creating an index to support a single query is acceptable if that query is important enough in terms of ROI to the business (or if it is run by your boss or the CEO). If the query is run infrequently, consider creating the index before the process begins and dropping the index when the process is complete.

Whenever you create new indexes, be sure to thoroughly test the performance of the queries it supports. Additionally, be sure to test database modification statements to gauge the additional overhead of updating the new indexes. Review the CPU time, elapsed time, and I/O requirements to assure that the indexes help. Keep in mind that tuning is an iterative process, and it may take time and several index tweaks to determine the impact of a change. There are no hard and fast rules for index creation. Experiment with different index combinations and measure the results.

When to Avoid Indexing

There are a few scenarios where indexing may not be a good idea. When tables are very small, say less than ten pages, consider avoiding indexes. Indexed access to a small table can be less efficient than simply scanning all of the rows because reading the index adds I/O requests.

Index I/O notwithstanding, even a small table can sometimes benefit from being indexed — for example, to enforce uniqueness or if most data access retrieves a single row using the primary key.

You may want to avoid indexing variable-length columns if the DBMS in question expands the variable column to the maximum length within the index. Such expansion can cause indexes to consume an inordinate amount of disk space and might be inefficient. However, if variable-length columns are used in SQL WHERE clauses, the cost of disk storage must be compared to the cost of scanning. Buying some extra disk storage is usually cheaper than wasting CPU resources to scan rows. Furthermore, the SQL query might contain alternate predicates that could be indexed instead of the variable-length columns.

Additionally, avoid indexing any table that is always accessed using a scan, that is, the SQL issued against the table never supplies a WHERE clause.

Index Overloading

Query performance can be enhanced in certain situations by overloading an index with additional columns. Indexes are typically based on the WHERE clauses of SQL SELECT statements. For example, consider the following SQL statement.

select emp_no, last_name, salary
from employee
where salary > 15000.00
;

Creating an index on the salary column can enhance the performance of this query. However, the DBA can further enhance the performance of the query by overloading the index with the emp_no and last_name columns, as well. With an overloaded index, the DBMS can satisfy the query by using only the index. The DBMS need not incur the additional I/O of accessing the table data, since every piece of data that is required by the query exists in the overloaded index.

DBAs should consider overloading indexes to encourage index-only access when multiple queries can benefit from the index or when individual queries are very important.

Be sure to stay tuned for the next installment of this series on database performance, which will cover denormalization and clustering.

Posted in DBA | Tagged , | 5 Comments

You Can’t Force Data Quality

How many times have you surfed the Web only to encounter a form that requests a slew of personal information before you are permitted to go any further? You know what I’m talking about. A company markets a white paper or poll results or something else that intrigues you, so you click on the link, and bang, there you are. You don’t have the information you wanted yet, but if you just fill out this form then you will be redirected to the information.

Makes you want to scream, doesn’t it? Some folks just close their browser or move on to something else. Some folks enter partially accurate information to see how little they need to provide without getting rejected. And some folks just provide bogus information.

Now sometimes completely bogus information won’t work. Maybe the form requires an email address to which the information will be sent. But hey, that’s what Gmail and Yahoo Mail were made for, right? Just create a new address, fill in the form using it, collect the information, then shut down, or ignore that email account for the rest of your life.

Of course, if you’re trying to sign up for a webinar this might not work because many companies remove generic email addresses. Who can blame them? They’re conducting a webinar to drum up business and gather leads. If you provide a generic email address the organizer will assume that you aren’t a good lead or maybe even a competitor trying to gather intelligence.

Then there’s the phone number. I almost never supply an accurate phone number. If the form allows, I type in “do not call me” as my phone number. The better web sites will not permit characters in a phone number though. So then I am forced to use the information number, 555-1212 (with my area code) or another bogus number. I get more than enough cold calls for things I don’t need already, thank you.

The point I’m trying to make is that these marketing tactics are responsible for the creation of a lot of bad quality data. But at least some of the data must be useful or the marketers wouldn’t use these tactics. And who can fault marketers for actually trying to target prospective customers? After all, that’s their job. And the information was evidently interesting enough to get you to click to it, right?

So what’s my point? Well, I have a couple of them. The first is that these Web forms need to be more stringently developed. For example, you should never be able to type characters into a phone number field. I’m talking about basic edit checks that every programmer should have been taught to do in Coding 101.

You also can check for and reject commonly submitted bogus items. For example, Mickey Mouse will never be your customer. And an address of 1313 Mockingbird Lane may be good for the Munsters, but not your customers. And while you’re at it, any phone number with a 555 prefix can be summarily rejected, too.

If you’re really interested in accurate data, take the time to do some more robust edit checking. Do the area code and zip code entered actually exist? Do they match the city and state that was entered? For example, if someone enters the 512 area code (Austin, TX) but enters Pittsburgh, PA for the city and state, you know the data is bogus. Or at least suspect … after all, people do move and take their mobile phone number with them. I have a friend who moved from Chicago to Florida to New York to Texas and he still has a mobile phone with Chicago’s 630 area code.

And if you want to go even further, you can match up company names to known addresses for that company to verify that an actual, accurate company name is being provided. Of course, there are exceptions here, too. Maybe you work from a home office and you’ve provided a legitimate address.

The bottom line is that organizations can do better at verifying data in their customer-facing Web applications. But even then, you just can’t force data quality. There will still be people “out there” (like me) who find ways to enter good enough data to prevent someone emailing them or calling them, trying to sell them something all the time.

And the data quality fight continues …

Posted in Data Quality | 1 Comment

A Few Database/DBMS Definitions

Just a quick post today to inform my readers of several technical definitions that I have written for TechTarget’s WhatIs? site. If you are not familiar with that site, click on the link and investigate it. It is a great way to hunt around and educate yourself on terms that may not be familiar to you.

Anyway, lately I’ve been working with the site to help develop some of their definitions in the data and database management realm. Here are a few of the ones I’ve participated in developing:

Of course, there are many other data and database-related definition up on WhatIs?, as well as tons of other IT definitions. Be sure to check it out if you haven’t already done so!

Posted in DBA | Tagged , , , , , | 1 Comment

The Surprising Things You Don’t Know About Big Data

 

I found this infographic to be informative and entertaining, so I’m sharing it here for the readers of my blog. Let me know what you think… should I post more things like this in the future?

The Surprising Things You DonYou can also find more infographics at Visualistan

Posted in Big Data, Data Growth | 1 Comment

Programmer Makes Excuses, Too!

In our last post (DBA Excuses… and advice to programmers for overcoming them!) we examined some of the bigger excuses used by DBAs to avoid problems and work. But poor excuses are not the exclusive domain of the DBA; far from it! Application developers and programmers rely on their fair share of excuses, too. And if you’re a DBA you’ve probably heard most of them. Let’s break down the top few programmer excuses and see what can be done to avoid them in the future.

The number one programmer excuse is to blame the DBMS.  If you’re a programmer, chances are high that you’ve either said something like the following (or at least thought it): “There’s something wrong with DB2 (or Oracle, or insert your favorite DBMS here)!” The basic mentality is that the DBMS is guilty until proven innocent; the programmer will never run up to the DBA and say “there’s a problem with this horrible code I wrote, can you help me fix it?”

Blaming the DBMS is never a helpful strategy. Oh, yes, in some rare instances there will be a problem or bug in the DBMS itself, but those instances are very rare. Most “database problems” can be tracked back to programming problems. By keeping this in mind at all times everyone will be better off – the problem will get fixed sooner and you will not alienate your DBAs by constantly blaming the DBMS.

Another common excuse is known as the Copied Code Syndrome. As most programmers know, copying working code from one program to another is an efficient way of quickly developing programs. But with database development you have to be careful to make sure that what you copy is really what you need. Here’s how this excuse works: when the programmer is confronted with a problem in his program he simply says “That can’t be a problem because I copied from another program and that program works.”  Well, that may be true, but many things can go wrong with copied SQL. Maybe you copied something that is 95% what you need, but you didn’t modify the code for your purposes. Or maybe something is different about the rest of the code in your program that makes the copied code in effective. Or maybe you aren’t totally sure of what each and every statement and parameter that you copied does?

A corollary to the Copied Code Syndrome is the It worked yesterday excuse. But today is another day, and if it ain’t working today, it ain’t working. Many things can change from day-to-day that can cause working code to become problematic – not the least of which is that code itself. Programmers make so many changes to code as a requirement of their job that sometimes you can just forget that something did indeed change. The bottom line is to work on solutions to problems instead of excuses to deflect blame. Blame is counter-productive to resolving problems.

Yet another excuse bandied about by developers is the Better Mousetrap excuse. The best approach to developing programs using a relational database is to put as much work as possible into the SQL and let the DBMS optimize the access. But there is always that Wile E. Coyote developer who says “But I can do that better in C or Java (or insert your favorite programming language here).” Doing it in SQL puts the work on the DBMS – and there is a much better chance for the DBMS to be bug-free than whatever code you cobble together.

The final programmer excuse I’ll mention today is the Time Is Running Out excuse. This can best be summarized as “There is always time to do it over later, but never enough time to do it right the first time.” Usually this excuse comes to light when you hear that magic phrase “It’s too late in the project to re-write that.”  But the problem caused by the code continues to exist – the programmer just wants some magic to occur to fix it that does not require coding changes. Won’t happen! There is no magic button out there! Sometimes the code has to change to solve the problem.

In the end, the biggest thing you can do as an application programmer is to research and understand any issue before you go running to the DBA.  If your program fails, find the SQLCODE (or SQLSTATE) and any associated reason code and try to fix it yourself first.  If you don’t understand something, read the manual before going to the DBA. There is no reason why everyone shouldn’t have their own set of manuals; most of them can be downloaded for free from the DBMS vendor’s web site.

To conclude, if I had a nickel for every time someone tried to use one of these excuses on me, I’d be a wealthy man. But life does not work that way. So maybe we can all climb back into the trenches and vow to avoid using all of these excuses — both DBAs and programmers… it’ll makes working with your databases a lot easier!

Posted in DBA, SQL | 1 Comment