1. Complete and up-to-date Statistics

Teradata SQL Tuning begins by providing the optimizer with the statistics it needs. This must always be done as a first step. Statistics influence the execution plan. It is not only important to define all required statistics, but also to keep them as up-to-date as possible. There is a simple reason why I put statistics first: Often performance problems are solved simply by changing the execution plan. Which columns require which type of statistics (full statistics collecting, random-AMP sampling or sample statistics) depends primarily on the data demography.

Random-AMP sampling

Random AMP sampling is usually sufficient for columns with many different values. The table should contain significantly more rows than there are AMPs in the system.

The following applies to random-AMP sampling: The more distinct the column values are, the better the estimate will be. If the column values are skewed, there is a risk that the random-AMP sample will be taken from an AMP that is not representative of the data. Skewed data leads to overestimation or underestimation of the number of rows. Good candidates for Random-AMP sampling are unique indices, i.e., UPI and USI. Random-AMP sampling only takes place on indexed columns. Therefore, You should always collect statistics on non-indexed columns that are used in WHERE conditions. Whether full or sample statistics are collected depends on how unique the column values are.

Fully collected Statistics

Fully collected statistics are required for skewed column values and columns with a small number of distinct values (NUPI and NUSI).

Statistics for Row-Partitioned Tables

The Teradata Optimizer has unique statistic requirements for PPI tables. The following statistics should additionally be collected on PPI tables: Dummy Column “PARTITION” Statistics on dummy column “PARTITION” tell the optimizer the number of the empty statistics. Dummy column “PARTITION” + PI column These statistics are required if the partitioning columns are not part of the primary index. In this case, the same primary index value can exist in different partitions. Statistics on dummy column “PARTITION” + PI allow the optimizer to estimate the cost of the sliding window and rowkey based merge join and of dynamic partition elimination steps. Below statement can be used to determine which statistics the optimizer would additionally need in a SQL statement:

DIAGNOSIS HELPSTATS ON FOR SESSION;

This statement displays a list of suggested statistics at the end of the Execution Plan (given by the EXPLAIN statement) and the Optimizer's opinion of their value (confidence levels). By gradually adding these statistics, you can test their influence on the execution plan.

Identify Stale Statistics

There are several ways to identify stale statistics. The easiest way is to split the SQL statement and test each partial statement individually. Splitting is done merely by comparing the estimated number of rows (as shown in the Explain output) with the actual number of records returned by the query. The above-described approach is particularly suitable if the entire SQL statement does not execute in a reasonable time. Here's an example:

SELECT t01.*

FROM <Tablename1> t01

INNER JOIN

<Tablename2> t02

ON t01.PK = t02.PK

WHERE

t01.<Column name> = 1 AND t02.<Column name> = 2;



The above query can be divided into two parts for testing:



SELECT * FROM <Tablename1> WHERE <Columnnname> = 1;

SELECT * FROM <Tablename2> WHERE <Columnnname> = 2;

If you execute both sub-queries, and the number of rows returned differs significantly from the estimate in EXPLAIN, the statistics may be obsolete.

2. Teradata Primary Index Choice

