Search This Blog

Monday, May 20, 2013

Teradata Data Distribution - Primary Index

Teradata Data Distribution 

There are three keys to how Teradata spreads the data among the AMPs. They are Primary Index, Primary Index, and Primary Index

The Primary Index
Teradata takes each table and spreads the table rows across the AMPs. When the table needs to be read, each AMP has to read only their portion of the table. If the AMPs start reading at the same time and there are an equal amount of rows on each AMP, then parallel processing works brilliantly. Alone an AMP can do so little, but the AMPs working together can accomplish the incredible. This brilliant feat begins with the Primary Index.
Each table in Teradata is required to have a Primary Index. The biggest key to a great Teradata Database Design begins with choosing the correct Primary Index. The Primary Index will determine on which AMP a row will reside. Because this concept is extremely important, let me state again that the Primary Index is the only thing that will determine on which AMP a row will reside.
Many people new to Teradata assume that the most important concept concerning the Primary Index is data distribution. INCORRECT! The Primary Index does determine data distribution, but even more importantly the Primary Index provides the fastest physical path to retrieving data. The Primary Index also plays an incredibly important role in how joins are performed. Remember these three important concepts of the Primary Index and you are well on your way to a great Physical Database Design.
The Primary Index plays 3 roles:
·       Data Distribution
·       Fastest Way to Retrieve Data
·       Incredibly important for Joins

The Two Types of Primary Indexes

Every table must have at least one column as the Primary Index. The Primary Index is defined when the table is created. There are only two types of Primary Indexes, which are a Unique Primary Index (UPI) or a Non-Unique Primary Index (NUPI).

Unique Primary Index (UPI)

A Unique Primary Index means that the values for the selected column must be unique. If you try and insert a row with a Primary Index value that is already in the table, the row will be rejected. A Unique Primary Index will always spread the table rows evenly amongst the AMPs. Please don’t assume this is always the best thing to do. Below is a table that has a Unique Primary Index. We have selected EMP to be our Primary Index. Because we have designated EMP to be a Unique Primary Index then there can be no duplicate employee numbers in the table.


                      Employee Table
EMP DEPT LNAME FNAME SAL
UPI
1 100 JOHN CHRIS 10000
2 200 JOHN JACK 13000
3 300 LICE ANN 12000
4 300 BROWN MARY 30000

A Unique Primary Index (UPI) will always spread the rows of the table evenly amongst the AMPs.
Don’t assume this is always the best choice!

Non-Unique Primary Index

A Non-Unique Primary Index (NUPI) means that the values for the selected column can be non-unique. You can have billions of the same values in the Primary Index. A Non-Unique Primary Index will almost never spread the table rows evenly. Please don’t assume this is always a bad thing. Below is a table that has a Non-Unique Primary Index. We have selected LNAME to be our Primary Index. Because we have designated LNAME to be a Non-Unique Primary Index we are anticipating that there will be individuals in the table with the same last name.

 Employee Table
EMP  DEPT LNAME FNAME SAL
NUPI
1 100 JOHN CHRIS 10000
2 200 JOHN JACK 13000
3 300 LICE ANN 12000
4 300 BROWN MARY 30000

A Non-Unique Primary Index (UPI) will almost NEVER spread the rows of the table evenly amongst the AMPs.
Don’t assume this is a bad thing!

How Teradata Turns the Primary Index Value into the Row Hash

The Primary Index is the only thing that determines where a row will reside. It is important that you understand this process. Here are the fundamentals in the simplest form. When a new row arrives into Teradata then:
Teradata examines the Primary Index value for the row.
Teradata takes that Primary Index value and runs it through a Hashing Formula.
The output of the Hashing Algorithm (a.k.a., Formula) is a 32-bit Row Hash.
The 32-bit Row Hash will perform two functions:
1. The 32-bit Row Hash will point to a certain spot on the Hash Map, which will indicate which AMP will hold the row.
2. The 32-bit Row Hash will always remain with the Row as part of a Row Identifier (Row ID).
Hashing is a mathematical process where an Index (UPI, NUPI) is converted into a 32-bit row hash value. The key to this hashing algorithm is the Primary Index. When this value is determined, the output of this 32-bit value is called the Row Hash.
A new row is going to be inserted into Teradata. The Primary Index is the column called EMP. The value in EMP for this row is 99. Teradata runs the value of 99 through the Hash Formula and the output is a 32-bit Row Hash. In his example our 32-bit Row Hash output: 00001111000011110000111100001111.

The Row Hash Value determines the Rows Destination

The first 16 bits of the Row Hash (a.k.a., Destination Selection Word) is used to locate an entry in the Hash Map. This entry is called a Hash Map Bucket. The only thing that resides inside a Hash Map Bucket is the AMP number where the row will reside.
The first 16 bits of the Row Hash of 00001111000011110000111100001111 is used to locate a bucket in the Hash Map. A bucket will contain an AMP number. We now know that employee 99 whose row hash is 00001111000011110000111100001111 will reside on AMP 4. Note: The AMP uses the entire 32 bits in storing and accessing the row.
If we took employee 99 and ran it through the hash formula again and again, we would always get a row hash of 00001111000011110000111100001111.
If we take the row hash of 00001111000011110000111100001111 again and again, it would always point to the same bucket in the hash map.

Every time employee 99 is run through the hash formula it returns the same Row Hash. That Row Hash will point to the same Hash Bucket every time. That is how Teradata knows which AMP will hold row 99. It does the math and it always gets what it always got!
The Row is Delivered to the Proper AMP
Now that we know that Employee 99 is to be delivered to AMP 4(For ex), Teradata packs up the row, places the Row Hash on the front of the row, and delivers it to AMP 4.
REVIEW:
·       A row is to be inserted into a Teradata table
·       The Primary Index Value for the Row is put into the Hash Algorithm
·       The output is a 32-bit Row Hash
·       The Row Hash points to a bucket in the Hash Map
·       The bucket points to a specific AMP
·       The row along with the Row Hash are delivered to that AMP

The AMP will add a Uniqueness Value

When the AMP receives a row it will place the row into the proper table, and the AMP checks if it has any other rows in the table with the same row hash. If this is the first row with this particular row hash the AMP will assign a 32-bit uniqueness value of 1. If this is the second row hash with that particular row hash, the AMP will assign a uniqueness value of 2. The 32-bit row hash and the 32-bit uniqueness value make up the 64-bit Row ID. The Row ID is how tables are sorted on an AMP.

How Teradata Retrieves Rows

In the example below a user runs a query looking for information on Employee 99. The PE sees that the Primary Index Value EMP is used in the SQL WHERE clause. Because this is a Primary Index access operation, the PE knows this is a one AMP operation. The PE hashes 99 and the Row Hash is 00001111000011110000111100001111. This points to a bucket in the Hash Map that represents AMP 4. AMP 4 is sent a message to get the Row Hash: 00001111000011110000111100001111 and make sure it’s EMP 99.









Teradata Data Placement


Teradata Data Placement 

Because Teradata was built for large data warehouses, its architects knew that data placement and management of tables could be a full time job. That is why they designed Teradata to automatically manage the data. Nobody had ever attempted this incredible feat. The Teradata designers dreamed of things that never were and made them so.
Managing table space, disks, and other system administration functions in a data warehouse is a nightmare. Teradata has made the DBA’s role a dream because Teradata lets the system handle the difficult functions. Teradata not only spreads the data evenly, but it can retrieve it quickly because it knows which AMP holds a particular row.
Teradata always attempts to spread data evenly so each AMP will manage approximately the same amount of data. As a result, the rows of every table are distributed across all of the AMPs. In other words, every AMP stores a portion of every table in the database on its virtual disk (VDISK). If a data warehouse has 200 tables, then each AMP will hold a portion the 200 tables. This method of data distribution is unique only to Teradata.
There are some significant benefits to handling data this way: First, the biggest bottleneck in any system is the disk. Because each AMP has their own virtual disk and each table is spread among the AMPs, there is no disk bottleneck.
Second, when each AMP has nearly the same quantity of table rows, then no one AMP becomes a data bottleneck. AMPs can retrieve all or a portion of the data in parallel so you do not have AMPs sitting idle while others are chugging away. Baseball superstar Casey Stengel once said, “It’s easy to get good players. Getting’ em to play together, that’s the hard part.” AMPs love to work together in parallel.
Third, each AMP is unaware of any data except its own portion. Each AMP can ONLY read or write to a particular row of data that the AMP actually owns. This makes retrieving data from a particular row very efficient as all AMPs focus on their own work. Fourth, each AMP automatically groups all of its rows by the tables from which they come. Have you ever been to a large aquarium and seen one of the displays that look like a very tall, clear cylinder? As you walk around the glass, the fish tend to swim in schools. Similarly, Teradata does this with the rows on the AMPs to boost performance. When you ask for data from any given table, an AMP will immediately go to that particular group of rows, and then select what you need. It doesn’t need to look through the rows of many tables before it finds what you need. This is how parallel processing works. The AMPs retrieve data in parallel and then pass it over the BYNET to the PE. The PE ensures the data is delivered to the user. Keep in mind the BYNET is an internal Teradata network, across which the PEs and the AMPs communicate.

The example below shows the information we have just discussed. Notice that the system has four AMPs, and three tables: “Employee,” “WebLog,” and “Order.” Notice each AMP holds a portion of the rows for every table. AMP1, for example, holds 1/4th of the Employee table rows, 1/4th of the WebLog table rows, and 1/4th of the Order table rows.