Teradata SQL Tuning is not complete without choosing the best possible Primary Index. Design your queries so that the primary index can be used in the joins. All join columns must be part of the primary index. If only one column of the primary index is missing in the join condition, the result is a different row hash (the order how they are defined in the primary index doesn't matter) Still, the join condition can contain additional columns. These are then applied as residual conditions after locating the rows via row hash. To execute a join between two tables, the rows of both tables must be co-located on the same AMP. This is true when they have the same primary index. In this case, the optimizer can use a join strategy that requires no redistribution of rows a so-called "direct join". If for some reason you cannot change the primary indexes, or if you need a specific primary index for a particular SQL statement, create a volatile table (or a true temporary table) with the same structure and content as the original table but with a different primary index. There are three things to consider when selecting the Primary Index: uniform distribution of data, good suitability for join operations, and low volatility:

This is the only way to ensure that all AMPs start and finish their work simultaneously. This is exactly what parallel data processing is all about.

3. Teradata SQL Tuning with Indexing & Partitioning Using indexes or partitioning is another way to improve query performance. Teradata offers a number of different indexes, all of which have their advantages and disadvantages. Which index should be used when depends mainly on the workload.

The Teradata Secondary Index

Secondary indexes come in two forms. As unique secondary index (USI) and as non-unique secondary index (NUSI). Although one could conclude from the name that these differ only in the uniqueness, their functionality is very different.



The Teradata USI The USI is very similar to the Unique Primary Index:

The Index Rows of the Index subtable are distributed evenly over all AMPS by Rowhash and sorted by RowHash. If the USI contains at least all columns used in a WHERE condition, the AMP can be determined which owns the index row (in this case the index row).



The determined index row contains the ROWID of the base table row that is being searched for, and this can then be used to access the desired row.



The USI is suitable for direct access to individual rows and is therefore high-performance. It is ideal for tactical workload where this feature is required. The Teradata NUSI The NUSI is not distributed according to a Rowhash. NUSI rows are always held together with the AMP that has the corresponding row of the base table. Therefore a NUSI access is always an all-AMP operation. The NUSI index rows are sorted by rowhash or by an integer value. Sorting by an integer value (date is internally of data type integer, and therefore also possible) is one of the advantages of the NUSI, as this makes it ideal for range scans (e.g. all days of a certain month).

The Teradata Row-Partitioned Table

While secondary indexes in Teradata are stored in a sub-table and therefore require extra space, partitioning is just another way to structure the rows on the mass storage device. The rows of a partitioned table are not only distributed to the AMPs according to rowhash, but are also assigned to the appropriate partitions and inside the partitions sorted according to rowhash.



The rows of a partition are arranged on the disk in such a way that a full cylinder scan can be performed. When you should partition a table, and when the use of a secondary index or join index is more appropriate, depends on the workload. It is also possible to create additional indexes on a partitioned table. Partitioned tables are often used for strategic queries in which a series of data (for example, the sales for the current year) is aggregated.

Disadvantages of Indexing & Partitioning

When we work with indexing techniques, we need to keep an eye on the entire data warehouse architecture and decide whether our solution fits. Indexes can have a negative impact on the ETL process for several reasons. Loading tools such as Fastload require secondary indexes and join indexes to be removed before loading. The index sub-tables have to be managed by Teradata. Insert, Delete and Update statements require that in addition to the actual table, the index sub-table must be maintained. If potentially useful indexes are not used by the optimizer and they are not helpful in the entire PDM design, drop them immediately. You're wasting space and resources.

4. Query Rewriting

The performance of a query can often be improved by rewriting the query. Personally, I prefer to consider an SQL statement as a black box and to limit optimizations to technical methods first. Here are a few examples: EXISTS instead of IN

Splitting a large SQL statement into smaller parts

UNION ALL instead of UNION

DISTINCT instead of GROUP BY Not having to understand the content and business logic of a query, I do not need to contact the author of the query. The purely technical optimizations are usually not that risky. Only when I reach the limits of purely technical optimization do I begin to deal with business logic. Understanding business logic often opens up additional optimization opportunities. Rewriting of queries often solves performance problems, even when all other techniques have failed.

5. Teradata SQL Tuning with Real-Time Monitoring

Teradata SQL tuning requires to watch the query running in real-time. Monitoring a query in viewpoint at runtime helps to identify the critical steps. In Viewpoint you should look for the following steps: Steps that take a long time to finish and consume a huge amount of resources.

Steps that are skewed, especially if the skew factor reaches 99%, as this means that all work is done by only one AMP or a few AMPs.

Analyzing the bad query

We have to think about the root cause of the bad query step, here are a few ideas: Does the base table have a skewed primary index (static skew)?

Does the redistribution of rows cause skew (dynamic skew)?

Are massive amounts of data redistributed because of poor join preparation due to missing or stale statistics?

Are there several hash collisions during the execution of the INSERT statement? Stale and missing statistics typically lead to incorrect decisions in join preparation (copying a table to all AMPs instead of rehashing) and to the use of incorrect join methods (for example, product join instead of merge join).

6. Comparison of Resource Usage

Another important task in Teradata SQL Tuning is measuring resource consumption before and after the optimization of the query. Query run times are misleading because they can be affected by the simultaneous workload of other queries over which we have no control. In performance tuning, we prefer to use absolute key figures that are independent of what else is running on our Teradata system. Below is a query that gives you a detailed insight into how good each step of the SQL statement to be optimized is. To execute this query, you must have read access to table DBC.DBQLOGTBL (or related views): Do not forget to give each version of the query to be optimized its own query band so that you can uniquely identify it in the table DBC.DBQLOGTBL:

SET QUERY_BAND = 'Version=1;' FOR SESSION;

SELECT

AMPCPUTIME,

(FIRSTRESPTIME-STARTTIME DAY(2) TO SECOND(6)) RUNTIME,

SPOOLUSAGE/1024**3 AS SPOOL_IN_GB,

CAST(100-((AMPCPUTIME/(HASHAMP()+1))*100/

NULLIFZERO(MAXAMPCPUTIME)) AS INTEGER) AS CPU_SKEW,

MAXAMPCPUTIME*(HASHAMP()+1) AS CPU_IMPACT,

AMPCPUTIME*1000/NULLIFZERO(TOTALIOCOUNT) AS LHR

FROM

DBC.DBQLOGTBL

WHERE

QUERYBAND = 'Version=1;' ;