Plus, the data is spread evenly across for all tables. If a query asks for all rows in the employee table, then each AMP will retrieve their employee table rows in parallel. Each AMP will then pass its data to the PE via the BYNET. Because the data in the employee table is spread evenly among all AMPs, each should finish reading at exactly the same time.
Also, notice how each AMP separates each table. Just like schools of fish, the rows of the Employee table are grouped together. In addition, the WebLog and Order tables are grouped together. This is important key in a data warehouse environment because most queries read millions of rows to satisfy a single query. Performance is enhanced when table rows are grouped together and Teradata is permitted to bring blocks of rows into memory.

Teradata Components

Teradata Components


There are three main components in Teradata which does all wonder to the world of Database.
  1. Parsing Engine
  1. AMP (Access Module Processor)
  1. Bynet 


Parsing Engine (PE)
The Teradata Parsing Engine (PE) is the hero in the world of database optimization. Most databases make educated guesses about the best way to retrieve data. Teradata has such a great reputation and experience for speeding up data access that it has earned the name “The OPTIMIZER.” Because Teradata knows how to retrieve data quickly it gives users the confidence to believe in the data warehouse. As users gain experience they begin to believe in themselves.
When you logon to Teradata, they connect to a Parsing Engine (PE). When a user submits a query, then the PE takes action. The PE creates a PLAN that tells the AMPs exactly what to do in order to get the data. The PE knows how many AMPs are in the system, how many rows are in the table, and the best way to get to the data. The PE enjoys serving valid Teradata users, but it was raised like a guard dog. A good guard dog loves its family, but it barks and may bite when strangers approach. The PE will always check a user’s security (access) rights to ensure they have the proper authority to obtain the information that is being requested. If the user has authority, the PE instructs the AMPs to get the data. If the user doesn’t have proper access rights, the query is rejected.
The PE doesn’t like to brag, but it did graduate at the top of its class. This has given the PE years of experience in guiding the AMPs to answer complex questions – some of which have never been asked before in their respective industries. This experience allows users to ask any question regardless of its complexity. The PE isn’t called “The Optimizer” for nothing. It needs no tuning by a Database Administrator (DBA) or hints from the user. Teradata users ask the questions, and Teradata simply returns the answers.

Access Module Processor (AMP)

The Access Module Processor (AMP) is a component of little words. It keeps its mouth shut and its ears open. Each AMP listens to the PE via the BYNET for instructions. The AMPs primary responsibilities consist of retrieving and writing data to its disk. The AMP is the worker bee of the system. It is the perfect employee. It never complains, rarely calls in sick, and lives to take direction from its boss who is the Parsing Engine (PE). The AMPs work together like many hands to make the work light.
Every AMP has its own disk, and it’s the only AMP allowed to read or write data to that disk. This method of processing is referred to as a “Shared-Nothing” architecture. Although AMPs are the perfect workers, they are not the perfect playmates. Even as children AMPs would never share toys with other AMPs on the playground. Each AMP has its own disk, and it shares this with no other AMP, hence a “Shared-Nothing” architecture.
Teradata spreads the rows of a table evenly across all AMPs in the system. When the PE asks the AMPs to get the data, each AMP will read the rows only on their particular disk. If this is done simultaneously, all AMPs should finish at about the same time. As a matter of fact, when we explained this philosophy to Confucius he stated, “A query is only as fast as the slowest AMP.” Confucius, however, did say not to quote him!
Again, an AMPs job is to read and write data to its disk. The AMP takes its direction from the Parsing Engine (PE). The number of AMPs varies per system. 

The BYNET


The BYNET ensures communication between AMPs and PEs. When fast communication is necessary, the BYNET operates as a communications superhighway. There are no traffic jams on the BYNET because its designers went the extra mile. The BYNET makes sure that communication between AMPs and PEs are always on the right track and that it happens rapidly. The BYNET has been designed for speed, reliability, and throughput.
There are actually two BYNETs per system. They are called “BYNET 0” and “BYNET 1”. The two BYNETs are usually referred to as just the BYNET. The reasons two BYNETs exist on a Teradata system is because of the following:
1. Redundancy: If one BYNET fails, the second BYNET takes over.
2. Performance: Think of the two BYNETs as telephone lines in your home. AMPs and PE’s can talk to one another on one or over both BYNETs.
Here are the steps that outline exactly how the AMPs, PEs, and BYNET work together: A user performs a LOGON to Teradata. A PE is assigned to manage all SQL requests for that particular user. When a user queries Teradata, the following occurs: The PE checks the user’s SQL Syntax;
·       The PE checks the user’s security rights;
·       The PE comes up with a plan for the AMPs to follow;
·       The PE passes the plan along to the AMPs over the BYNET;
·       The AMPs follow the plan and retrieve the data requested;
·       The AMPs pass the data to the PE over the BYNET; and
·       The PE then passes the final data to the user.
The BYNET provides the communications between AMPs and PEs – so no matter how large the data warehouse physically gets, the BYNET makes each AMP and PE think that they are right next to one another. The BYNET gets its name from the Banyan tree. The Banyan tree has the ability to continually plant new roots to grow forever. In addition, Banyan trees have been found that are a mile wide. The BANYON network or BYNET has the ability to continually grow. The BYNET is installed at the largest data warehouse sites in the world and the DBA’s smiles that are a mile wide.



Wednesday, May 15, 2013

Teradata Spaces - Perm , Spool, Temp - Understanding



Space in Teradata

In order to better manage the space and queries, it is important to understand the concepts of space management in Teradata which will enable one to write optimized queries.

A user or database is assigned two types of space. They are Permanent Space and Spool Space. PERM space is used to store tables and SPOOL space is for users to run their queries. If your query exceeds your allocated Spool space you will need a second chance because your query is immediately aborted.
This paragraph is vital in understanding space on Teradata so pay attention.

Lets say you give a user or database 4 Gigabytes of PERM space to hold tables. Space is always divided equally over the number of AMPs to ensure reasonable data distribution. Assume we have a 2 AMP system and the user was given 4 Gigabytes then each AMP is assigned 2 Gigabytes of PERM space for the users tables. If uneven distribution occurs then your table will stop loading because you are out of space. The same theory goes with SPOOL space. If you are given 2 Gigabytes of Spool Space then your queries can grow until they reach 2 Gigabytes, but remember that space is equally divided over the number of AMPs.

Once again since there are 2 AMPs (picture below) in the system your query cannot exceed 1 Gigabyte per AMP. If you have what is called a “Hot AMP” where more data is stored is on one AMP versus the others you can run out of space prematurely. Permanent Space is where objects (i.e., databases, users, tables) are created and stored. Permanent Space is released when data is deleted or when objects are dropped.

Spool Space is PERM space on the system that has not been allocated. The Primary reason for SPOOL space is to be available to store intermediate results or queries that are being processed in Teradata. Spool Space is released when the query is over or when the query no longer needs it.

Volatile Tables consume Spool Space and Permanent Tables consumes Perm Space. Apart from this, there is TEMP SPACE which is all unused space of PERM SPACE and it is used by Global Temporary Tables.

Teradata Utilities


Teradata Utilities

Below article shows the details of various Teradata Utilites and their usage.

BTEQ:

BTEQ is batch-mode utility for submitting SQL requests to the Teradata database. It runs on every supported platform – laptop to mainframe. It can both export/import data to/from client system.

Instead of checking error code or error level after each statement, use the following setting at the beginning of the script. This sets the error severity level at which BTEQ terminates to 1.
.MAXERROR 1

Thus, any error condition which results in an error level of 1 or greater will cause the program to terminate, returning the error code that caused the MAXERROR condition to trigger. (MAXERROR is NOT the maximum number of errors allowed).

Under certain conditions, it may be desirable to have certain error conditions not trigger the session to exit. Such an example is dropping a table or view, but not wanting to abort the session if that table/view does not exist. This can be accomplished by having the DROP statement as the first statement and .MAXERROR 1 as the second statement.

If your need to have the DROP object statement after some SQL statement (cannot be the first statement), the method to accomplish this is to set the error level associated with the error code.
.SET ERRORLEVEL 3807 SEVERITY 0
Then to reset the error level to be checked again you do the following:
.SET ERRORLEVEL 3807 SEVERITY 8
(8 is the default error level of the 3807 error, table/view does not exist).
You can find ERRORLEVEL for specific ERRORCODE in the BTEQ manual.
If you are going to use this functionality, it is very important to reset the ERRORLEVEL back to its default before processing any statement where you want that error condition to abort the script.
If need to implement loops in BTEQ script ,  can use following syntax/logic

Sql stmnt;

If activitycount ……

  =n ; ( how many times want to repeat the loop ).

Bteq Export

All bteq export processes should use the ‘close’ option of the export command and the 'set retry off' to ensure that the process aborts immediately upon a DBMS restart.  If not, the export will reconnect sessions when Teradata is available again, retransmitting rows already sent.

Bteq Import

All bteq import processes populating empty tables should be preceded by a delete of that table for restartability. Import will not automatically reconnect sessions after a Teradata restart.  The job must be manually restarted.


FASTLOAD:


Purpose: Loads large amount of data from external file into an empty table at high speed

Restriction:
Only load one empty table with 1 fast load job.
Tables defined with Referential integrity, secondary indexes, join indexes, hash indexes or triggers cannot be loaded with FastLoad.
Duplicate rows cannot be loaded into a multiset table with FastLoad.

FastLoad has two phases – Data Acquisition and Application. It requires separate error table for each phase. Use the BEGIN LOADING statement to specify (and create) the two error tables for the operation. We can specify the error table in the same database as the data table or different database.

BEGIN LOADING [dbname.]table_name
      ERRORFILES [dbname.]Err_Table1,
      ERRORFILES [dbname.]Err_Table2
      [CHECKPOINT integer]
      [INDICATORS];
.
.
.
.
END LOADING;
LOGOFF;

We must remove the error tables before we re-run the same load job or it will terminate in an error condition.

The CHECKPOINT option defines points in a job where FastLoad pauses to record that Teradata has processes a specified number of input records. When we use checkpoints, we do not have to re-run the entire Fastload job if it stops before completion. Fastload will use the checkpoint information in the restart log table to determine the restart location.Checkpoints slow FastLoad processing – set the CHECKPOINT large enough that checkpoints are taken every 10 to 15 minutes.

An errlimit count should be specified on all fastload utility control cards to pause the load when an unusually high number of constraint violations are directed to error table 1.  For large tables (such as fact tables), this number should be approximately 1000.  The errlimit for smaller tables, such as dimension tables, would be table specific.

END LOADING indicates that all data rows have been transmitted and the second phase can begin. Its omission means the load is incomplete and will be restarted later. This causes the table that is being loaded to become “Fastload Paused” and we can’t access the table via SQL. If the END LOADING was omitted by mistake, submit BEGIN and END LOADING statements, it will restart phase 2 only.

We can specify the max and min number of sessions that can be used by the Fastload script. Specify the max value equal to the number of AMPs. If we specify a max value larger than the number of available AMPs, Fastload limits the sessions to one per working AMP. Min is optional and defaulted to 1.

FAST EXPORT:

Purpose: Exports large volumes of formatted data from Teradata to a host file or user-written application.

Restrictions:
Equality conditions for a Primary Index or USI
WITH option to generate total or subtotal response rows.


The FastExport job may consist of multiple SELECT statements, which will be executed sequentially by FastExport.
In the .EXPORT statement, we need to specify definition of the output data file. The different data file format supported are: 
TEXT – Fixed width format
VARTEXT – Character delimiter format
BINARY – Binary format, a 2 bytes length indicator followed by n bytes of data

The data can be exported in the sorted order. But note that requesting sorted data adds additional work (overhead and time) to Teradata.

We can specify the max and min number of sessions that can be used by the FastExport script. Specify the max value equal to the number of AMPs. If we specify a max value larger than the number of available AMPs, FastExport limits the sessions to one per working AMP. Min is optional and defaulted to 1.


MULTI LOAD:


Purpose: Used for loading, updating or deleting data to and from populated tables, typically with batch inputs from a host file.

Restrictions:
Cannot process tables defined with USI’s, Referential Integrity, Join Indexes, Hash Indexes, or Triggers.
No data retrieval capability.
Import tasks require use of Primary Index.


The Multiload supports five target tables per script. Tables may contain pre-existing data. Ability to do INSERTs UPDATEs, DELETEs and UPSERTs.

In the BEGIN MLOAD statement define one work table for each target data table. If work tables are not defined, these are created with the table name prefixed by ‘WT_’. Make sure that the database where work tables are defined has enough space. Multiload loads the data into work table before applying into the target table data blocks.

Two error tables need to be defined for each target table. If they are not defined in the BEGIN MLOAD, they are defaulted to an ‘ET_’ and ‘UV_’ prefix and the table name. ‘ET_tablename’ refers to acquisition phase error table and ‘UV_tablename’ refers to an application phase error table.

BEGIN MLOAD
    TABLES tname1, tname2,…
    WORKTABLES wt_table1, wt_table2,…
    ERRORTABLES et_table1 uv_table1, et_table2 uv_table2, …
    [CHECKPOINT integer]
    [INDICATORS];
.
.
.
.
END MLOAD;

Use RELEASE MLOAD tablename; statement if MLOAD doesn’t successfully completed and there is no desire to restart the MLOAD. This will return the target table to general availability. Error tables should be dropped manually, as RELASE MLOAD will not drop them automatically.

In the .IMPORT statement, we need to specify definition of the input data file. The different data file format supported are: 
TEXT – Fixed width format
VARTEXT – Character delimiter format

We can specify the max and min number of sessions that can be used by the MLOAD script. Specify the max value equal to the number of AMPs. If we specify a max value larger than the number of available AMPs, MLOAD limits the sessions to one per working AMP. Min is optional and defaulted to 1.
Multiload jobs may or may not benefit from dropping/recreating indexes.  This is dependent on the size of the table, the number of indexes, and the size of the file being multiloading.  Tests will  need to be conducted to determine the method that performs best.  If drop/create index is not done, these members should exis, but contain comments only.

An errlimit count should be specified on all multiload utility control cards to pause the load when an unusually high number of constraint violations are directed to the ‘et’ error table.  For large tables (such as fact tables), this number should be approximately 1000. The errlimit for smaller tables, such as dimension tables, would be table specific.

Multiload Tips and Techniques

Multiload is a Teradata load utility that is used mostly to append rows to a table.  It is the fastest way to do this, but is substantially slower than fastload.  Although runtime is affected by the number of duplicate primary index values, multiload runs approximately 2-3 times slower than fastload.  A sample runtime on a 2 node, 12 amp NCR box is: 1000000, 300 byte rows in 1 hour (unique primary index).
Multiload usually runs faster when secondary indexes are dropped prior to the load and then recreated afterwards. Multiload does not support unique secondary indexes and they must be dropped prior to a multiload.
Multiload restart options depend on whether or not the job abends in the acquisition or application phase.  The syslist will indicate which phase it is in, but if you are unsure run the release mload command.  If the job is in the application phase, this command will not be accepted. Please see the multiload restart procedures for more details on restart options.
Multiload can also be used to perform a large number of deletes in an efficient manner, using the multiload delete statement. 
Any operation performed using MLOAD cannot be rolled back.



         

Teradata Joining Strategies

Teradata Join Strategies are utilized by the optimizer to choose the least cost plan and better performance. The strategy will be chosen based on the available information to the Optimizer like Table size, PI information, Stats Information. 

Teradata join strategies are following:
·       Merge (Exclusion)
·       Nested
·       Row Hash
·       Product (including Cartesian Product joins)

Merge Join Strategies


There are four different merge join strategies based on the redistribution. Below details have all these information.

Merge Join Strategy 1

The 1st merge join will utilize the Primary Index on both tables in the join Condition.
The key here is that both of the Primary Index columns of each table are used in the WHERE or ON clause in the join type.



The inner join above focuses on returning all rows when there is a match between the two tables. The ON clause is extremely important because this join establishes the join (equality) condition. Think of this as if you were repairing a deck and you required a certain kind of wood in order to make sure you had a match. You would go down to the local home improvement store to locate the right pieces of wood to repair the deck. A match would definitely not be cedar if your deck required pressured pine.

To investigate further, each matching row is joined where Emp = Emp which is stated from the ON Clause in the JOIN. If we analyze further, EMP is the Primary Index for both tables. This first merge join type is extremely efficient because both columns in the ON clause are the Primary Indexes of their respective tables. When this occurs, NO data has to be moved into spool and the joins can be performed in what is called AMP LOCAL. Teradata can perform this join with rapid speed. Remember that the less data that has to be moved to complete a join the better the performance will be achieved. The end result of this join is that the rows from each table are physically joined together to form one row.

Merge Join Strategy 2

The previous join strategy is the best join scenario because it focuses on utilizing the Primary Index Column in both tables for the equality (ON) condition. The next best scenario is when a join is performed on a Primary Index column of one table to a non-primary indexed column of another table.

In this example, two tables are being joined based on the DEPT column. In the department table, the Primary Index column is DEPT. As we know, this is a good match based on the equality (ON) condition. However, the employee table has EMP as the Primary Index column. Which table do you think will move based on this join?
Regardless of the equality condition, the primary objective is to bring the rows together from each table on the same AMPs. There are several options that the Teradata Optimizer could choose in order to complete this task. The first option is to duplicate the smaller table on all AMPs. The second option could be to leave the department table that has an equality condition match on the Primary Index Column stationary on the AMP. The next step would be to move the rows from the Employee table into spool. This would be accomplished by hashing (locating) the columns in the employee table, and then moving these rows into spool to the appropriate AMPs where the department table rows reside. What has occurred here is that the stationary table is already sorted by the hash code and the spool table will be re-sorted by hash code in spool to the appropriate matching AMPs.

Clearly the second option is an excellent choice for the Teradata Optimizer because it reduces the amount of resources necessary to complete the join and improve performance.

Merge Join Strategy 3

The third scenario is where neither table is being joined on the Primary Index of either table. In this case Teradata will redistribute both tables into spool and sort them by hash code. When we want to redistribute and sort by hash code we merely hash the non-primary index columns and move them to the AMPs spool where they are sorted by hash. Once this is accomplished, then the appropriate rows are together in spool on all the AMPs. It is now join time!

In the previous example, the columns in the join equality are MgrEmp = MgrNo. The Primary Index of the department table is DEPT and the Primary Index for the manager table is LOC. In this case, both columns being utilized in this join equality are not part of the Primary Index columns. So what strategy will Teradata take to resolve this join operation?
Basically rows from both tables will need to be rehashed and redistributed into SPOOL.
The reason is because neither columns selected in the ON Clause are the Primary Index of the respective tables. Therefore, both tables are redistributed based on the ON clause columns.

The next step in this process is to redistributed the rows and locate them to the matching AMPs. When this is completed, the rows from both tables will be located in two different spools. Lastly, the rows in each spool will be joined together to bring back the matching rows. This type of join strategy is extremely inefficient. It consumes a ton of resources and time to manage and assemble this type of join.

Merge Join Strategy 4

The fourth merge join strategy is called the big table - small table join. If one of the tables being joined is small, then Teradata may choose a strategy that will duplicate the smaller table across all the AMPs. The key about this strategy is that regardless if the table is part of the Primary Index Column or not Teradata could still choose to duplicate the table across all the AMPs.


In this inner join above, the two tables involved in the join are the Employee table and the Department table. The DEPT column is the join equality that is making the match between the two tables. The DEPT column is the Primary Index Column in the Department table. The Employee table has the EMP column as the Primary Index. The final analysis of this join is that the Department table is small and makes a good candidate for this type of join strategy.
In order to join these two tables together, the first step is to get the rows together on the same AMP. In this case, since the Department table is small, Teradata will choose to duplicate the entire Department table on each AMP into spool. Once this is completed, then the next step is for the AMPs to join the base Employee rows with the Department rows.
`
Instead of redistributing the larger Employee table, which is not part of the Primary Index Column in the equality (ON) condition, Teradata will choose a more efficient strategy. This strategy would be to duplicate the smaller table across all the AMPs (Big Table -Small Table Join). This merge join strategy will consume minimal resources, and allow for Teradata to excel.

Nested Join

A nested join strategy is probably the most precise join available. This join is designed to utilize a unique index type (Either Unique Primary Index or Unique Secondary Index) from one of the tables in the join statement in order to retrieves a single row. It then matches that row to one or more rows on the other table being used in the join.

From the example above, the nested join has the join equality (ON) condition based on the DEPT column. The dept column is the Primary Index Column on the department table. In addition, the dept column is the Secondary Index Column in the employee table. Based on this information above, which rows will move?
Keep in mind that the nested join prides itself on being able to move a single row into spool and then matching that row with another table that contains several matches. How is this done? Analysis of this join statement indicates a new clause has been added to this join statement. This is known as the WHERE option. When utilized, the WHERE option allows for a single row to be retrieved from a table. In addition, a nested join will always use a unique index to isolate that single record and then join that record to another table. The other table may use an index or it may not. However, the best practice is to always use columns that have indexes when doing joins. Teradata has superior knowledge on indexed columns and can utilize this information to choose an aggressive strategy to complete a join. Utilization of indexes in join statements will improve performance and utilize less resources as the below diagram illustrates.


Since there is only one row in the department table that has a match for department =10, which is based on the AND option in the join statement, the Teradata Optimizer will choose a path to move the department table columns into spool and duplicate them across all the AMP’s.
Once this is completed, then the matches will proceed with that single record (10 and SALES) to the second table, which did not move from the base AMP. Nested Joins are great in an OLTP Environment because of the usage of both Unique and Non-Unique Indexes. In addition, a nested join can reduce the resources necessary to complete the join. Finally, nested joins, which are similar to all the join strategies discussed, must have an equality condition in the ON Clause (d.dept = e.dept).

Hash Join

The Hash Join is part of the Merge Join Family. Remember that the key to a Merge Join is based on an equality condition such as E.Dept = D.Dept in the ON clause of the join statement. A Hash Join can only take place if one or both of the tables on each AMP can fit completely inside the AMP’s memory.
Hash Join Strategy

In this example, the Hash Join has a join equality (ON) condition based on the EMP and MGREMP Columns. The key point here is the columns do not necessarily have to the same name when doing a join operation. The columns names can be different but the row information has to be similar in order for the match to work. Both the EMP and MGREMP columns have the same type of information so therefore a join based on these column names will be successful. In addition, EMP column is the Primary Index column on the employee table. However, the MGREMP column is not an index column in the department table. Based on this information above, which rows will move?
Remember that the key to determining a Hash Join is if the SMALLER TABLE can be held completely in each AMP’s MEMORY.


The Hash Join process is where the smaller table is sorted by row hash and duplicated on every AMP. The key here is that the smaller table is required to be held completely in each AMP’s memory. Teradata will use the join column of the larger table in order to search for a match. The row hash join is extremely efficient because it eliminates the sorting, redistribution, and or copying of the larger table into spool. In addition, the rows that are duplicated into the AMP’s memory yield increased performance because the rows never go into spool. Rows that go into spool always have to involve disk activity. AMP memory does not involve disk interaction, which automatically increases performance. Hash Joins and Nested Joins are both Great in an OLTP Environment for these reasons.

Exclusion Join

All of the joins that we have reviewed up to this point were based on finding matching rows based on a join equality condition. The returned rows from these types of joins compared rows from both tables in a join and then returned rows that matched. In addition, these joins were inclusive. When working with exclusion joins the thought process has to be reversed. Exclusion Joins have one primary function. They exclude rows during a join. The best example here is when I was out with my best friend and his two sons (Blake and Zach). They were telling a story that sounded believable about their dog Freddie who allegedly chased a neighbor’s cat down the street. When they completed the story, I asked them if this was true…they said in unison “NOT”! Well the NOT statement works exactly the same in Teradata. When you put a NOT in front of a statement it will give you the opposite answer.

SELECT EMP, DEPT, NAME 
FROM 
EMPLOYEETABLE
WHERE DEPT=10 and 
EMP NOT IN (SELECT MGREMP from DEPTTABLE WHERE MGREMP IS NOT NULL )

As you can see in the above example and as has been discussed above this type of join utilizes the NOT IN statement. Exclusion joins are used for finding rows that don’t have a matching row in the other table. Queries with the NOT IN operator are the types of queries that always result in exclusion joins. In this case, this query will find all the employees who belong to department 10 who are NOT managers.
These joins will always involve a Full Table Scan because Teradata will need to compare every record to eliminate rows that will need to be excluded. With this being stated, this type of join can be resource intensive if the two tables in this comparison are large.
In addition, the biggest problem with the Exclusion Joins is when the NOT IN statement is used. The reason for this is that NULLs are considered unknowns so the data returned in the answer will be NULLs. There are two ways to correct this:
·       Define NOT IN columns as NOT NULL on the CREATE TABLE.
·       Add the “ AND WHERE Column IS NOT NULL” to the end of the JOIN as seen in the above example.

Product Joins

What Makes Product Joins Different

Product Joins compare every row of one table to every row of another table. They are called product joins because they are a product of the number of rows in table one multiplied by the number of rows in table two. For example, if one table had five rows and the other table had five rows then the Product Join would compare 5 x 5 or 25 rows with a potential of 25 rows coming back.

SELECT E.EMP,D.DEPT 
FROM EMPLOYEETABLE E,DEPTTABLE D
WHERE
EMP LIKE '_b%'
About 99% of the time, product joins are major mistakes. The recommendation is to avoid these types of queries whenever possible. The reason is because all rows in both tables will be compared. Remember, Teradata tables have the potential to contain millions of rows. If a user accidentally writes a product join against two tables that have 1 million rows each. The result set would return One Trillion Rows (1000000000000)! Needless to say this is a mistake you want to make. So how do you avoid writing a product join?
To avoid a product join, check your syntax to ensure that the join is based on an EQUALITY condition. In the join syntax example above, the equality statement reads “WHERE EMP Like ‘_b%’”. Because this clause is not based on a common domain condition between the two tables (i.e., e.dept = d.dept), the result is a product join. Another cause of a product join is when aliases are not used after being established. Finally check your join syntax to ensure the WHERE clause is not missing.

Cartesian Product Join

Just as discussed with Product Joins above, a Cartesian Product Join is usually something you want to avoid. If we decided to run this query in Michigan this would be call the big “Mistake on the Lake”. A Cartesian Product Join will join every row in one table to every row in another table. The only thing that decides the number of rows will be the total number of rows from both tables. If one table had 5 rows and another had 10 rows then you will always get 50 rows returned. Imagine this situation. if we have a table with 10 million rows and another with 25 million rows and a Cartesian product join is written (by accident) against these two tables. What will be the result? Well, based on the example above, you will get back about 25 Trillion Rows (250000000000000)! This is definitely NOT the correct answer this user would want. This is why spool space limitations are utilized.


SELECT E.EMP,D.DEPT 
FROM EMPLOYEETABLE E,DEPTTABLE D;
About 99% of the time, a Cartesian Product Join is a major problem. The recommendation is avoid these types of queries whenever possible. The reason is because all rows in both tables will be joined. So how do you avoid writing a Cartesian Product Join?
To avoid a Cartesian Product Join, check your syntax to ensure that the join is based on an EQUALITY condition. In the join syntax example above, the WHERE clause is missing. Because this clause is missing, a common domain condition between the two tables (i.e., e.dept = d.dept) does not exist, the result is a product join. Another cause of a product join is when aliases are not used after being established.