Teradata SQL Quick Reference

401
8/10/2019 Teradata SQL Quick Reference http://slidepdf.com/reader/full/teradata-sql-quick-reference 1/401 Teradata SQL Quick Reference

Transcript of Teradata SQL Quick Reference

Page 1: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 1/401

Teradata SQL Quick Reference

Page 2: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 2/401

Chapter 1: Teradata Parallel Architecture

Teradata Introduction

The world's largest data warehouses commonly use the superior technology of NCR's

Teradata relational dataase management system !R"#$S%& data warehouse is normallyloaded directly from operational data& The ma(ority) if not all of this data will e collected on*line as a result of normal usiness operations& The data warehouse therefore acts as acentral repository of the data that reflects the effecti+eness of the methodologies used inrunning a usiness&

 s a result) the data loaded into the warehouse is mostly historic in nature& To get a truerepresentation of the usiness) normally this data is not changed once it is loaded& ,nstead) itis interrogated repeatedly to transform data into useful information) to disco+er trends andthe effecti+eness of operational procedures& This interrogation is ased on usiness rules todetermine such aspects as profitaility) return on in+estment and e+aluation of risk&

-or e.ample) an airline might load all of its maintenance acti+ity on e+ery aircraft into thedataase& Suse/uent in+estigation of the data could indicate the fre/uency at which certainparts tend to fail& -urther analysis might show that the parts are failing more often on certainmodels of aircraft& The first enefit of the new found knowledge regards the aility to plan for the ne.t failure and maye e+en the type of airplane on which the part will fail& Therefore) thepart can e on hand when and maye where it is needed or the part might e proacti+elychanged prior to its failure&

,f the information re+eals that the part is failing more fre/uently on a particular model of aircraft) this could e an indication that the aircraft manufacturer has a prolem with thedesign or production of that aircraft& nother possile cause is that the maintenance crew isdoing something incorrectly and contriuting to the situation& 0ither way) you cannot fi. aprolem if you do not know that a prolem e.ists& There is incredile power and sa+ings inthis type of knowledge&

 nother usiness area where the Teradata dataase e.cels is in retail& ,t pro+ides anen+ironment that can store illions of sales& This is a critical capaility when you arerecording and analying the sales of e+ery item in e+ery store around the world& 2hether it isused for in+entory control) marketing research or credit analysis) the data pro+ides an insightinto the usiness& This type of knowledge is not easily attainale without detailed data thatrecords e+ery aspect of the usiness& Tracking in+entory turns) stock replenishment) or predicting the numer of goods needed in a particular store yields a priceless perspecti+einto the operation of a retail outlet& This information is what enales one retailer to thri+ewhile others go out of usiness&

Teradata  is flourishing with the realiation that detail data is critical to the sur+i+al of ausiness in a competiti+e) lower margin en+ironment& Continually) usinesses are forced todo more with less& Therefore) it is +ital to ma.imie the efforts that work well to impro+e profit

and minimie or correct those that do not work&

3ne computer +endor used these same techni/ues to determine that it cost more to sell intothe desktop en+ironment than was realied in profit& 4rior to this realiation) the sales efforthad attempted to make up the loss y selling more computers& 5nfortunately) increasedsales meant increased losses& Today) that company is doing much etter and has made ahuge step into profitaility y discontinuing the small computer line&

Page 3: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 3/401

Teradata Architecture

The Teradata dataase currently runs normally on NCR Corporation's 2orld$ark Systems inthe 5N,6 $4*RS en+ironment& Some of these systems consist of a single processing node!computer% while others are se+eral hundred nodes working together in a single system& TheNCR nodes are ased entirely on industry standard C45 processor chips) standard internal

and e.ternal us architectures like 4C, and SCS,) and standard memory modules with 7*wayinterlea+ing for speed&

 t the same time) Teradata can run on any hardware ser+er in the single node en+ironmentwhen the system runs $icrosoft NT and 2indows 8999& This single node may e anycomputer from a large ser+er to a laptop&

2hether the system consists of a single node or is a massi+ely parallel system withhundreds of nodes) the Teradata R"#$S uses the e.act same components e.ecuting on allthe nodes in parallel& The only difference etween small and large systems is the numer of processing components&

2hen these components e.ist on different nodes) it is essential that the componentscommunicate with each other at high speed& To facilitate the communications) the multi*nodesystems use the #N0T as the interconnect etween the nodes& ,t is a high speed) multi*path) dual redundant communications channel& nother amaing capaility of the #N0T isthat the andwidth increases with each consecuti+e node added into the system& There ismore detail on the #N0T later in this chapter&

Teradata Components

 s pre+iously mentioned) Teradata  is the superior product today ecause of its paralleloperations ased on its architectural design& ,t is the parallel processing y the ma(or components that pro+ide the power to mo+e mountains of data& Teradata works more like theearly 0gyptians who uilt the pyramids without hea+y e/uipment using parallel) coordinatedhuman efforts& ,t uses smaller nodes running se+eral processing components all working

together on the same user re/uest& Therefore) a monumental task is completed in recordtime&

Teradata operates with three ma(or components to achie+e the parallel operations& Thesecomponents are called: 4arsing 0ngine 4rocessors) ccess $odule 4rocessors and the$essage 4assing Layer& The role of each component is discussed in the ne.t sections topro+ide a etter understanding of Teradata& 3nce we understand how Teradata works) wewill pursue the SQL that allows storage and access of the data&

Parsing Engine Processor (PEP or PE)

The 4arsing 0ngine 4rocessor !404% or 4arsing 0ngine !40%) for short) is one of the twoprimary types of processing tasks used y Teradata& ,t pro+ides the entry point into the

dataase for users on mainframe and networked computer systems& ,t is the primary director task within Teradata&

 s users ;logon; to the dataase they estalish a Teradata session& 0ach 40 can manage189 concurrent user sessions& 2ithin each of these sessions users sumit SQL as a re/uestfor the dataase ser+er to take an action on their ehalf& The 40 will then parse the SQLstatement to estalish which dataase o(ects are in+ol+ed& -or now) let's assume that thedataase o(ect is a tale& tale is a two*dimensional array that consists of rows andcolumns& row represents an entity stored in a tale and it is defined using columns& n

Page 4: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 4/401

e.ample of a row might e the sale of an item and its columns include the 54C) adescription and the /uantity sold&

 ny action a user re/uests must also go through a security check to +alidate their pri+ilegesas defined y the dataase administrator& 3nce their authoriation at the o(ect le+el is+erified) the 40 will +erify that the columns re/uested actually e.ist within the o(ectsreferenced&

Ne.t) the 40 optimies the SQL to create an e.ecution plan that is as efficient as possileased on the amount of data in each tale) the indices defined) the type of indices) theselecti+ity le+el of the indices) and the numer of processing steps needed to retrie+e thedata& The 40 is responsile for passing the optimied e.ecution plan to other componentsas the est way to gather the data&

 n e.ecution plan might use the primary inde. column assigned to the tale) a secondaryinde. or a full tale scan& The use of an inde. is preferale and will e discussed later in thischapter& -or now) it is sufficient to say that a full tale scan means that all rows in the talemust e read and compared to locate the re/uested data&

 lthough a full tale scan sounds really ad) within the architecture of Teradata) it is not

necessarily a ad thing ecause the data is di+ided up and distriuted to multiple) parallelcomponents throughout the dataase& 2e will look ne.t at the $4s that perform theparallel disk access using their file system logic& The $4s manage all data storage ondisks& The 40 has no disks&

 cti+ities of a 40: Con+ert incoming re/uests from 0#C",C to SC,, !if from an ,#$ mainframe% 4arse the SQL to determine type and +alidity <alidate user pri+ileges 3ptimie the access path!s% to retrie+e the rows

#uild an e.ecution plan with necessary steps for row access Send the plan steps to ccess $odule 4rocessors !$4% in+ol+ed

Access Module Processor (AMP)

The ne.t ma(or component of Teradata's parallel architecture is called an ccess $odule4rocessor !$4%& ,t stores and retrie+es the distriuted data in parallel& ,deally) the data rowsof each tale are distriuted e+enly across all the $4s& The $4s read and write data andare the workhorses of the dataase& Their (o is to recei+e the optimied plan steps) uilt ythe 40 after it completes the optimiation) and e.ecute them& The $4s are designed towork in parallel to complete the re/uest in the shortest possile time&

3ptimally) e+ery $4 should contain a suset of all the rows loaded into e+ery tale& #ydi+iding up the data) it automatically di+ides up the work of retrie+ing the data& Rememer)all work comes as a result of a users' SQL re/uest& ,f the SQL asks for a specific row) thatrow e.ists in its entirety !all columns% on a single $4 and other rows e.ist on the other 

 $4s&

,f the user re/uest asks for all of the rows in a tale) e+ery $4 should participate along withall the other $4s to complete the retrie+al of all rows& This type of processing is called anall $4 operation and an all rows scan& =owe+er) each $4 is only responsile for its rows)not the rows that elong to a different $4& s far as the $4s are concerned) it owns all of the rows& 2ithin Teradata) the $4 en+ironment is a ;shared nothing; configuration& The

 $4s cannot access each other's data rows) and there is no need for them to do so&

Page 5: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 5/401

3nce the rows ha+e een selected) the last step is to return them to the client program thatinitiated the SQL re/uest& Since the rows are scattered across multiple $4s) they must econsolidated efore reaching the client& This consolidation process is accomplished as a partof the transmission to the client so that a final comprehensi+e sort of all the rows is ne+er performed& ,nstead) all $4s sort only their rows !at the same time > in parallel% and the$essage 4assing Layer is used to merge the rows as they are transmitted from all the

 $4s&

Therefore) when a client wishes to se/uence the rows of an answer set) this techni/uecauses the sort of all the rows to e done in parallel& 0ach $4 sorts only its suset of therows at the same time all the other $4s sort their rows& 3nce all of the indi+idual sorts arecomplete) the #N0T merges the sorted rows& 4retty rilliant?

 cti+ities of the $4: Store and retrie+e data rows using the file system  ggregate data

@oin processing etween multiple tales Con+ert SC,, returned data to 0#C",C !,#$ mainframes only% Sort and format output data

Message Passing Layer (BYNET)

The $essage 4assing Layer +aries depending on the specific hardware on which theTeradata dataase is e.ecuting& ,n the latter part of the 89 th century) most Teradata dataasesystems e.ecuted under the 5N,6 operating system& =owe+er) in 1AAB) Teradata  wasreleased on $icrosoft's NT operating system& Today it also e.ecutes under 2indows 8999&The initial release of Teradata) on the $icrosoft systems) is for a single node&

2hen using the 5N,6 operating system) Teradata supports up to 18 nodes& This massi+elyparallel system estalishes the asis for storing and retrie+ing data from the largestcommercial dataases in the world) Teradata& Today) the largest system in the world consistsof 1DE nodes& There is much room for growth as the dataases egin to e.ceed 79 or 9teraytes&

-or the NCR 5N,6 systems) the $essage 4assing Layer is called the #N0T& The amaingthing aout the #N0T is its capacity& ,nstead of a fi.ed andwidth that is shared amongmultiple nodes) the andwidth of the #N0T increases as the numer of nodes increase&This feat is accomplished as a result of using +irtual circuits instead of using a single fi.edcale or a twisted pair configuration&

To understand the workings of the #N0T) think of a telephone switch used y local andlong distance carriers& s more and more people place phone calls) no one needs to speakslower& s one switch ecomes saturated) another switch is automatically used& 2hen your phone call is routed through a different switch) you do not need to speak slower& ,f a naturalor other type of disaster occurs and a switch is destroyed) all suse/uent calls are routedthrough other switches& The #N0T is designed to work like a telephone switching network&

 n additional aspect of the #N0T is that it is really two connection paths) like ha+ing twophone lines for a usiness& The redundancy allows for two different aspects of itsperformance& The first aspect is speed& 0ach path of the #N0T pro+ides andwidth of 19$egaytes !$#% per second with <ersion 1 and E9 $# per second with <ersion 8& Thereforethe aggregate speed of the two connections is 89$#Fsecond or 189$#Fsecond& =owe+er) asmentioned earlier) the andwidth grows linearly as more nodes are added&

5sing <ersion 1 any two nodes communicate at 79$#Fsecond !19$#Fsecond G 8 #N0Ts G8 nodes%& Therefore) 19 nodes can utilie 899$#Fsecond and 199 nodes ha+e

Page 6: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 6/401

8999$#Fsecond a+ailale etween them& 2hen using the +ersion 8 #N0T) the same 199nodes communicate at 18)999$#Fsecond !E9$#Fsecond G 8 #N0Ts G 199 nodes%&

The second and e/ually important aspect of the #N0T uses the two connections for a+ailaility& Regardless of the speed associated with each #N0T connection) if one of theconnections should fail) the second is completely independent and can continue to functionat its indi+idual speed without the other connection& Therefore) communications continue topass etween all nodes&

 lthough the #N0T is performing at half the capacity during an outage) it is still operationaland SQL is ale to complete without failing& ,n reality) when the #N0T is performing at only19$#Fsecond per node) it is still a lot faster than many normal networks that typicallytransfer messages at 19$# per second&

 ll messages going across the #N0T offer guaranteed deli+ery& So) any messages notsuccessfully deli+ered ecause of a failure on one connection automatically route across theother connection& Since half of the #N0T is not working) the andwidth reduces y half&=owe+er) when the failed connection is returned to ser+ice) its topology is automaticallyconfigured ack into ser+ice and it egins transferring messages along with the other connection& 3nce this occurs) the capacity returns to normal&

A Teradata ata!ase

2ithin Teradata) a dataase is a storage location for dataase o(ects !tales) +iews)macros) and triggers%& n administrator can use "ata "efinition Language !""L% to estalisha dataase y using a CR0T0 "T#S0 command&

  dataase may ha+e 40R$N0NT !40R$% space allocated to it& This 40R$ spaceestalishes the ma.imum amount of disk space for storing user data rows in any talelocated in the dataase& =owe+er) if no tales are stored within a dataase) it is not re/uiredto ha+e 40R$ space& lthough a dataase without 40R$ space cannot store tales) it canstore +iews and macros ecause they are physically stored in the "ata "ictionary !""%40R$ space and re/uire no user storage space& The "" is in a ;dataase; called "#C&

Teradata allocates 40R$ space to tales) up to the ma.imum) as rows are inserted& Thespace is not pre*allocated& ,nstead) it is allocated) as rows are stored in locks on disk& Thema.imum lock sie is defined either at a system le+el in the "#S Control Record) at thedataase le+el or indi+idually for each tale& Like 40R$) the lock sie is a ma.imum sie&et) it is only a ma.imum for locks that contain multiple rows& #y nature) the locks are+ariale in length& So) disk space is not pre*allocatedH instead) it is allocated on an asneeded asis) one sector !18 ytes% at a time& Therefore) the largest possile wasted diskspace in a lock is 11 ytes&

  dataase can also ha+e S433L space associated with it& ll users who run /ueries needworkspace at some point in time& This S433L space is workspace used for the temporary

storage of rows during the e.ecution of user SQL statements& Like 40R$ space) S433L isdefined as a ma.imum amount that can e used within a dataase or y a user& Since40R$ is not pre*allocated) unused 40R$ space is automatically a+ailale for use asS433L& This ma.imies the disk space throughout the system&

,t is a common practice in Teradata to ha+e some dataases with 40R$ space that containonly tales& Then) other dataases contain only +iews& These +iew dataases re/uire no40R$ space and are the only dataases that users ha+e pri+ileges to access& The +iews inthese dataases control all access to the real tales in other dataases& They insulate theactual tales from user access& There will e more on +iews later in this ook&

Page 7: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 7/401

The newest type of space allocation within Teradata  is T0$43RR !T0$4% space& dataase may or may not ha+e T0$4 space) howe+er) it is re/uired if Iloal TemporaryTales are used& The use of temporary tales is also co+ered in more detail later in the SQLportion of this ook&

  dataase is defined using a series of parameter +alues at creation time& The ma(ority of the parameters can easily e changed after a dataase has een created using the $3",-"T#S0 command& =owe+er) when attempting to increase 40R$ or T0$4 spacema.imums) there must e sufficient disk space a+ailale e+en though it is not immediatelyallocated& There may not e more 40R$ space defined that actual disk on the system&

  numer of additional dataase parameters are listed elow along with the user parametersin the  ne.t section& These parameters are tools for the dataase administrator and other e.perienced users when estalishing dataases for tales and +iews&

C"EATE # M$I%Y ATABA&E Parameters 40R$N0NT

T0$43RR S433L  CC35NT

-LL#CJ @35RNL "0-5LT @35RNL

Teradata 'sers

,n Teradata) a user is the same as a dataase with one e.ception& user is ale to logon tothe system and a dataase cannot& Therefore) to authenticate the user) a password must eestalished& The password is normally estalished at the same time that the CR0T0 5S0Rstatement is e.ecuted& The password can also e changed using a $3",- 5S0Rcommand&

Like a dataase) a user area can contain dataase o(ects !tales) +iews) macros andtriggers%& user can ha+e 40R$ and T0$4 space and can also ha+e spool space& 3n theother hand) a user might not ha+e any of these types of space) e.actly the same as adataase&

The iggest difference etween a dataase and a user is that a user must ha+e a password&This similarity etween the two makes administering the system easier and allows for default+alues that all dataases and users can inherit&

The ne.t two lists regard the creation and modification of dataases and users&

C"EATE M$I%Y * ATABA&E or '&E" (in common)

40R$N0NT T0$43RR

S433L  CC35NT -LL#CJ @35RNL

"0-5LT @35RNL

Page 8: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 8/401

C"EATE M$I%Y * '&E" (only) 4SS23R" STRT54 "0-5LT "T#S0

#y no means are these all of the parameters& ,t is not the intent of this chapter) nor the intent

of this ook to teach dataase administration& There are reference manuals and coursesa+ailale to use& Teradata administration warrants a ook y itself&

&ym!ols 'sed in this Boo+

Since there are no standard symols for teaching SQL) it is necessary to understand someof the symols used in our synta. diagrams throughout this ook&

This chart should e used as a reference for SQL synta. used in the ook:

3pen tale as spreadsheet  This chart should !e used as a re,erence ,or &-Lsynta. used in the !oo+/

Kdataase*name

Sustitute an actual dataase name in this location

Ktale*name Sustitute an actual tale name in this location

Kcomparison Sustitute a comparison in this location) i&e& aM1

Kcolumn*name Sustitute an actual column name in this location

Kdata*+alue Sustitute a literal data +alue in this location

optional entry O 0+erything etween the O is optional) not re/uired to e +alidsynta. ) use when needed

P use this or this

5se one of the keywords or symols on either side of the ;;)ut not oth& ,&e& P L0-T R,I=T use either ;L0-T; or ;R,I=T; ut not oth and the left P and the right are ne+er used in SQL&

%igure 010 

ATABA&E Command

2hen users negotiate a successful logon to Teradata) they are automatically positioned in adefault dataase as defined y the dataase administrator& 2hen an SQL re/uest is

e.ecuted) y default) it looks in the current dataase for all referenced o(ects&

There may e times when the o(ect is not in the current dataase& 2hen this happens) theuser has one of two choices to resol+e this situation& 3ne solution is to /ualify the name of the o(ect along with the name of the dataase in which it resides& To do this) the user simplyassociates the dataase name to the o(ect name y connecting them with a period !&% or dotas shown elow:

Kdataase*name&Ktale*name

Page 9: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 9/401

The second solution is to use the dataase command& ,t repositions the user to the specifieddataase& fter the dataase command is e.ecuted) there is no longer a need to /ualify theo(ects in that dataase& 3f course) if the SQL statement references additional o(ects inanother dataase) they will ha+e to e /ualified in order for the system to locate them&Normally) you will "T#S0 to the dataase that contains most of the o(ects that youneed& Therefore it reduces the numer of o(ect names re/uiring /ualification&

The following is the synta. for the "T#S0 command&

"T#S0 Kdataase*name H

,f you are not sure what dataase you are in) either the =0L4 S0SS,3N or S0L0CT"T#S0 command may e used to make that determination& These commands and other =0L4 functions are co+ered in the SQL portion of this ook&

'se o, an Inde.

 lthough a relational data model uses 4rimary Jeys and -oreign Jeys to estalish therelationships etween tales) that design is a Logical $odel& 0ach +endor uses specialiedtechni/ues to implement a 4hysical $odel& Teradata does not use keys in its physical model&,nstead) Teradata is implemented using indices) oth primary and secondary&

The 4rimary ,nde. !4,% is the most important inde. in all of Teradata& The performance of Teradata can e linked directly to the selection of this inde.& The data +alue in the 4,column!s% is sumitted to the hashing function& The resulting row hash +alue is used to mapthe row to a specific $4 for data distriution and storage&

To illustrate this concept) , ha+e on se+eral occasions used two decks of cards& ,magine if you will) fourteen people in a room& To the largest) most powerful looking man in the room)you gi+e one of the decks of cards& =is large hands allow him to hold all fifty*two cards atone time) with some degree of success& The cards are arranged with the ace of spadescontinuing through the king of spades in ascending order& fter the spades) the hearts comene.t) then the clus and last) the diamonds& 0ach suit is arranged starting with the ace and

ascending up to the king& The cards are partitioned y suit&

The other deck of cards is di+ided among the other thirteen people& 5sing this procedure) allcards with the same +alue !i&e& aces% all go to the same person& Likewise) all the deuces)treys and suse/uent cards each go to one of the thirteen people& 0ach of the four cards wille in the same order as the suits contained in the single deck that went to the lone man:spades) hearts) clus and diamonds& 3nce all the cards ha+e een distriuted) each of thethirteen people will e holding four cards of the same +alue !7G1M8%& Now) the game canegin&

The re/uests in this game come in the form of ;gi+e*me); one or more cards&

To make it easy for the lone player) we first re/uest: gi+e*me the ace of spades& The person

with four aces finds their ace) as does the lone player with all 8 cards) oth on the top other their cards& That was easy?

 s the difficulty of the gi+e*me re/uests increase) the le+el of difficulty dramatically increasesfor the lone person& -or instance) when a gi+e*me re/uest is for all of the twos) only one of the thirteen people holds up all four of their cards and it is finished& The lone man mustlocate the 8 of spades etween the ace and trey& Then) go and locate the 8 of hearts)thirteen cards later etween the ace and trey& Then) find the 8 of clus) thirteen cards after that) as well as the 8 of diamonds) and thirteen cards after that to finally complete there/uest&

Page 10: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 10/401

 nother re/uest might e gi+e*me all of the diamonds& -or the thirteen people) each personlocates and holds up one card of their cards and the re/uest is finished& -or the lone personwith the single deck) the re/uest means finding and holding up the last thirteen cards in their deck of fifty*two& ,n each of these gi+e*me re/uests) the lone man had to negotiate all fiftytwo cards while the thirteen other people only needed to determine which of the four cardsapplied to the re/uest) if any& This is the same procedure used y Teradata& ,t di+ides up thedata like we di+ided up the cards&

 s illustrated) the thirteen people are faster than the lone man& =owe+er) the game is notlimited to thirteen players& ,f there were 8E people who wished to play on the same team) thecards simply need to e di+ided or distriuted differently&

2hen using the +alue !ace through king% there are only 1 uni/ue +alues& ,n order for 8Epeople to play) we need a way to come up with 8E uni/ue +alues for 8E people& To make thecards more uni/ue) we might comine the +alue of the card !i&e& ace% with the color&Therefore) we ha+e two red aces and two lack aces as well as two sets for e+ery other card& Now when we distriute the cards) each of the twenty*si. people recei+es only twocards instead of the original four& The distriution is still ased on f ifty*two cards !8 times 8E%&

 t the same time) the optimum numer of people for the game is not 8E& #ased on what has

een discussed so far) what is the optimum numer of people

,f your answer is 8) then you are asolutely correct&

2ith this many people) each person has one and only one card& ny time a gi+e*me isre/uested of the participants) their one card either /ualifies or it does not& ,t doesn't get anysimpler or faster than this situation&

 s easy as this may sound) to accomplish this distriution the +alue of the card alone is notsufficient to manifest 8 uni/ue +alues& Neither is using the +alue and the color& Thatcomination only gi+es us a distriution of 8E uni/ue +alues when 8 uni/ue +alues aredesired&

To achie+e this distriution we need to estalish still more uni/ueness& -ortunately) we canuse the suit along with the +alue& Therefore) the ace of spades is different than the ace of hearts) which is different from the ace of clus and the ace of diamonds& ,n other words)there are now 8 uni/ue identities to use for distriution&

To relate this distriution to Teradata) one or more columns of a tale are chosen to e the4rimary ,nde.&

Primary Inde.

The 4rimary ,nde. can consist of up to 1E different columns prior to <8RE and E7 columnswith that release& These columns) when considered together) pro+ide a comprehensi+etechni/ue to deri+e a 5ni/ue 4rimary ,nde. !54,) pronounced as ;you*pea;% +alue as we

discussed pre+iously regarding the card analogy& That is the good news&

To store the data) the +alue!s% in the 4, are hashed +ia a calculation to determine which $4will own the data& The same data +alues always hash the same row hash and therefore arealways associated with the same $4&

The ad+antage to using up to si.teen columns is that row distriution is +ery smooth or e+enly ased on uni/ue +alues& This simply means that each $4 contains the samenumer of rows& t the same time) there is a downside to using se+eral columns for a 4,&The 40 needs e+ery data +alue for each column as input to the hashing calculation to

Page 11: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 11/401

directly access a particular row& ,f a single column +alue is missing) a full tale scan willresult ecause the row hash cannot e recreated& ny row retrie+al using the 4, column!s% isalways an efficient) one $4 operation&

 lthough uni/ueness is good in most cases) Teradata does not re/uire that a 54, e used& ,talso allows for a Non*5ni/ue 4rimary ,nde. !N54,) pronounced as new*pea%& The potentialdownside of a N54, is that if se+eral duplicate +alues !N54, dups% are stored) they all go tothe same $4& This can cause an une+en distriution that places more rows on some of the

 $4s than on others& This means that any time an $4 with a larger numer of rows isin+ol+ed) it has to work harder than the other $4s& The other $4s will finish efore theslower $4& The time to process a single user re/uest is always ased on the slowest $4&Therefore) serious consideration should e used when making the decision to use a N54,&

0+ery tale must ha+e a 4, and it is estalished when the tale is created& ,f the CR0T0T#L0 statement contains: 5N,Q50 4R,$R ,N"06 !Kcolumn*list%) the +alue in thecolumn!s% will e distriuted to an $4 as a 54,& =owe+er) if the statement reads: 4R,$R,N"06 !Kcolumn*list%) the +alue in the column!s% will e distriuted as a N54, and allowduplicate +alues& gain) all the same +alues will go to the same $4&

,f the ""L statement does not specify a 4,) ut it specifies a 4R,$R J0 !4J%) the named

column!s% are used as the 54,& lthough Teradata does not use primary keys) the ""L maye ported from another +endor's dataase system&

  54, is used ecause a primary key must e uni/ue and cannot e null& #y default) oth54,s and N54,s allow a null +alue to e stored unless the column definition indicates thatnull +alues are not allowed using a N3T N5LL constraint&

Now) with that eing said) when considering @3,N accesses on the tales) sometimes it isad+antageous to use a N54,& This is ecause the rows eing (oined etween tales must eon the same $4& ,f they are not on the same $4) one of the rows must e mo+ed to thesame $4 as the matching row& Teradata will use one of two different strategies totemporarily mo+e rows& ,t can copy all needed rows to all $4s or it can redistriute themusing the hashing mechanism on the column defined as the (oin domain that is a 4,&

=owe+er) if neither (oin column is a 4,) it might e necessary to redistriute all participatingrows from oth tales y hash code to get them together on a single $4&

4lanning data distriution) using access characteristics) can reduce the amount of datamo+ement and therefore impro+e (oin performance& This works fine as long as there are aconsistent numer of duplicate +alues or only a small numer of duplicate +alues& Thelogical data model needs to e e.tended with usage information in order to know the estway to distriute the data rows& This is done during the physical implementation phaseefore creating tales&

&econdary Inde.

  Secondary ,nde. !S,% is used in Teradata as a way to directly access rows in the data)

sometimes called the ase tale) without re/uiring the use of 4, +alues& 5nlike the 4,) an S,does not effect the distriution of the data rows& ,nstead) it is an alternate read path andallows for a method to locate the 4, +alue using the S,& 3nce the 4, is otained) the row cane directly accessed using the 4,& Like the 4,) an S, can consist of up to 1E columns until<8RE and then up to E7 columns&

,n order for an S, to retrie+e the data row y way of the 4,) it must store and retrie+e an inde.row& To accomplish this Teradata creates) maintains and uses a sutale& The 4, of thesutale is the +alue in the column!s% that are defined as the S,& The ;data; stored in thesutale row is the pre+iously hashed +alue of the real 4, for the data row or rows in the

Page 12: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 12/401

ase tale& The S, is a pointer to the real data row desired y the re/uest& n S, can also euni/ue !5S,) pronounced as you*sea% or non*uni/ue !N5S,) as new*sea%&

The rows of the sutale contain the row hashed +alue of the S,) the actual data +alue!s% of the S,) and the row hashed +alue of the 4, as the row ,"& 3nce the row ," of the 4, isotained from the sutale row) using the hashed +alue of the S,) the last step is to get theactual data row from the $4 where it is stored& The action and hashing for an S, is e.actlythe same as when starting with a 4,& 2hen using a 5S,) the access of the sutale is a one

 $4 operation and then accessing the data row from the ase tale is another one $4operation& Therefore) 5S, accesses are always a two $4 operation ased on two separaterow hash operations& 2hen using a N5S,) the sutale access is always an all $4operation& Since the data is distriuted y the 4,) N5S, duplicate +alues may e.ist andproaly do e.ist on multiple $4s& So) the est plan is to go to all $4s and check for there/uested N5S, +alue&

To make this more efficient) each $4 scans its sutale& These sutale rows contain therow hash of the N5S,) the +alue of the data that created the N5S, and one or more row ,"sfor all the 4, rows on that $4& This is still a fast operation ecause these rows are /uitesmall and se+eral are stored in a single lock& ,f the $4 determines that it contains no rowsfor the +alue of the N5S, re/uested) it is finished with its portion of the re/uest& =owe+er) if 

an $4 has one or more rows with the re/uested N5S, +alue) it then goes and retrie+es thedata rows into spool space using the inde.&

2ith this said) the SQL optimier may decide that there are too many ase tale data rowsto make inde. access efficient& 2hen this happens) the $4s will do a full ase tale scanto locate the data rows and ignore the N5S,& This situation is called a weakly selecti+e N5S,&0+en using old*fashioned inde.ed se/uential files) it has always een more efficient to readthe entire file and not use an inde. if more than 1U of the records were needed& This iscompounded with Teradata ecause the ;file; is read in parallel instead of all data from asingle file& So) the efficiency percentage is proaly closer to eing less than U of all therows in order to use the N5S,& ,f the SQL does not use a N5S,) you should consider dropping it) due to the fact that the sutale takes up 40R$ space with no enefit to theusers& The Teradata 064L,N is co+ered in this ook and it is the easiest way to determine if 

your SQL is using a N5S,& -urthermore) the optimier will ne+er use a N5S, withoutSTT,ST,CS&

There has een another e+olution in the use of N5S, processing& ,t is called N5S,#itmapping& This means that if a tale has two different N5S, indices and indi+idually theyare weakly selecti+e) ut together they can e itmapped together to eliminate most of thenon*conforming rowsH it will use the two different N5S, columns together ecause theyecome highly selecti+e& Therefore) many times) it is etter to use smaller indi+idual N5S,indices instead of a large composite !more than one column% N5S,&

There is another feature related to N5S, processing that can impro+e access time when a+alue range comparison is re/uested& 2hen using hash +alues) it is impossile to determineany +alue within the range& This is ecause large data +alues can generate small hash+alues and small data +alues can produce large hash +alues& So) to o+ercome the issueassociated with a hashed +alue) there is a range feature called <alue 3rdered N5S,s& t thistime) it may only e used with a four yte or smaller numeric data column& #ased on itsfunctionality) a <alue 3rdered N5S, is perfect for date processing& See the ""L chapter inthis ook for more details on 5S, and N5S, usage&

etermining the "elease o, Your Teradata &ystem/

S0L0CT G -R3$ "#C&"#C,N-3H

Page 13: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 13/401

In,o2ey In,oata

R0L0S0 <8R&9&91&9&99

<0RS,3N 9&91&9&99

Chapter 8: %undamental &-L 'sing &elect

%undamental &tructured -uery Language (&-L)

The access language for all modern relational dataase systems !R"#$S% is StructuredQuery Language !SQL%& ,t has e+ol+ed o+er time to e the standard& The NS, SQL groupdefines which commands and functionality all +endors should pro+ide within their R"#$S&

There are three le+els of compliance within the standard: 0ntry) ,ntermediate and -ull& Thethree le+el definitions are ased on specific commands) data types and functionalities& So) it

is not that a +endor has incorporated some percentage of the commandsH it is more thateach command is categoried as elonging to one of the three le+els& -or instance) mostdata types are 0ntry le+el compliant& et) there are some that fall into the ,ntermediate and-ull definitions&

Since the standard continues to grow with more options eing added) it is difficult to stayfully NS, compliant& dditionally) all R"#$S +endors pro+ide e.tra functionality and optionsthat are not part of the standard& These e.tra functions are called e.tensions ecause theye.tend or offer a enefit eyond those in the standard definition&

 t the writing of this ook) Teradata was fully NS, 0ntry le+el compliant ased on the 1AA8Standards document& NCR also pro+ides much of the ,ntermediate and some of the -ullcapailities& This ook indicates feature y feature which SQL capailities are NS, andwhich are Teradata specific) or e.tensions& ,t is to NCR's enefit to e as compliant as

possile in order to make it easier for customers of other R"#$S +endors to port their datawarehouse to Teradata&

 s indicated earlier) SQL is used to access) store) remo+e and modify data stored within arelational dataase) like Teradata& The SQL is actually comprised of three types of statements& They are: "ata "efinition Language !""L%) "ata Control Language !"CL% and"ata $anipulation Language !"$L%& The primary focus of this ook is on "$L and ""L&#oth ""L and "CL are) for the most part) used for administering an R"#$S& Since theS0L0CT statement is used the +ast ma(ority of the time) we are concentrating on itsfunctionality) +ariations and capailities&

0+erything in the first part of this chapter descries NS, standard capailities of theS0L0CT command& s the statements ecome more in+ol+ed) each capaility will e

designated as either NS, or a Teradata 0.tension&

Page 14: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 14/401

Basic &ELECT Command

5sing the S0L0CT has een descried like playing the game) @eopardy& The answer isthereH all you ha+e to do is come up with the correct /uestion&

The asic structure of the S0L0CT statement indicates which column +alues are desiredand the tales that contain them& To aid in the learning of SQL) this ook will capitalie theSQL keywords& =owe+er) when SQL is written for Teradata) the case of the statement is notimportant& The SQL statements can e written using all uppercase) lowercase or acominationH it does not matter to the Teradata 40&

The S0L0CT is used to return the data +alue!s% stored in the columns named within theS0L0CT command& The re/uested columns must e +alid names defined in the tale!s%listed in the -R3$ portion of the S0L0CT&The following shows the format of a asic S0L0CT statement& ,n this ook) the synta. usese.pressions like: Kcolumn*name !see -igure 1*1% to represent the location of one or morenames re/uired to construct a +alid SQL statement:

S0L0CTO P Kcolumn*name G

  V)Kcolumn*nameO

-R3$ Ktale*name H

The structure of the ao+e command places all keywords on the left in uppercase and the+ariale information such as column and tale names to the right& Like using capital letters)this positioning is to aid in learning SQL& Lastly) although the use of S0L is acceptale inTeradata) with 0CTO in s/uare rackets eing optional) it is not NS, standard&

Lastly) when multiple column names are re/uested in the S0L0CT) a comma must separatethem& 2ithout the separator) the optimier cannot determine where one ends and the ne.tegins&

The following synta. format is also acceptale:

S0L0CTO Kcolumn*name -R3$ Ktale*name H

#oth of these S0L0CT statements produce the output report) ut the ao+e style is easier toread and deug for comple. /ueries& The output display might appear as:

Rows Returned

3column1name4

aaaaaaaaaaaaaaaaaa

cccccccccccccccccc

,n the output) the column name ecomes the default heading for the report& Then) the datacontained in the selected column is displayed once for each row returned&

The ne.t +ariation of the S0L0CT statement returns all of the columns defined in the taleindicated in the -R3$ portion of the S0L0CT&

S0L0CTO G

Page 15: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 15/401

-R3$ Ktale*name H

The output of the ao+e re/uest uses each column name as the heading and the columnsare displayed in the same se/uence as they are defined in the tale& "epending on the toolused to sumit the re/uest) care should e taken) ecause if the returned display is wider than the media !i&e& terminalMB9 and paperM1%H it may e truncated&

 t times) it is desirale to select the same column twice& This is permitted and to accomplishit) the column name is simply listed in the S0L0CT column list more than once& Thistechni/ue might often e used when doing aggregations or calculating a +alue) oth areco+ered in later chapters&

The tale elow is used to demonstrate the results of +arious re/uests& ,t is a small talewith a total of ten rows for easy comparison&-or 0.ample: the ne.t S0L0CT might e used with -igure 8*1) to display the studentnumer) the last name) first name) the class code and grade point for all of the students inthe Student tale:

S0L0CT 5

-R3$ StudentWTale H

3pen tale as spreadsheet &tudent Ta!le 1 contains 06 students

&tudent7I Last7Name %irst7name Class7code 8rade7Pt

P2 %2

'PI N'&I N'&I

1889 4hillips $artin SR &99

18E7 =anson =enry -R 8&BB

87181 Thomas 2endy -R 7&99

81888 2ilson Susie S3 &B9

8E9999 @ohnson Stanley  

8B998 $cRoerts Richard @R 1&A9

881 #ond @immy @R &A

87E8 "elaney "anny SR &

79 Smith ndy S3 8&99

78799 Larkins $ichael -R 9&99

%igure 910 

19 Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

78799 Larkins $ichael -R 9&99

Page 16: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 16/401

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

18E7 =anson =enry -R 8&BB

8B998 $cRoerts Richard @R 1&A9

8E9999 @ohnson Stanley 81888 2ilson Susie S3 &B9

87181 Thomas 2endy -R 7&99

87E8 "elaney "anny SR &

1889 4hillips $artin SR &99

881 #ond @immy @R &A

79 Smith ndy S3 8&99

Notice that @ohnson has /uestion marks in the grade point and class code columns& $ostclient software uses the /uestion mark to represent missing data or an unknown +alue

!N5LL%& $ore discussion on this condition will appear throughout this ook& The other thingto note is that character data is aligned from left to right) the same as we read it and numericis from right to left) from the decimal&

This S0L0CT returns all of the columns e.cept the Student ," from the Student tale:

S0L0CT -irstWname

  )LastWname

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale H

19 Rows returned

%irst7Name Last7Name Class7Code 8rade7Pt

$ichael Larkins -R 9&99

=enry =anson -R 8&BB

Richard $cRoerts @R 1&A9

Stanley @ohnson

Susie 2ilson S3 &B9

2endy Thomas -R 7&99

"anny "elaney SR &

$artin 4hillips SR &99

@immy #ond @R &A

 ndy Smith S3 8&99

There is no short cut for selecting all columns e.cept one or two& lso) notice that thecolumns are displayed in the output in the same se/uence they are re/uested in theS0L0CT statement&

Page 17: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 17/401

Page 18: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 18/401

&tudent7I Last7Name 8rade7Pt

87181 Thomas 7&99

87E8 "elaney &

1889 4hillips &99881 #ond &A

2ithout the 2=0R0 clause) the $4s return all of the rows in the tale to the user& ore andmore Teradata user systems are getting to the point where they are storing illions of rows ina single tale& There must e a +ery good reason for needing to see all of them& $ore simplyput) you will always use a 2=0R0 clause whene+er you want to see only a portion of therows in a tale&

Compound Comparisons (AN # $")

$any times a single comparison is not sufficient to specify the desired rows& To add morefunctionality to the 2=0R0 clause) it is common to use more than one comparison& Themultiple condition checks and column names are not separated y a comma) like columnnames& ,nstead) they must e connected using a logical operator&

The following is the synta. for using the N" logical operator:

S0L0CTO Kcolumn*name

  V)Kcolumn*name O

-R3$ Ktale*name

2=0R0 Kcolumn*name Kcomparison Kdata*+alue AN $" * Kcolumn*name Kcomparison Kdata*+alue H

Notice that the column name is listed for each comparison separated y a logical operatorHthis will e true e+en when it is the same column eing compared twice& The N" signifiesthat each indi+idual comparison on oth sides of the N" must e true& The final result of the comparison must e TR50 for a row to e returned&

3pen tale as spreadsheet This Truth Ta!le illustrates this point using AN

%irst Test "esult AN &econd Test "esult %inal "esult

True True True

True -alse -alse-alse True -alse

-alse -alse -alse

%igure 91@ 

2hen using N") different columns must e used ecause a single column can ne+er contain more than a single data +alue&

Page 19: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 19/401

Therefore) it does not make good sense to issue the ne.t S0L0CT using an N" on thesame column ecause no rows will e+er e returned&

S0L0CT LastWName

  )-irstWName

-R3$ StudentWTale

2=0R0 IradeW4t M &9 AN IradeW4t M 7&9H

No rows found

The ao+e S0L0CT will ne+er return any rows& ,t is impossile for a column to contain morethan one +alue& No student has a &9 grade a+erage N" a 7&9 a+erage& They might ha+eone or the other) ut not oth& ,t might contain one or the other) ut ne+er oth at the sametime& The N" operator indicates oth must e TR50 and should ne+er e used etweentwo comparisons on the same column&

#y sustituting an 3R logical operator for the pre+ious N") rows will now e returned&

The following is the synta. for using 3R:

S0L0CT StudentW,"  )LastWName

  )-irstWName

  )IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t M &9 $" IradeW4t M 7&9 H

8 Rows returned

&tudent7I Last7Name %irst7Name 8rade7Pt

87181 Thomas 2endy 7&991889 4hillips $artin &99

The 3R signifies that only one of the comparisons on each side of the 3R needs to e truefor the entire test to result in a true and the row to e selected&

3pen tale as spreadsheet This Truth Ta!le illustrates the results ,or the $"/

%irst Test "esult $" &econd Test "esult %inal "esult

True True True

True -alse True

-alse True True

-alse -alse -alse

%igure 91 

2hen using the 3R) the same column or different column names may e used& ,n this case)it makes sense to use the same column ecause a row is returned when a column containseither of the specified +alues as opposed to oth +alues as seen with N"&

Page 20: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 20/401

,t is perfectly legal and common practice to comine the N" with the 3R in a singleS0L0CT statement&

The ne.t S0L0CT contains oth an N" as well as an 3R:

S0L0CT G

-R3$ StudentWTale

2=0R0 IradeW4t M &9 $" IradeW4t M 7&9 AN ClassWCode M '-R' H

8 Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

87181 Thomas 2endy -R 7&99

1889 4hillips $artin SR &99

 t first glance) it appears that the comparison worked correctly& =owe+er) upon closer e+aluation it is incorrect ecause 4hillips is a senior and not a freshman&

2hen mi.ing N" with 3R in the same 2=0R0 clause) it is important to know that the N"is e+aluated first& The pre+ious S0L0CT actually returns all rows with a grade point of &9&=ence) 4hillips was returned& The second comparison returned Thomas with a grade point of 7&9 and a class code of '-R'&

2hen it is necessary for the 3R to e e+aluated efore the N" the use of parentheseschanges the priority of e+aluation& different result is seen when doing the 3R first& =ere ishow the statement should e written:

S0L0CT LastWName

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale

2=0R0 (IradeW4t M &9 $" IradeW4t M 7&9% AN ClassWCode M '-R' H

1 Row returned

Last7Name Class7Code 8rade7Pt

Thomas -R 7&99

Now) only Thomas is returned and the output is correct&

Impact o, N'LL on Compound Comparisons

N5LL is an SQL reser+ed word& ,t represents missing or unknown data in a column& SinceN5LL is an unknown +alue) a normal comparison cannot e used to determine whether it istrue or false& ll comparisons of any +alue to a N5LL result in an unknownH it is neither truenor false& The only +alid test for a null uses the keyword N5LL without the normalcomparison symols and is e.plained in this chapter&

2hen a tale is created in Teradata) the default for a column is for it to allow a N5LL +alue toe stored& So) unless the default is o+er*ridden and N5LL +alues are not allowed) it is a goodidea to understand how they work&

Page 21: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 21/401

  S=32 T#L0 command !chapter % can e used to determine whether a N5LL isallowed& ,f the column contains a N3T N5LL constraint) you need not e concerned aoutthe presence of a N5LL ecause it is disallowed&

3pen tale as spreadsheet  This AN Truth Ta!le must no !e used ,or compound tests hen N'LL <alues are alloed/

%irst Test "esult AN &econd Test "esult %inal "esultTrue 5nknown 5nknown

5nknown True 5nknown

-alse 5nknown -alse

5nknown -alse -alse

5nknown 5nknown 5nknown

%igure 91D 

3pen tale as spreadsheet This $" Truth Ta!le must no !e used ,or compoundtests hen N'LL <alues are alloed/

%irst Test "esult $" &econd Test "esult %inal "esult

True 5nknown True

5nknown True True

-alse 5nknown 5nknown

5nknown -alse 5nknown

5nknown 5nknown 5nknown

%igure 91 

-or most comparisons) an unknown !null% is functionally e/ui+alent to a false ecause it isnot a true& Therefore) when using any comparison symol a row is not returned when itcontains a N5LL&

 t the same time) the ne.t S0L0CT does not return @ohnson ecause all comparisonsagainst a N5LL are unknown:

S0L0CT G

-R3$ StudentWTale

2=0R0 IradeW4t M N5LL N" ClassWCode M N5LL H

No rows found<8R: GGG -ailure D1 The user must use ,S N5LL or ,S N3T N5LL to test for N5LL +alues&

 s seen in the ao+e Truth tales) a comparison test cannot e used to find a N5LL&To find a N5LL) it ecomes necessary to make a slight change in the synta. of theconditional comparison& The coding necessary to find a N5LL is seen in the ne.t section&

'sing N$T in &-L Comparisons

Page 22: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 22/401

,t can e fairly straightforward to re/uest e.actly which rows are needed& =owe+er)sometimes rows are needed that contain any +alue other than a specific +alue& 2hen this isthe case) it might e easier to write the S0L0CT to find what is not needed instead of what isneeded& Then con+ert it to return e+erything else& This might e the situation when there are199 potential +alues stored in the dataase tale and AA of them are needed& So) it is easier to eliminate the one +alue than it is to specifically list the desired AA different +aluesindi+idually&

0ither of the ne.t two S0L0CT formats can e used to accomplish the elimination of the one+alue:

S0L0CTO Kcolumn*name

-R3$ Ktale*name

2=0R0 Kcolumn*name N$T Kcomparison Kdata*+alue H

3r 

S0L0CTO Kcolumn*name

-R3$ Ktale*name

2=0R0 N$T (Kcolumn*name Kcomparison Kdata*+alue% H

This second +ersion of the S0L0CT is normally used when compound conditions arere/uired& This is ecause it is usually easier to code the S0L0CT to get what is not wantedand then to enclose the entire set of comparisons in parentheses and put one N3T in frontof it& 3therwise) with a single comparison) it is easier to put N3T in front of the comparisonoperator without re/uiring the use of parentheses&

The ne.t S0L0CT uses the N3T with an N" comparison to display seniors and lower classmen with grade points less than &9:

S0L0CT LastWName

  )-irstWName

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale

 2=0R0 N$T !IradeW4t M &9 N" ClassWCode K 'SR'% H

E Rows returned

Last7Name %irst7Name Class7Code 8rade7Pt

$cRoerts Richard @R 1&A9

=anson =enry -R 8&BB

"elaney "anny SR &

Larkins $ichael -R 9&99

4hillips $artin SR &99

Smith ndy S3 8&99

2ithout using the ao+e techni/ue of a single N3T) it is necessary to change e+eryindi+idual comparison& The following S0L0CT shows this approach) notice the other changenecessary elow) N3T N" is an 3R:

Page 23: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 23/401

Page 24: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 24/401

Last7Name

=anson

,n the earlier Truth tale) the N5LL +alue returned an unknown when checked with acomparison operator& 2hen looking for specific conditions) an unknown was functionallye/ui+alent to a false) ut really it is an unknown&

These two Truth tales can e used together as a tool when mi.ing N" and 3R together inthe 2=0R0 clause along with N3T&

3pen tale as spreadsheet This Truth Ta!le helps to gauge returned ros henusing N$T ith AN/

%irst Test "esult AN &econd Test "esult "esult

N3T!True%M-alse N3T!5nknown%M5nknown -alse

N3T!5nknown%M5nknown N3T!True%M-alse -alse

N3T!-alse%MTrue N3T!5nknown%M5nknown 5nknownN3T!5nknown%M5nknown N3T!-alse%MTrue 5nknown

N3T!5nknown%M5nknown N3T!5nknown%M5nknown 5nknown

%igure 91G 

3pen tale as spreadsheet This Truth Ta!le can !e used to gauge returned roshen using N$T ith $"/

%irst Test "esult $" &econd Test "esult "esult

N3T!True%M-alse N3T!5nknown%M5nknown 5nknown

N3T!5nknown%M5nknown N3T!True%M-alse 5nknown

N3T!-alse%MTrue N3T!5nknown%M5nknown True

N3T!5nknown%M5nknown N3T!-alse%MTrue True

N3T!5nknown%M5nknown N3T!5nknown%M5nknown 5nknown

%igure 91H 

There is an issue associated with using N3T& 2hen a N3T is done on a true condition) theresult is a false& Likewise) the N3T of a false is a true& =owe+er) when a N3T is done withan unknown) the result is still an unknown& 2hene+er a N5LL appears in the data for any of the columns eing compared) the row will ne+er e returned and the answer set will not ewhat is e.pected&

,t takes some practice and consideration when using N3T& nother area where care must etaken is when allowing N5LL +alues to e stored in one or oth of the columns& smentioned earlier) pre+ious +ersions of Teradata had no concept of ;unknown; and if acompare didn't result in a true) it was false& 2ith the emphasis on NS, compatiility theunknown was introduced&

Page 25: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 25/401

,f N5LL +alues are allowed and there is potential for the N5LL to impact the final outcome of compound tests) additional tests are re/uired to eliminate them& 3ne way to eliminate thisconcern is to ne+er allow a N5LL +alue in any columns& =owe+er) this may not eappropriate and it will re/uire more storage space ecause a N5LL can e compressed&Therefore) when a N5LL is allowed) the SQL needs to check for a N5LL&

5sing the e.pression ,S N3T N5LL is the only techni/ue when N5LL is allowed in a columnand the N3T is used with a single or a compound comparison written as:

S0L0CT LastWName) -irstWName

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale

2=0R0 N$T !IradeW4t M &9 N" 8rade7Pt I& N$T N'LL N"

  ClassWCode K 'SR' N" Class7Code I& N$T N'LL% H

D Rows returned

Last7Name %irst7Name Class7Code 8rade7Pt

Larkins $ichael -R 9&99

=anson =enry -R 8&BB

$cRoerts Richard R 1&A9

@ohnson Stanley

"elaney "anny SR &

4hillips $artin SR &99

Smith ndy S3 8&99

Notice that @ohnson came ack this time and did not appear pre+iously ecause of the N5LL+alues&

Later in this ook) the C3L0SC0 will e e.plored as another way to eliminate N5LL +aluesdirectly in the SQL instead of in the dataase&

Multiple alue &earch (IN)

4re+iously) it was shown that adding a 2=0R0 clause to the S0L0CT limited the returnedrows to those that meet the criteria& The ,N comparison is an alternati+e to using one or more 3R comparisons on the same column in the 2=0R0 clause of a S0L0CT statementand the ,N comparison also makes it a it easier to code:

S0L0CTO Kcolumn*name

  V)Kcolumn*name O

-R3$ Ktale*name

2=0R0 Kcolumn*name IN (3<alue1list4) =

The +alue list normally consists of multiple +alues separated y commas& 2hen the +alue inthe column eing compared matches one of the +alues in the list) the row is returned&

Page 26: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 26/401

The following is an e.ample for the alternati+e method when any one of the conditions isenough to satisfy the re/uest using ,N:

S0L0CT LastWName

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t IN (96J @6J 6) =

Row returned

Last7Name Class7Code 8rade7Pt

4hillips SR &99

Thomas -R 7&99

Smith S3 8&99

The use of multiple conditional checks as well as the ,N can e used in the same S0L0CTre/uest& Considerations include the use of N" for declaring that multiple conditions must alle true& 0arlier) we saw the solution using a compound 3R&

'sing N$T IN

 s seen earlier) sometimes the unwanted +alues are not known or it is easier to eliminate afew +alues than to specify all the +alues needed& 2hen this is the case) it is a commonpractice to use the N3T ,N as coded elow&

The ne.t statement eliminates the rows that match and return those that do not match:

S0L0CT LastWName

  )IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t N$T IN !8&9) &9) 7&9% H

E Rows returned

Last7Name 8rade7Pt

$cRoerts 1&A9

=anson 8&BB

2ilson &B9

"elaney &Larkins 9&99

#ond &A

The following S0L0CT is a etter way to make sure that all rows are returned when using aN3T ,N:

S0L0CT LastWName

  )ClassWCode

Page 27: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 27/401

  )IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t N$T IN !8&9) &9) 7&9% $"  IradeW4t ,S N5LL H

D Rows returned

Last7Name Class7Code 8rade7Pt

Larkins -R 9&99

=anson -R 8&BB

$cRoerts @R 1&A9

@ohnson

2ilson S3 &B9

"elaney SR &

#ond @R &A

Notice that @ohnson came ack in this list and not the pre+ious re/uest using the N3T ,N&

ou may e thinking that if the N5LL reser+ed word is used within the ,N list it will co+er thesituation& 5nfortunately) you are forgetting that this comparison always returns an unknown&Therefore) the ne.t re/uest will N0<0R return any rows:

S0L0CT LastWName

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t N$T IN !8&9) &9) 7&9) N'LL% H

No Rows found

$aking this mistake will cause no rows to e+er e returned& This is ecause e+ery time thecolumn is compared against the +alue list the N5LL is an unknown and the Truth taleshows that the N3T of an unknown is always an unknown for all rows&,f you are not sure aout this) do an 064L,N ! chapter % of the N3T ,N and a su/uery tosee that the $4 step will actually e skipped when a N5LL e.ists in the list& There are alsoe.tra $4 steps to compensate for this condition& ,t makes the SQL <0R inefficient&

'sing -uanti,iers ersus IN

There is another alternati+e to using the ,N& Quantifiers can e used to allow for normalcomparison operators without re/uiring compound conditional checks&

The following is e/ui+alent to an ,N:

S0L0CTO Kcolumn*name

  V)Kcolumn*name O

-R3$ Ktale*name

2=0R0 Kcolumn*name ? ANY !K+alue*list%

Page 28: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 28/401

H

This ne.t re/uest uses N instead of ,N:

S0L0CT LastWName

  )ClassWCode

  )IradeW4t-R3$ StudentWTale

2=0R0 IradeW4t ? ANY !8&9) &9) 7&9% H

Row returned

Last7Name Class7Code 8rade7Pt

4hillips SR &99

Thomas -R 7&99

Smith S3 8&99

5sing a /ualifier) the e/ui+alent to a N3T ,N is:

S0L0CTO Kcolumn*name

  V)Kcolumn*name O

-R3$ Ktale*name

2=0R0 Kcolumn*name N$T ? ALL !K+alue*list% H

Notice that like adding a N3T to the compound condition) all elements need to e changedhere as well& To re+erse the M N) it ecomes N3T M LL& This is important) ecause theN3T M N selects all the rows e.cept those containing a N5LL& The reason is that as soonas a +alue is not e/ual to any one of the +alues in the list) it is returned&

The following S0L0CT is con+erted from an earlier N3T ,N:

S0L0CT LastWName

  )IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t N$T ? ALL !8&9) &9) 7&9% H

E Rows returned

Last7Name 8rade7Pt

$cRoerts 1&A9

Larkins 9&99

=anson 8&BB

2ilson &B9

"elaney &

#ond &A

Page 29: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 29/401

Multiple alue "ange &earch (BET:EEN)

The #0T200N comparison can e used as another techni/ue to re/uest multiple +alues for a column that are all in a specific range& ,t is easier than writing a compound 3R comparisonor a long +alue list of se/uential numers when using the ,N&

This is a good time to point out that this chapter is incrementally adding new ways tocompare for +alues within a 2=0R0 clause& =owe+er) all of these techni/ues can e usedtogether in a single 2=0R0 clause& 3ne method does not eliminate the aility to use one or more of the others using logical operators etween each comparison&

The ne.t S0L0CT shows the synta. format for using the #0T200N:

S0L0CTO Kcolumn*name

  V)Kcolumn*name O

-R3$ Ktale*name

2=0R0 Kcolumn*name BET:EEN 3lo1<alue4 AN 3high1<alue4 =

The first and second +alues specified are inclusi+e for the purposes of the search& ,n other words) when these +alues are found in the data) the rows are included in the output&

 s an e.ample) the following code returns all students whose grade points of 8&9) 7&9 and all+alues etween them:

S0L0CT IradeW4t

-R3$ StudentWTale

2=0R0 IradeW4t BET:EEN 96 and 6 =

D Rows returned

8rade7Pt

&99

8&BB

7&99

&B9

&A

&

8&99

Notice that due to the inclusi+e nature of the #0T200N) oth 8&9 and 7&9 were included inthe answer set& The first +alue of the #0T200N must e the lower +alue) otherwise) no rowswill e returned& This is ecause it looks for all +alues that are greater or e/ual to the first+alue and less than or e/ual to the second +alue&

  #0T200N can also e used to search for character +alues& 2hen doing this) care muste taken to insure that rows are recei+ed with the +alues that are needed& The system canonly compare character +alues that are the same length& So) if one column or +alue isshorter than the other) the shortest will automatically e padded with spaces out to the samelength as the longer +alue&

Page 30: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 30/401

Comparing 'C' and 'CL,-3RN,' ne+er constitutes a match& ,n reality) the dataase iscomparing 'C' with 'CL,-3RN, ' and they are not e/ual& Sometimes) it is easier to usethe L,J0 comparison operator which will e co+ered in the ne.t section& lthough) easier tocode) it does not always mean faster to e.ecute& There is always a trade*off to consider&

The ne.t S0L0CT finds all of the students whose last name starts with an L:

S0L0CT LastWName-R3$ StudentWTale

2=0R0 LastWName BET:EEN KLK AN KLK H

1 Row returned

Last7Name

Larkins

,n reality) the 2=0R0 could ha+e used #0T200N 'L' and '$' as long as no student's lastname was '$'& The data needs to e understood when using #0T200N for character comparisons&

Character &tring &earch (LI2E)

The L,J0 is used e.clusi+ely to search for character data strings& The ma(or differenceetween the L,J0 and the #0T200N is that the #0T200N looks for specific +alues withina range& The L,J0 is normally used when looking for a string of characters within a column&

 lso) the L,J0 has the capaility to use ;wildcard; characters&

3pen tale as spreadsheet The ildcard characters are/

:ildcardsym!ol

:hat it does

 W !underscore% matches any single character) ut a character must epresent

U !percent sign% matches any single character) a series of characters or theasence of characters

%igure 9106 

The ne.t S0L0CT finds all rows that ha+e a character string that egins with 'Sm':

S0L0CT G

-R3$ StudentWTale

2=0R0 LastWName LI2E KsmK =

1 Row returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

79 Smith ndy S3 8&99

The fact that the 's' is in the first position dictates its location in the data& Therefore) the 'm'must e in the second position& Then) the 'U' indicates that any numer of characters!including none% may e in the third and suse/uent positions& So) if the 2=0R0 clause

Page 31: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 31/401

contained: L,J0 'Usm') it only looks for strings that end in ;S$&; 3n the other hand) if it werewritten as: L,J0 'UsmU') then all character strings containing ;sm; anywhere are returned&

 lso) rememer that in Teradata mode) the dataase is not case sensiti+e& =owe+er) in NS,mode) the case of the letters must match e.actly and the pre+ious re/uest must e writtenas 'SmU' to otain the same result& Care should e taken regarding case when working in

 NS, mode& 3therwise) case does not matter&

The 'W' wildcard can e used to force a search to a specific location in the character string& nything in that position is considered a match ut a character must e in there&

The following S0L0CT uses a L,J0 to find all last names with an ;; in the second positionof the last name:

S0L0CT G

-R3$ StudentWTale

2=0R0 LastWName L,J0 !'WaU'% H

8 Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

78799 Larkins $ichael -R 9&99

18E7 =anson =enry -R 8&BB

,n the ao+e e.ample) the ;W; allows any character in the first position) ut re/uires acharacter to e there&

The keywords LL) N) or S3$0 can e used to further define the +alues eing searched&They are the same /uantifiers used with the ,N& =ere) the /uantifiers are used to e.tend thefle.iility of the L,J0 clause&

Normally) the L,J0 will look for a single set of characters within the data& Sometimes) that isnot sufficient for the task at hand& There will e times when the characters to search are notconsecuti+e) nor are they in the same se/uence&

The ne.t S0L0CT returns rows with oth an 's' and an 'm' ecause of the LL&

FG set session transaction Teradata GF

S0L0CT G

-R3$ StudentWTale

2=0R0 LastWName LI2E ALL (K&KJ KmK) H

Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

8B998 $cRoerts Richard @R 1&A9

87181 Thomas 2endy -R 7&99

79 Smith ndy S3 8&99

,t does not matter if the 's' appears first or the 'm' appears first) as long as oth are containedin the string&

Page 32: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 32/401

#elow) NS, is case sensiti+e and only 1 row returns due to the fact that the 'S' is uppercase)so Thomas and $cRoerts are not returned:

FG set session transaction NS, GF

S0L0CT G

-R3$ StudentWTale

2=0R0 LastWName L,J0 LL !'USU') 'UmU'% H

1 Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

79 Smith ndy S3 8&99

,f) in the ao+e statement) the LL /uantifier is changed to N !NS, standard% or S3$0!Teradata e.tension%) then a character string containing either of the characters) 's' or 'm') ineither order is returned& ,t uses the 3R comparison&

This ne.t S0L0CT returns any row where the last name contains either an 's' or an 'm':

FG set session transaction NS, in #T0Q GF

S0L0CT G

-R3$ StudentWTale

2=0R0 LastWName LI2E ANY (KsKJ KmK) H

B Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

78799 Larkins $ichael -R 9&99

18E7 =anson =enry -R 8&BB

8B998 $cRoerts Richard @R 1&A9

8E9999 @ohnson Stanley

81888 2ilson Susie S3 &B9

87181 Thomas 2endy -R 7&99

79 Smith ndy S3 8&99

1889 4hillips $artin SR &99

 lways e aware of the issue regarding case sensiti+ity when using NS, $ode& ,t willnormally affect the numer of rows returned and usually reduces the numer of rows&

There is a specialty operation that can e performed in con(unction with the L,J0& Since thesearch uses the ;W; and the ;U; as wildcard characters) how can you search for actual datathat contains a ;W; or ;U; in the data

Now that we know how to use the wildcard characters) there is a way to take away thespecial meaning and literally make the wildcard characters an 'W' and a 'U'& That is thepurpose of 0SC40& ,t tells the 40 to not match anything) ut instead) match the actualcharacter of 'W' or 'U'&

Page 33: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 33/401

The ne.t S0L0CT uses the 0SC40 to find all tale names that ha+e a ;W; in the B th positionof the name from the "ata "ictionary&

S0L0CT Talename

-R3$ "#C&tales

2=0R0 Talename LI2E (K7 7 7 7 7 7 7 7K) E&CAPE KK

  N" "ataasename M 'mikel' H

8 Rows returnedTa!lename

StudentWTale

StudentWCourseWTale

,n the ao+e output) the only thing that matters is the 'W' in position eight ecause of the firstse+en 'W' characters are still wildcards&

eri<ed Columns

The ma(ority of the time) columns in the S0L0CT statement e.ist within a dataase tale&=owe+er) sometimes it is more ad+antageous to calculate a +alue than to store it&

 n e.ample might e the salary& ,n the employee tale) we store the annual salary& =owe+er)a re/uest comes in asking to display the monthly salary& "oes the tale need to e changedto create a column for storing the monthly salary $ust we go through and update all of therows !one per employee% and store the monthly salary into the new column (ust so we canselect it for display

The answer is no) we do not need to do any of this& ,nstead of storing the monthly salary) we

can calculate it from the annual salary using di+ision& ,f the annual salary is di+ided y 18!months per year%) we ;deri+e; the monthly salary using mathematics&

3pen tale as spreadsheet Chart o, AN&I operands ,or math operations/

$perator $peration per,ormed

!% parentheses) !all math operations in parentheses done first%

GG e.ponentiation) !19GG18 deri+es 1)999)999)999)999 or 1 trillion%

G multiplication) !19G18 deri+es 189%

F di+ision) !19F18 deri+es 9) oth are integers and truncation of  decimal occurs%

X addition) !19X18 deri+es 88%

* sutraction) !19Y18 deri+es *8) since 18 is greater than 19 andnegati+e +alues are allowed%

%igure 9100 

Page 34: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 34/401

These math functions ha+e a priority associated with their order of e.ecution when mi.ed inthe same formula& The se/uence is asically the same as their order in the chart& lle.ponentiation is performed first& Then) all multiplication and di+ision is performed and lastly)all addition and sutraction is done& 2hene+er two different operands are at the samepriority) like addition and sutraction) they are performed ased on their appearance in thee/uation from left to right&

 lthough the ao+e is the default priority) it can e o+er*ridden within the SQL& Normally ane/uation like 8X7G yields 88 as the answer& This is ecause the 7G M 89 is done first andthen the 8 is added to it& =owe+er) if it is written as !8X7%G) now the answer ecomes 9!8X7MEGM9%&

The following S0L0CT shows these and the results of an assortment of mathematics:

S0L0CT 8X7G) !8X7%G

  )8X7F) !8X7%F

  )8X7&9F) !8X7&9%F

  )19GGA H

1 Row Returned8X7G !8X7%G 8X7F !8X7%F 8X7&9F !8X7&9%F 19GGA

88 9 8 1 8&B 1&8 199999999Note/ starting with integer +alues) as in the ao+e) the answer is an integer& ,f decimals areused) the result is a decimal answer& 3therwise) a con+ersion can e used to change thecharacteristics of the data efore eing used in any calculation& dding the decimal makes adifference in the precision of the final answer& So) if the SQL is not pro+iding the answer e.pected from the data) con+ert the data first !CST function later in this ook%&

The ne.t S0L0CT shows how the SQL can e written to implement the earlier e.ample withannual and monthly salaries:

S0L0CT salary !format 'ZZZ)ZZA&AA'%  )salaryF18 !format 'Z)ZZA&AA'%

-R3$ 4ayWTale H

8 Rows returned

salary salary#09

7B)987&99 7)998&99

19)B99&99 A99&99Since the column name is the default column heading) the deri+ed column is calledsalaryF18) which is not proaly what we wish to see there& The ne.t section co+ers the

usage of an alias to temporarily change the name of a column during the life of the SQL&

"eri+ed data can e used in the 2=0R0 clause as well as the S0L0CT& The following SQLwill only return the columns when the monthly salary is greater than [1)999&99:

S0L0CT salary !format 'ZZZ)ZZA&AA'%

  )salaryF18 !format 'Z)ZZA&AA'%

-R3$ 4ayWTale

2=0R0 salaryF18 1999 H

Page 35: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 35/401

1 Row returned

salary salary#09

7B)987&99 7)998&99

Teradata contains se+eral functions that allow a user to deri+e data for usiness andengineering& This is a chart of those Teradata arithmetic) trigonometric and hyperolic mathfunctions:

3pen tale asspreadsheet$perator

$peration per,ormed

$3" x   $odulo returns the remainder from a di+ision !1 mod 8deri+es 1) as the remainder of di+ision) 8 goes into 1) 9 timeswith a remainder of 1& Then) 8 mod 19 deri+es 8) 19 goes into8) 9 times with a remainder of 8%& $3" always returns 9 thru.*1& s such) $3" 8 returns 9 for e+en numers and 1 for oddH $3" D can e used to determine the day of the weekHand $3" 19) $3" 199) $3" 1999) etc can e used to shiftthe decimal of any numer to the left y the numer of eroesin the $3" operator&

 #S! x %  solute +alue) the asolute +alue of a negati+e numer isthe some numer as a positi+e .& !#S!19Y18%M8%

064! x % 0.ponentiation) e raised to a power) !064!19% deri+es8&898E7EDA7B9ED0997%

L3I! x % Logarithm calculus function) !L3I!19% deri+es the +alue1&99999999999990999%

LN! x % Natural logarithm) !LN!19% deri+es the +alue8&98B9A8AA790999%

SQRT! x % S/uare root) !SQRT!19% deri+es the +alue&1E88DDEE91EBB0999%

C3S! x % Takes an angle in radians (x % and returns the ratio of twosides of a right triangle& The ratio is the length of the sidead(acent to the angle di+ided y the length of the hypotenuse&The result lies in the range *1 to 1) inclusi+e where x   is any+alid numer e.pression that e.presses an angle in radians&

S,N! x % Takes an angle in radians (x % and returns the ratio of twosides of a right triangle& The ratio is the length of the sideopposite to the angle di+ided y the length of the hypotenuse&The result lies in the range *1 to 1) inclusi+e where x   is any

+alid numer e.pression that e.presses an angle in radians&TN! x % Takes an angle in radians (x % and returns the ratio of two

sides of a right triangle& The ratio is the length of the sideopposite to the angle di+ided y the length of the sidead(acent to the angle where x  is any +alid numer e.pressionthat e.presses an angle in radians&

 C3S! x % Returns the arccosine of x & The arccosine is the angle whosecosine is x  where x  is the cosine of the returned angle& The+alues of x  must e etween *1 and 1) inclusi+e& The returned

Page 36: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 36/401

3pen tale asspreadsheet$perator

$peration per,ormed

angle is in the range 9 to radians) inclusi+e&

 S,N! x % Returns the arcsine of ! x)& The arcsine is the angle whosesine is x  where x  is the sine of the returned angle& The +aluesof x  must e etween *1 and 1) inclusi+e& The returned angle

is in the range F8 to F8 radians) inclusi+e&

 TN! x % Returns the arctangent of ! x)& The arctangent is the anglewhose tangent is ar g& The returned angle is in the range F8 to

F8 radians) inclusi+e&

 TN8 ! x,y % Returns the arctangent of the specified (x,y) coordinates& Thearctangent is the angle from the .*a.is to a line contained theorigin!9)9% and a point with coordinates !.)y%& The returned

angle is etween and radians) e.cluding & positi+e resultrepresents a counterclockwise angle from the .*a.is where anegati+e result represents a clockwise angle& The TN8!.)y%e/uals TN!yF.%) e.cept that . can e 9 in TN8!.)y% and .cannot e 9 in TN!yF.% since this will result in a di+ide yero error& ,f oth . and y are 9) an error is returned&

C3S=! x % Returns the hyperolic cosine of ! x)  where  x   is any realnumer&

S,N=! x % Returns the hyperolic sine of ! x) where x  is any real numer&

TN=! x % Returns the hyperolic tangent of ! x)  where arg   is any realnumer&

 C3S=! x % Returns the in+erse hyperolic cosine of ! x)& ,t is the +alue

whose hyperolic cosine is a numer so that  x   is any realnumer e/ual to) or greater than) 1&

 S,N=! x % Returns the in+erse hyperolic sine of ! x)& The in+ersehyperolic sine is the +alue whose hyperolic sine is anumer so that x  is any real numer&

 TN=! x % Returns the in+erse hyperolic tangent of ! x)& ,t is the +aluewhose hyperolic tangent is a numer so that  x   is any realnumer etween 1 and *1) e.cluding 1 and *1%&

%igure 9109 

Some of these functions are demonstrated elow and throughout this ook& =ere they are

also using alias names for the columns& Their application will e specific to the type of application eing written& ,t is not the intent of this ook to teach the meaning and use inengineering and trigonometry) ut more to educate regarding their e.istence&

Creating a Column Alias Name

Since the name of the selected column or deri+ed data formula appears as the heading for the column) it makes for strange looking results& To make the output look etter) it is a good

Page 37: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 37/401

idea to use an alias to dress up the heading name used in the output& #esides making theoutput look etter) an alias also makes the SQL easier to write ecause the new columnname can e used anywhere in the SQL statement&

A&

Compliance: NS,

The pre+ious S0L0CT used salaryF18) which is proaly not what we wish to see in theheading& Therefore) it is preferale to alias the column within the e.ecution of the SQL& Thismeans that a temporary name is assigned to the selected column for use only in thisstatement&

To alias a column) use an S and any legal Teradata name after the real column namere/uested or math formula using the following techni/ue:

S0L0CT salary A& Annual7salary

  )salaryF18 A& Monthly7salary

-R3$ 4ayWTale H

8 Rows returned

Annual7salary Monthly7salary

7B987&99 7998&99

19B99&99 A99&99

3nce the alias name has een assigned) it is literally the name of the column for the life of the SQL statement&

The ne.t re/uest is a +alid e.ample of using of the alias in the 2=0R0 clause:

S0L0CT salary !format '[[[)[[A&AA'% S annualWsalary  )salaryF18 !format '[[[)[[A&AA'% A& monthly7salary

-R3$ 4ayWTale

2=0R0 monthly7salary  1999 H

1 Row returned

annual7salary monthly7salary

[7B)987&99 [7)998&99

The math functions are +ery helpful for calculating and e+aluating characteristics of the data&

The following e.amples incorporate most of the functions to demonstrate their operationalfunctionality&

The ne.t S0L0CT uses literals and aliases to show the data eing input and results for eachof the most common usiness applicale operations:

S0L0CT 899F199 S "i+899

  )897 $3" 199 S Last8

  )8 $3" 8 S 0+en

Page 38: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 38/401

  ) $3" 8 S 3dd

  )#S!1% S 2as4ositi+e

  )#S!*1% S 4ositi+eNow

  )SQRT!7% S S/Root H

1 Row returnedi<966 Last9 E<en $dd :asPositi<e Positi<eNo &

8 7 9 1 1 1 8&

The output of the S0L0CT shows some interesting results& The di+ision is easyH we learnedthat in elementary school& The first $3" 199 results in 7) ecause the result of the di+isionis 8) ut the remainder is 7 !897 * 899 M 7%& $3" 199 can result in any +alue etween 9and AA& ,n reality) the $3" 199 mo+es the decimal point two positions to the left& 3n theother hand) the $3" 8 will always e 9 for e+en numers and 1 for odd numers& The #Salways returns the positi+e +alue of any numer and lastly) 8 is the s/uare root of 7&

$any of these will e incorporated into SQL throughout this ook to demonstrate additionalusiness applications&

NAME

Compliance: Teradata 0.tension

4rior to the S ecoming the NS, standard) Teradata used N$0" as the keyword toestalish an alias& lthough oth currently work) it is strongly suggested that an S e usedfor compatiility& lso) as hard as it is to elie+e) , ha+e heard that N$0" may not work infuture releases&

The following is the same S0L0CT as seen earlier) ut here it uses the N$0" instead of 

the S:S0L0CT salary (NAME Annual7salary)

  )salaryF18 (NAME Monthly7salary)

-R3$ 4ayWTale H

8 Rows returned

Annual7salary Monthly7salary

7B987&99 7998&99

19B99&99 A99&99

Naming con<entions

2hen creating an alias only +alid Teradata  naming characters are allowed& The aliasecomes the name of the column for the life of the SQL statement& The only difference isthat it is not stored in the "ata "ictionary&

The charts elow list the +alid characters to use and then the rules !on the left% to followwhen NS, compliance is desired& lso listed are the more fle.ile Teradata !on the right%allowale characters and e.tended character sets with its rules&

Page 39: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 39/401

3pen tale as spreadsheet Chart o, alid Characters ,or AN&I and Teradata/

AN&I Characters Alloed Teradata Characters Alloed

!up to 1B in a single name% !up to 9 in a single name%

  through Z through Z and a through

9 through A 9 through A

 W !underscore F underline% W !underscore F underline%

\ !octathrope F pound sign F numer sign%

[ !dollar sign F currency sign%

%igure 910@ 

3pen tale as spreadsheet Chart o, AN&I and Teradata Naming Con<entions

AN&I "ules ,or columnnames

Teradata "ules ,or column names

$ust e entirely in upper case

Can e all upper) all lower or a mi.ture of case usingany of these characters

$ust start with throughZ

Can start with any +alid character 

$ust end withunderscore W 

Can end with any +alid character 

%igure 910 

Teradata uses all of the NS, characters as well as the additional ones listed in the ao+echarts&

Brea+ing Con<entions

,t is not recommended to reak these con+entions& =owe+er) sometimes it is necessary or desirale to use non*standard characters in a name& lso) sometimes words ha+e een usedas tale or column names and then in a later release) the name ecomes a reser+ed word&There needs to e a techni/ue to assist you when either of these re/uirements ecomesnecessary&

The techni/ue uses doule /uotes !;% around the name& This techni/ue tells the 40 that theword is not a reser+ed word and makes it a +alid name& This is the only place that Teradatauses a doule /uote instead of a single /uote !'%&

 s an e.ample) the pre+ious S0L0CT has een modified to use doule /uotes !;% instead of N$0":

S0L0CT salary ;Annual salary;

  )salaryF18 ;Monthly salary;

-R3$ 4ayWTale

3R"0R # ;nnual Salary; H

Page 40: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 40/401

8 Rows returned

Annualsalary

Monthlysalary

19B99&99 A99&99

7B987&99 7998&99 lthough it is not o+ious due to the underlining) the column heading for the first column is nnual Salary) including the space& space is not a +alid naming character) ut this is thecolumn name and it is +alid ecause of the doule /uotes& This can e seen in the 3R"0R# where it uses the column name& The ne.t section pro+ides more details on the use of 3R"0R #&

$"E" BY

The Teradata $4s generally ring data ack randomly unless the user specifies a sort& Theaddition of the 3R"0R # re/uests a sort operation to e performed& The sort arranges therows returned in ascending se/uence unless you specifically re/uest descending& 3ne or more columns may e used for the sort operation& The first column listed is the ma(or sortse/uence& ny suse/uent columns specified are minor sort +alues in the order of their appearance in the list&

The synta. for using an 3R"0R #:

S0L0CTO Kcolumn*name

  V)Kcolumn*nameO

-R3$ Ktale*name

$"E" BY 3column1name4 3relati<e1column1num!er4 * O A&C E&C

  …J 3column1name4 3relati<e1column1num!er4 * O A&C E&C  H

,n Teradata) if the se/uence of the rows eing displayed is important) then an 3R"0R #

should e used in the S0L0CT& $any other dataases store their data se/uentially y the+alue of the primary key& s a result) the data will appear in se/uence when it is returned& Toe faster) Teradata stores it differently&

Teradata organies data rows in ascending se/uence on disk ased on a row ," +alue) notthe data +alue& This is the same +alue that is calculated to determine which $4 should eresponsile for storing and retrie+ing each data row&

2hen the 3R"0R # is not used) the data will appear +aguely in row hash se/uence and isnot predictale& Therefore) it is recommended to use the 3R"0R # in a S0L0CT or thedata will come ack randomly& Rememer) e+erything in Teradata is done in parallel) thisincludes the sorting process&

The ne.t S0L0CT retrie+es all columns and sorts y the Irade point a+erage:S0L0CT G

-R3$ StudentWTale

2=0R0 IradeW4t

$"E" BY 8rade7Pt H

7 Rows returned

Page 41: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 41/401

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

87E8 "elaney "anny SR &

81888 2ilson Susie S3 &B9

881 #ond @immy @R &A87181 Thomas 2endy -R 7&99

Notice that the default se/uence for the 3R"0R # is ascending !SC%) lowest +alue tohighest& This can e o+er*ridden using "0SC to indicate a descending se/uence as shownusing the following S0L0CT:

S0L0CT G

-R3$ StudentWTale

2=0R0 IradeW4t

3R"0R # IradeW4t E&CH

7 Rows returned

&tudent7I Last7Name %irst7Name Class7Code 8rade7Pt

87181 Thomas 2endy -R 7&99

881 #ond @immy @R &A

81888 2ilson Susie S3 &B9

87E8 "elaney "anny SR &

 s an alternati+e to using the column name in an 3R"0R #) a numer can e used& Thenumer reflects the column's position in the S0L0CT list& The ao+e S0L0CT could also ewritten this way to otain the same result:

S0L0CT G

-R3$ StudentWTale

2=0R0 IradeW4t

$"E" BY D E&C =

,n this case) the grade point column is the fifth column in the tale definition ecause of itslocation in the tale and the S0L0CT uses G for all columns& This adds fle.iility to the writingof the S0L0CT& =owe+er) always watch out for the aility words) like fle.iility ecause itadds another aility word: responsiility& 2hen using the column numer) if the column thatis used for the sort is mo+ed to another location in the select list) a different column is nowused for the sort& Therefore) it is important to e responsile to change the list and thenumer in the 3R"0R #&

$any times it is necessary that the +alue in one column needs to e sorted within these/uence of a second column& This techni/ue is said to ha+e a ma(or sort column or key andone or more minor sort keys&

The first column listed in the 3R"0R # is the ma(or sort key& Likewise) the last columnlisted is the most minor sort key within the se/uence& The minor keys are referred to aseing sorted within the ma(or sort key& dditionally) some columns can ascend while othersdescend&

Page 42: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 42/401

This S0L0CT sorts two different columns: the last name !minor sort% ascending !SC%)within the class code !ma(or sort% descending !"0SC%:

S0L0CT LastWName

  )ClassWCode

  )IradeW4t

-R3$ StudentWTale

$"E" BY 9 E&CJ 0 H

19 Rows returned

Last7Name Class7Code 8rade7Pt

"elaney SR &

4hillips SR &99

Smith S3 8&99

2ilson S3 &B9

#ond @R &A

$cRoerts @R 1&A9

=anson -R 8&BB

Larkins -R 9&99

Thomas -R 7&99

@ohnson

Notice that in the ao+e statement) the 3R"0R # uses relati+e column numers instead of column names to define the sort& The numers 8 and 1 were used instead of ClassWCodeand LastWName& 2hen you select columns and then use numers in the sort) the numers

relate to the order of the columns after the keyword S0L0CT& 2hen you S0L0CT G !allcolumns% then the sort numer reflects its position within the tale&

 n additional capaility of Teradata is that a column can e used in the 3R"0R # that isnot selected& This is possile ecause the dataase uses a tag sort for speed and fle.iility&,n other words) it uilds a tag area that consists of all the columns specified in the 3R"0R# as well as the columns that are eing selected&

3pen tale as spreadsheet  This diagram shos the layout o, a ro in &P$$L used ith an$"E" BY/

Tagcolumn1

…TagcolumnN

 $4\ Selectcolumn1

Selectcolumn8

…SelectcolumnN

%igure 910D 

 lthough it can sort on a column that is not selected) the se/uence of the output may appear to e completely random& This is due to the sorted +alue not seen in the display&

 dditionally) within a Teradata session the user can re/uest a Collation Se/uence and aCode Set for the system to use& #y re/uesting a Collation Se/uence of 0#C",C) the sortputs the data into the proper se/uence for the ,#$ mainframe system& Therefore) is theautomatic default code set when connecting from the mainframe&

Page 43: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 43/401

Likewise) if a user were e.tracting to a 5N,6 computer) the normal code set is CS,,&=owe+er) if the file is transferred from 5N,6 to a mainframe and con+erted there) it is in thewrong se/uence& 2hen it is known ahead of time that the file will e used on a mainframeut e.tracted to a different computer) the Collation Se/uence can e set to 0#C",C&Therefore) when the file code set is con+erted) the file is in the correct se/uence for themainframe without doing another sort&

Like the Collation Se/uence) the Code Set can also e set& So) a file can e in 0#C",Cse/uence and the data in SC,, or sorted in SC,, se/uence with the data in 0#C",C& Thefinal use of the file needs to e considered when making this choice&

T$P "os $ption

2ith Release <8RE) Teradata pro+ides the NS, capaility of using T34 to limit the outputrows to a specific numer of the percentage for the total numer of rows in an orderedanswer set&

The synta. for using T34:

S0L0CTO T34 P Kinteger*+alue Kdecimal*+alue 40RC0NT O 2,T= T,0S O

  Kcolumn*list

-R3$ Ktale*name H

The T34 re/uest follows the S0L0CT keyword& Then a numer appears which indicateshow many rows are returned to the client& This numer can e either an integer or a decimalnumer& =owe+er) Teradata cannot return a portion of a rowH it must return entire rows&Therefore) the decimal numer only is allowed when the option 40RC0NT specification isused& ,n other words) you could ring ack & or one*half percent of the rows in the tale&

The last option that can e used with T34 is 2,T= T,0S& This notation means that if a row isto e included ut the ne.t row or series of rows ha+e the same e.act +alue as the last row)than the additional rows will also e included in the output e+en though it e.ceeds thenumer of rows re/uested&

This S0L0CT is the same as pre+iously shown ut uses the T34 to limit the output:

S0L0CT T34 LastWName

  )ClassWCode) IradeW4t

-R3$ StudentWTale

3R"0R # 8 "0SC) 1 H

Rows returned

Last7Name Class7Code 8rade7Pt

"elaney SR &4hillips SR &99

Smith S3 8&99

,f the 2,T= T,0S option is used) than an e.tra row returns ecause there are 8 with S3:

S0L0CT T34 2,T= T,0S LastWName

  )ClassWCode) IradeW4t

Page 44: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 44/401

-R3$ StudentWTale

3R"0R # 8 "0SC) 1 H

7 Rows returned

Last7Name Class7Code 8rade7Pt

"elaney SR &

4hillips SR &99

Smith S3 8&99

:ilson  &$  @G6 

#ecause of the location of T34 within the S0L0CT and the elimination of some of the rows)it is not compatile with the following SQL constructs presented later in this ook:

,ST,NCT > chapter 1 

Q5L,- > chapter 19 !replaces Q5L,- with RNJ and R32WN5$#0R%S$4L0 > chapter 19 2,T= and 2,T= # > chapter 1D 

I&TINCT %unction

 ll of the pre+ious operations of the S0L0CT returned a row from a tale ased on itse.istence in a tale& s a result) if multiple rows contain the same +alue) they all aredisplayed&

Sometimes it is only necessary to see one of the +alues) not all& ,nstead of contemplating a2=0R0 clause to accomplish this task) the ",ST,NCT can e added in the S0L0CT toreturn uni/ue +alues y eliminating duplicate +alues&

The synta. for using ",ST,NCT:

S0L0CT I&TINCT Kcolumn*name …

) Kcolumn*name…

 O-R3$ Ktale*name H

The ne.t S0L0CT uses ",ST,NCT to return only uni/ue row +alues:

S0L0CAT I&TINCT ClassWcode

-R3$ studentWtale

3R"0R # classWcodeH

Rows Returned

Class7code

-R

@R

S3

SR

There are a couple noteworthy situations in the ao+e output& -irst) although there are threefreshman) two sophomores) two (uniors) two seniors and one row without a class code) only

Page 45: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 45/401

one output row is returned for each of these +alues& Lastly) the N5LL is considered a uni/ue+alue whether there is one row or multiple rows containing it& So) it is displayed one time&

The main considerations for using ",ST,NCT) it must:1& ppear only once8& pply to all columns listed in the S0L0CT to determine uni/ueness& ppear efore the first column name

The following S0L0CT uses more than one column with a ",ST,NCT:

S0L0CT I&TINCT classWcode) gradeWpt

-R3$ studentWtale

3R"0R # classWcode) gradeWptH

19 Rows Returned

class7code grade7pt

-R 9&99-R 8&BB

-R 7&99

@R 1&A9

@R &A

S3 8&99

S3 &B9

SR &99

SR &

The ",ST,NCT in this S0L0CT returned all ten rows of the tale& This is due to the fact thatwhen the class code and the grade point are comined for comparison) they are all uni/ue&The only potential for a duplicate e.ists when two students in the same class ha+e the samegrade point a+erage& Therefore) as more and more columns are listed in a S0L0CT with a",ST,NCT) there is a greater opportunity for more rows to e returned due to a higher likelihood for uni/ue +alues&

,f) when using ",ST,NCT) spool space is e.ceeded) see chapter   and the use of theIR354 # +ersus ",ST,NCT for eliminating duplicate rows& ,t may sol+e the prolem andthat chapter tells the reason for it&

Chapter @/ $n1line ;ELP and &;$: CommandsHELP commandsThe Teradata Database offers several types of help using an interactive client. For convenience, this reduces or eliminates the need to look information up in a hardcopy

Page 46: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 46/401

manual or on a D!"#$. Therefore, using the help and sho% operations in this chapter can save you a large amount of time and make you more productive. &ince Teradataallo%s you to organi'e database ob(ects into a variety of locations, sometimes you need todetermine %here certain ob(ects are stored and other detail information about them.

#pen table as spreadsheet This chart is a list of available HELP commands on #b(ects)

HELP D*T*+*&Edatabase!name-

Displays the names of all the tables /T0, vie%s /10, macros/$0, and triggers /20 stored in a database and user %rittentable comments

HELP 3&E" user!name-

Displays the names of all the tables /T0, vie%s /10, macros/$0, and triggers /20 stored in a user area and user %rittentable comments

HELP T*+LE table!name-

Displays the column names, type identifier, and any user %ritten comments on the columns %ithin a table.

HELP 1#L*T4LET*+LE

Displays the names of all 1olatile temporary tables active for the user session.

HELP 14E5 vie%!name-

Displays the column names, type identifier, and any user %ritten comments on the columns %ithin a vie%.

HELP $*"# macro!name-

Displays the characteristics of parameters passed to it ate6ecution time.

HELP P"#ED3"Eprocedure!name-

Displays the characteristics of parameters passed to it ate6ecution time.

HELP T"422E" trigger!name-

Displays details created for a trigger, like action time andse7uence.

HELP #L3$8 table!

name-.9 HELP #L3$8 vie%!name-.9 HELP #L3$8table!name-.column!name-, .:

Displays detail data describing the column level

characteristics.

Figure ;!<To see the database ob(ects stored in a Database or 3ser area, either of the follo%ingHELP commands may be used)HELP D*T*+*&E $y=D+

#r 

HELP 3&E" $y=3ser > "o%s "eturned

Table?1ie%?$acro name @ind omment

employee T T A Table

Page 47: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 47/401

Table?1ie%?$acro name @ind omment

%ith <ro% per  employee

employee=v 1 1 A 1ie%for accessingEmployeeTable

Employee=m< $ $ A$acro toreport onEmployeeTable

Employee=Trig 2 2 A

Trigger toupdateEmployeeTable

&ince Teradata considers a database and a user to be e7uivalent, both can store the sametypes of ob(ects and therefore, the t%o commands produce similar output. 8o% that you have seen the names of the ob(ects in a database or user area, further investigation displays the names and the types of columns contained %ithin the ob(ect.For tables and vie%s, use the follo%ing commands)HELP T*+LE $y=Table B "o%s "eturned

olumn 8ame Type omment 8ullable Format Title

olumn< 4 Thiscolumn isan integer 

C !/<0

olumnG 4G Thiscolumn isa smallint

C !/0

olumn; 4< Thiscolumn is

a byteint

C !/;0

olumn> F Thiscolumn isa fi6edlength

C I/G0

olumn 1 Thiscolumn isa variable

C I/G0

Page 48: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 48/401

olumn 8ame Type omment 8ullable Format Title

olumn< 4 Thiscolumn isan integer 

C !/<0

olumnG 4G Thiscolumn isa smallint

C !/0

length

olumnJ D* Thiscolumn isa date

C CCCC!$$!DD

olumnB D Thiscolumn isa decimal

C !!!!!!!!.

$a6 Length DecimalTotalDigits

Decimal FractionalDigits

"angeLo%

"angeHigh

> 8

G 8

< 8

G 8

G 8

> 8

> G 8

3pperase Table?1ie% Defaultvalue

har Type

4dolType

 8 T

 8 T

 8 T

 8 T <

 8 T <

 8 T

 8 T The above output has been %rapped to multiple lines to sho% all the detail informationavailable on the columns of a table.HELP 14E5 $y=1ie% /notice that the vast ma(ority of the column data is not available for a vie%, it comes fromthe table, not the &ELET that creates a vie%0B "o%s "eturned

Page 49: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 49/401

olumn 8ame Type omment 8ullable Format Title

olumn< Thiscolumn isan integer 

olumnG Thiscolumn isa smallint

olumn; Thiscolumn isa byteint

olumn> Thiscolumn isa fi6edlength

olumn This

column isa variablelength

olumnJ Thiscolumn isa date

olumnB Thiscolumn isa decimal

$a6 Length Decimal

TotalDigits

Decimal Fractional

Digits

"ange

Lo%

"ange

High

3pperase Table?1ie% Defaultvalue

har Type

4dolType

<

Page 50: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 50/401

3pperase Table?1ie% Defaultvalue

har Type

4dolType

<

The above output is %rapped to multiple lines, displays the column name and the kind,%hich e7uates to the data type and any comment added to a column. 8otice that a vie%does not kno% the data type of the columns from a real table. Teradata provides a#$$E8T command to add these comments on tables and columns.The follo%ing #$$E8T commands add a comment to a table and a vie%)

#$$E8T #8 T*+LE table!name- KThis is the ne% table commentK

#$$E8T #8 14E5 vie%!name- KThis is the ne% vie% commentK

This #$$E8T command adds a comment to a column)

#$$E8T #8 #L3$8 table!name-.column!name-  KThis is the ne% column commentK The above column information is helpful for most of the column types, such as48TE2E" /40, &$*LL48T /4G0 and D*TE /D*0 because the si'e and the value range isa constant. Ho%ever, the lengths of the DE4$*L /D0 and the character columns /F,10 are not sho%n here. These are the most common of the data types. &ee chapter </DDL0 for more details on data types.The ne6t HELP #L3$8 command provides more details for all of the columns)HELP #L3$8 $y=Table.9

The output is not sho%n again, since it is e6actly the same as the ne%er version of theHELP T*+LE command.The ne6t chart sho%s HELP commands for information on database tables and sessions,as %ell as &ML and &PL commands)The above chart does a pretty good (ob of e6plaining the HELP functions. Thesefunctions only provide additional information if the table ob(ect has one of thesecharacteristics defined on it. The 48DEI, &T*T4&T4& and #8&T"*48T functions%ill be further discussed in the Data Definition Language hapter /DDL0 because of their relationship to the ob(ects.

#pen table as spreadsheet Help ommands)

HELP 48DEI table!name- Displays the inde6es and their characteristics like uni7ue or non!uni7ue and the column or columns involved in the inde6. Thisdata is used by the #ptimi'er to create a plan for &ML.

HELP &T*T4&T4&table!name-

Displays values associated %ith the data demographics collectedon the table. This data is used by the #ptimi'er to create a planfor &ML.

HELP #8&T"*48T Displays the checks to be made on the data %hen it is inserted or 

Page 51: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 51/401

#pen table as spreadsheet Help ommands)

table!name-.constraint!name-

updated and the columns are involved.

HELP &E&&4#8 Displays the user name, account name, logon date and time,current database name, collation code set and character set beingused, transaction semantics, time 'one and character set data.

HELP K&MLK Displays a list of available &ML commands and functions.

HELP K&MLcommand-K

Displays the basic synta6 and options for the actual &MLcommand inserted in place of the command-.

HELP K&PLK Displays a list of available &PL commands.

HELP K&PLcommand-K

Displays the basic synta6 and options for the actual &PLcommand inserted in place of the command-.

Figure ;!G*t this point in learning &ML, and in the interest of getting to other &ML functions, one of the most useful of these HELP functions is the HELP &E&&4#8.The follo%ing HELP returns inde6 information on the department=table)HELP 48DEI Department=table ; ro%s returned

3ni7ue Primary or &econdary

olumn 8ames 4nde64d

*ppro6imateount

4nde6 8ame

#rdered or Partitioned

C P Dept=8o < . H

 8 & Department=name> . H

 8 & $gr=8o J. H

The follo%ing HELP returns information on the session from the PE)HELP &E&&4#8 < "o% "eturned /columns %rapped for vie%ing0

3ser 8ame *ccount 8ame

LogonDate

LogonTime

urrentDatabase

ollation haracter &et

D+ D+ ?<G?<G <<)>)<; Personnel *&44 *&44

Transaction &emantics urrentDateForm

TimeNone

Defaultharacter 

Type

E6portLatin

Teradata 4ntegerdate ) L*T48 <

Page 52: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 52/401

E6port 3nicode E6port3nicode*d(ust

E6port@an(i&O4&

E6port2raphic

< <

Default Date Format "adi6&eparator 

2roup&eparator 

2rouping"ule

CC?$$?DD . , ;

urrency "adi6 &eparator urrency2roup&eparator 

urrency2rouping"ule

urrency 8ame

. , ; 3&Dollars

urrency 4&#urrency Dualurrency 8ame

Dualurrency

Dual4&#urrency

3&D 3&Dollars

3&D

Default +yte4nt format Default4nteger format

Default&mall4ntformat

Default 8umericformat

Default "eal format DefaultTimeformat

DefaultTimestampformaturrent"ole

  !/;0

!/<0

!/0

!!/40./F0

!.E!

HH)$4)&&.&/F0N CCCC!$$!

DD+HH)$4)&&.&/F0N

D+

The above output has been %rapped for easier vie%ing. 8ormally, all headings and valuesare on a single line.The current date form, time 'one and everything that follo%s them in the output are ne%%ith the 1G"; release of Teradata. These columns have been added to make their reference here, easier than digging through the Data Dictionary using &ML.5hen using a tool like +TEM, the line is truncated. &o, for easier vie%ing, the.&4DET4TLE& and .F#LDL48E commands sho% the output in a vertical display.

Page 53: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 53/401

The ne6t se7uence of commands can be used %ithin +TEM).sidetitles on.foldline on

HELP &E&&4#8

< "o% "eturned3ser 8ame $4@EL

*ccount 8ame

D+

Logon Date ?J?G

Logon Time <)G)G

urrentData+ase

$4@EL

ollation *&44

haracter &et

*&44

Transaction&emantics

Teradata

urrentDateForm

4ntegerDate

&essionTime None

)

Defaultharacter Type

L*T48

E6port Latin<E6port3nicode

<

E6port3nicode*d(ust

E6port@an(i&O4&

<

E6port2raphic

To reset the display to the normal line, use either of the follo%ing commands)

.DEF*3LT&or .&4DET4TLE& #FF.F#LDL48E& #FF4n +TEM, any command starting %ith a dot /.0 does not have to end %ith a semi!colon /0.The ne6t HELP command returns a list of the available &ML commands and functions)HELP K&MLK>< "o%s "eturned

Page 54: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 54/401

#n!Line Help

D+& &ML#$$*8D&)

 

*+#"T *LTE" T*+LE +E248

L#22482+E248T"*8&*T4#8

HE@P#48T #LLET&T*T4&T4&

#$$4T #$$E8T "E*TED*T*+*&E

"E*TE 48DEI "E*TE $*"# "E*TE T*+LE

"E*TE 3&E" "E*TE 14E5 D*T*+*&E

DELETE DELETED*T*+*&E

DELETE 3&E" 

D"#P

D*T*+*&E

D"#P 48DEI D"#P $*"#

D"#P T*+LE D"#P 14E5 D"#P&T*T4&T4&

EH# E8D L#22482 E8DT"*8&*T4#8.

D+& &MLF38T4#8&)

 

*+& *DD=$#8TH& *1E"*2E

H*"*TE"& *&T H*"GHEI48T

#38T #"" #1*"=P#P

&3$ EIP EIT"*T

F#"$*T 48DEI H*&H*$P

H*&H+@*$P H*&H+3@ET H*&H"#5

@3"T#&4& L8 L#2

$*12 $*I4$3$ $H*"*TE"&

$D4FF $48DEI $484$3$

$L48"E2 $&3+&T" $&3$

 8*$ED 83LL4FNE"# #TET=LE82TH

M3*8T4LE "E2"=48TE"EPT "E2"=&L#PE

"*8D#$ "*8@ &@E5

&M"T &TDDE1=P#P &TDDE1=&*$P

&3+&T" &3$ T4TLE

T"4$ TCPE 3PPE"  

1*"2"*PH4 1*"=P#P 1*"=&*$P

NE"#4F83LL

The above output is not a complete list of the commands. The three dots in the center represent the location %here commands %ere omitted so it fit onto a single page. *llcommands are seen %hen performed on a terminal.

Page 55: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 55/401

#nce this output has been used to find the command, than the follo%ing HELP command provides additional information on it)HELP K&ML E8D T"*8&*T4#8K "o%s "eturned

#n!Line Help

Q E8D T"*8&*T4#8 R

Q R

Q ET R

&ince the terminal is used most of the time to access the database, take advantage of itand use the terminal for your HELP commands.Tools like Mueryman also have a variety of HELP commands and individual menus.*l%ays look for %ays to make the task easier.&ET &E&&4#8 commandThe Teradata Database provides user access only by allocating a session %ith a ParsingEngine. The Parsing engine %ill use default attributes based on the user and host

computer from %hich the user is connecting. 5hen a different session option is needed,the &ET &E&&4#8 command is needed. 4t over!rides the default for this session only. Thene6t time the user logs into Teradata, the original default %ill be used again.&ynta6 for &ET &E&&4#8)&ET &E&&4#8 Q #LL*T4#8 collation!se7uence- S  *#38TAaccount!id- F#" Q "EM3E&T S &E&&4#8 R S  D*TEF#"$ A Q 48TE2E"D*TE S *8&4D*TE R S  D*T*+*&E database!name- R The &ET &E&&4#8 can be abbreviated as) &&.ollation se7uence) *&44, E+D4, $3LT48*T4#8*L /European /diacritical0character or @an(i character0, H*"&ET=#LL /binary ordering based on the current

client character set0, O4&=#LL /logical ordering of characters based on the Oapanese4ndustrial &tandards collation0, H#&T /E+D4 for 4+$ channel!attached clients and*&44 for all other clients default collation0.*ccount!id) allo%s for the temporary changing of accounting data for charge back and priority. The account!id specified must be a valid one assigned to the user and the prioritycan only be do%n graded.48TE2E"D*TE) uses the CC?$$?DD format and *8&4D*TE uses the CCCC!$$!DD format for a date.Database!name) becomes the database to use as the current database for &ML operationsduring this session.

&;$: commands

There are times when you need to recreate a tale) +iew) or macro that you already ha+e) or you need to create another o(ect of the same type that is either identical or +ery similar toan o(ect that is already created& 2hen this is the case) the S=32 command is a way toaccomplish what you need& The intent of the S=32 command is to output the CR0T0statement that could e used to recreate the o(ect of the type specified&

Page 56: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 56/401

3pen tale as spreadsheet This chart shos the commands and their ,ormats/

S=32 T#L0 Ktale*name H

"isplays the CR0T0 T#L0 statement needed tocreate this tale&

S=32 <,02 K+iew*name

H

"isplays the CR0T0 <,02 statement needed to

create this +iew&

S=32 $CR3 Kmacro*name H

"isplays the CR0T0 $CR3 statement neededto create this macro&

S=32 TR,II0R Ktrigger*name H

"isplays the CR0T0 TR,II0R statementneeded to create this trigger&

S=32 4R3C0"5R0Kprocedure*name H

"isplays the CR0T0 4R3C0"5R0 statementneeded to create this stored procedure&

S=32 KSQL*statement H "isplays the CR0T0 T#L0 statements for alltalesF+iews referenced y the SQL statement &

%igure @1@ 

2e will e discussing all of these o(ect types and their associated "ata "efinition Language!""L% commands later in this course&

To see the CR0T0 T#L0 command for the 0mployee tale) we use the command:

S=32 T#L0 0mployee H

1 Rows Returned

CR0T0 S0T T#L0 $@L&0mployee )N3 -LL#CJ )

  N3 #0-3R0 @35RNL)

  N3 -T0R @35RNL

  !

  0mpWNr ,NT0I0R)

  LastWName C=R!9% C=RCT0R S0T LT,N N3T CS0S40C,-,C N3T N5LL)

  -irstWName <RC=R!89% C=RCT0R S0T LT,N N3T CS0S40C,-,C N3T N5LL)

  SocialWSecWNr ,NT0I0R)

  #irthW"ate "T0 N3T N5LL)

  "epartmentWNr S$LL,NT)

  @oWNr ,NT0I0R)

  Salary "0C,$L!19)8% N3T N5LL%

5N,Q50 4R,$R ,N"06 !0mpWNr%H

To see the CR0T0 <,02 command) we use a command like:

S=32 <,02 T3" H

Rows Returned

CR0T0 <,02 $@L&T3" S

S0L0CT G -R3$ SSWCL0N"R&CL0N"R

Page 57: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 57/401

2=0R0 CL0N"RW"T0 M '8991*9A*81'H

To see the CR0T0 $CR3 command for the macro called $R043RT) we use acommand like:

S=32 $CR3 $R043RT H

A Rows ReturnedCR0T0 $CR3 $@L91&$R043RT !,N4R$1 ,NT0I0R) ,N4R$8 C=R!19%% S

!S0L0CT "04T)

"W3-W200J)

 <I!SL%

-R3$ SSWCL0N"R&CL0N"R SC) $T#L0

2=0R0 CL0N"RW"T0 M :,N4R$8 !"T0) -3R$T '$$""'%

 N" "04T M :,N4R$1

IR354 # 1)8H%H

To see the CR0T0 TR,II0R command for <IWSLWT) we use:S=32 TR,II0R <IWSLWT H

89 Rows Returned

CR0T0 TR,II0R $@L&<IWSLWT

 -T0R 54"T0 3- !SLR% 3N $@L&0$4L300

R0-0R0NC,NI 3L" S 3L"R32

 N02 S N02R32

-3R 0C= R32

2=0N !N02R32&SLR

 !S0L0CT <I!#5"I0T% G &19 !"0C,$L!19)8%% -R3$ $@L91&"04RT$0NT% %

!,NS0RT ,NT3 $@L91&IR0T0RW19W40RC0NT

 !0$4WN5$

 )SLW"T0

 )3L"SL

 )N02SL

 )40RCW3-W#5"I0T%

 <L50S !N02R32&0$4WN#R

 )C5RR0NTW"T0

 )3L"R32&SLR

 )N02R32&SLR%H

% H

Since the S=32 command returns the ""L) it can e a real time sa+er& ,t is a +ery helpfultool when a dataase o(ect needs to e recreated) a copy of an e.isting o(ect is needed)or another o(ect is needed that has similar characteristics to an e.isting o(ect& 4lus) what a

Page 58: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 58/401

great way to get a reminder on the synta. needed for creating a tale) +iew) macro) or trigger&

,t is a good idea to sa+e the output of the S=32 command in case it is needed at a later date& =owe+er) if the o(ect's structure changes) the S=32 command should e re*e.ecuted and the new output sa+ed& ,t returns the ""L that can e used to create a newtale e.actly the same as the current tale& Normally) at a minimum) the tale name ischanged efore e.ecuting the command&

EQPLAIN

The 064L,N command is a powerful tool pro+ided with the Teradata  dataase& ,t isdesigned to pro+ide an 0nglish e.planation of what steps the $4 must complete to satisfythe SQL re/uest& The 064L,N is ased on the 40's e.ecution plan&

The 4arsing 0ngine !40% does the optimiation of the sumitted SQL) the creation of the $4 steps and the dispatch to any $4 in+ol+ed in accessing the data& The 064L,N is anSQL modifierH it modifies the way the SQL operates&

2hen an SQL statement is sumitted using the 064L,N) the 40 still does the sameoptimiation step as normal& =owe+er) instead of uilding the $4 steps) it uilds the0nglish e.planation and sends it ack to the client software) not to the $4& This gi+es usersthe aility to see resource utiliation) use of indices) and row and time estimates&

Therefore) it can predict a Cartesian product (oin in seconds) instead of hours later when theuser gets suspicious that the re/uest should ha+e een finished& The 064L,N should erun e+ery time changes to an o(ect's structure occur) when a re/uest is first put intoproduction and other key times during the life of an application& Some companies re/uirethat the 064L,N always e run efore e.ecution of any new /ueries&

The synta. for using the 064L,N is simple: (ust type the 064L,N keyword preceding your +alid SQL statement& -or e.ample:

EQPLAINKSQL*command H

The 064L,N can e used to translate the actions for all +alid SQL& ,t cannot pro+ide atranslation when synta. errors are present& The SQL must e ale to e.ecute in order to ee.plained&

3pen tale as spreadsheet Chart ,or some o, the +eyords that may !e seen inthe output o, an EQPLAIN/

Locking 4seudo Tale Serial lock on a symolic tale& 0+ery tale has one&5sed to pre+ent deadlocks situations etween users&

Locking tale for ,ndicates that an CC0SS) R0") 2R,T0) or  06CL5S,<0 lock has een placed on the tale

Locking rows for  Ktype

,ndicates that an CC0SS) R0") or 2R,T0) lock isplaced on rows as they are read or written

"o an #3RT test Iuarantees a transaction is not in p rogress for thisuser 

 ll $4s retrie+e ll $4s are recei+ing the $4 steps and are in+ol+ed

Page 59: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 59/401

3pen tale as spreadsheet Chart ,or some o, the +eyords that may !e seen inthe output o, an EQPLAIN/

in pro+iding the answer set

#y way of an all rows

scan

Rows are read se/uentially on all $4s

#y way of primaryinde.

Rows are read using the 4rimary inde. column!s%

#y way of inde.numer 

Rows are read using the Secondary inde. > numer from =0L4 ,N"06

#$S$S #it $ap Set $anipulation Step) alternati+e directaccess techni/ue when multiple N5S, columns arereferenced in the 2=0R0 clause

Residual conditions 2=0R0 clause conditions) other than those of a (oin

0liminating duplicaterows 4ro+iding uni/ue +alues) normally result of ",ST,NCT)IR354 # or su/uery

2here unknowncomparison will eignored

,ndicates that N5LL +alues will not compare to a TR50or -LS0& $ight e seen in a su/uery using N3T ,Nor N3T M LL ecause no rows will e returned if comparison is ignored&

Nested (oin The fastest (oin possile& ,t uses a 54, to retrie+e asingle row after using a 54, or a 5S, in the 2=0R0 toreduce the (oin to a single row&

$erge (oin Rows of one tale are matched to the other tale oncommon domain columns after eing sorted into the

same se/uence) normally Row =ash

4roduct (oin Rows of one tale are matched to all the rows of theother tale without concern for a domain match

R32," (oin The newest !<8RE% and other fastest (oin possile& ,tuses the R32," of a 54, to retrie+e a single row after using a 54, or a 5S, in the 2=0R0 to reduce the (ointo a single row&

"uplicated on all $4s 4articipating rows for the tale !normally smaller tale%of a (oin are duplicated on all $4S

=ash redistriuted on

all $4s

4articipating rows of a (oin are hashed on the (oin

column and sent to the same $4 that stores thematching row of the tale to (oin

S$S Set $anipulation Step) result of an ,NT0RS0CT)5N,3N) 06C04T or $,N5S operation

Last use S433L file is no longer needed after the step andspace is released

#uilt locally on the s rows are read) they are put into S433L on the

Page 60: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 60/401

3pen tale as spreadsheet Chart ,or some o, the +eyords that may !e seen inthe output o, an EQPLAIN/

 $4s same $4

 ggregate

,ntermediate Resultsare computed locally

The aggregation +alues are all on the same $4 and

therefore no need to redistriute them to work withrows on other $4s

 ggregate,ntermediate Resultsare computed gloally

The aggregation +alues are not all on the same $4and must e redistriuted on one $4) to accompanythe same +alue with from the other $4s

%igure @1 

3nce you attain more e.perience with Teradata and SQL) these terms lead you to a moredetailed understanding of the work in+ol+ed in any SQL re/uest&

The following charts list the confidence le+els indicated y the optimier:

3pen tale as spreadsheet 

This chart is ,or phrases that accompany theestimated num!er o, ros/

No confidence The 40 has no degree of certainty with the +alues used& This isnormally a result of not collecting STT,ST,CS and workingwith multiple steps in S433L

Lowconfidence

The 40 is not sure of the +alues eing used& This is normally aresult of processing in+ol+ing se+eral steps in S433L insteadof the actual rows in a tale

=ighconfidence

Normally indicates that STT,ST,CS ha+e een collected onthe columns or indices of a tale& llows the optimier to emore aggressi+e in the access plan&

,nde. @oinconfidence

,ndicates that a (oin is eing done there uses a (oin condition+ia a uni/ue inde.&

%igure @1D 

The first is the estimated numer of rows that will e returned& This numer is an educatedguess that the 40 has made ased on information a+ailale at the time of the 064L,N&This numer may or may not e accurate& ,f there are current STT,ST,CS on the tale) thenumers are more accurate& 3therwise) the 40 calculates a guess y asking a random $4for the numer of rows it contains& Then) it multiples the answer y the numer of $4s toguess a ;total row count&; t the same time) it lets you know how accurate the numer pro+ided might e using the terms in the ne.t chart&

The second area to check in the output of the 064L,N is the estimated cost) e.pressed intime) to complete the SQL re/uest& lthough it is e.pressed in time) do not confuse it witheither wall*clock or C45 time& ,t is strictly a cost factor calculated y the optimier for comparison purposes only& ,t does not take the numer of users) the current workload or other system related factors into account& fter looking at the potential e.ecution plans) theplan with the lowest cost +alue is selected for e.ecution& 3nce these two +alues arechecked) the /uestion that should e asked is: re these +alues reasonale

Page 61: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 61/401

-or instance) if the tale contains one million rows and the estimate is one million rows in 7seconds) that is proaly reasonale if there is not a 2=0R0 clause& =owe+er) if the talecontains a million rows and is eing (oined to a tale with two thousand rows and theestimate is that two hundred trillion rows will e returned and it will take fifty days) this is notreasonale&

The following 064L,N is for a full tale scan of the Student Tale:

064L,N

S0L0CT G -R3$ StudentWtale H

18 Rows Returned

E.planation

1& -irst) we lock a distinct $,J0L&;pseudo tale; for read on a Row=ash topre+ent gloal deadlock for $,J0L&StudentWtale&

8& Ne.t) we lock $,J0L&StudentWtale for read&& 2e do an all*$4s R0TR,0<0 step from $,J0L&StudentWtale y way of an

all*rows scan with no residual conditions into Spool 1) which is uilt locally onthe $4s& The sie of Spool 1 is estimated with lo con,idence to !e Gros& The estimated time for this step is 9&1 seconds&

7& -inally) we send out an 0N" TRNSCT,3N step to all $4s in+ol+ed inprocessing the re/uest&

* The contents of Spool 1 are sent ack to the user as the result of statement 1& Thetotal estimated time is 60D seconds&

The 064L,N estimates) B rows and &1 seconds& Since there are 19 rows in the tale) the064L,N is slightly off in its estimate& =owe+er) this is reasonale ased on the contents of the tale and the S0L0CT statement sumitted&

The ne.t 064L,N is for a (oin that has an error in it) can you find it:

064L,N

S0L0CT G-R3$ StudentWtale S) CourseWtale C) StudentWCourseWtale SC

2=0R0 s&studentWid M sc&studentWid H

E.planation

1& -irst) we lock a distinct $,J0L&;pseudo tale; for read on a Row=ash topre+ent gloal deadlock for $,J0L&SC&

8& Ne.t) we lock a distinct $,J0L&;pseudo tale; for read on a Row=ash topre+ent gloal deadlock for $,J0L&C&

& 2e lock a distinct $,J0L&;pseudo tale; for read on a Row=ash to pre+entgloal deadlock for $,J0L&S&

7& 2e lock $,J0L&SC for read) we lock $,J0L&C for read) and we lock $,J0L&S

for read&& 2e do an all*$4s @3,N step from $,J0L&SC y way of a Row=ash match

scan with no residual conditions) which is (oined to $,J0L&S& $,J0L&SC and$,J0L&S are (oined using a merge   Roin) with a (oin condition of !;$,J0L&S&StudentW," M $,J0L&SC&StudentW,";%& The result goes into Spool8) which is duplicated on all AMPs& The sie of Spool 8 is estimated with lowconfidence to e 18B rows& The estimated time for this step is 9&1A seconds&

E& 2e do an all*$4s @3,N step from $,J0L&C y way of an all*rows scan withno residual conditions) which is (oined to Spool 8 !Last 5se%& $,J0L&C and

Page 62: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 62/401

E.planation

Spool 8 are (oined using a  product Roin) with a (oin condition of !;!1M1%;%&The result goes into Spool 1) which is uilt locally on the $4s& The sie of Spool 1 is estimated with lo con,idence to !e D09 ros& The estimatedtime for this step is 9&89 seconds&

D& -inally) we send out an 0N" TRNSCT,3N step to all $4s in+ol+ed inprocessing the re/uest&

* The contents of Spool 1 are sent ack to the user as the result of statement 1& Thetotal estimated time is 6@H seconds&

The 064L,N estimates nearly 18 rows will e returned and it will take &A seconds& lthough the time estimate sounds acceptale) this is a +ery small tale& Looking at thenumer of rows returned as 18 with only 17 rows in the largest of these tales& This is notreasonale ased on the contents of the tales&

5pon further e.amination) the product (oin in step E is using !1M1% as the (oin conditionwhere it should e a merge (oin& Therefore) this is a Cartesian product (oin& careful analysisof the S0L0CT shows a single (oin condition in the 2=0R0 clause& =owe+er) this is a three*

tale (oin and should ha+e two (oin conditions& The 2=0R0 clause needs to e fi.ed and yusing the 064L,N we ha+e sa+ed +aluale time&

,f you can get to the point of using the 064L,N in this manner) you are way ahead of thegame& No one will e+er ha+e to slap your hand for writing SQL that runs for days) uses uplarge amounts of system resources and accomplishes asolutely nothing& ou say) ;"octor) ithurts when , do this&; The "octor says) ;"on't do that&; 2e are saying) ;"on't put e.tensi+eS0L0CT re/uests into production without doing an 064L,N on it&

Rememer) always e.amine the 064L,N for reasonale results& Then) sa+e the 064L,Noutput as a enchmark against any future 064L,N output& Then) if the SQL starts e.ecutingslower or using more resources) you ha+e a asis for comparison& ou might also use theenchmark if you decide to add a secondary inde.& This prototyping allows you to seee.actly what your SQL is doing&

Some users ha+e /uit using the 064L,N ecause they ha+e gotten inaccurate results&-rom our e.perience) when the numers are consistently different than the actual rowseing returned and the cost estimate is completely wrong) it is normally an indicator thatSTT,ST,CS should e collected or updated on the in+ol+ed tales&

Adding Comments

Sometimes it is necessary or desirale to document the logic used in an SQL statementwithin the /uery& comment is not e.ecuted and is ignored y the 40 at synta. checking andresolution time&

AN&I Comment

To comment a line using the NS, standard form of a comment: ** the doule dash at the start of a single line denotes a comment is on that

line

0ach line that is a comment must e started with the same two dashes for each commentline& This is the only techni/ue a+ailale for commenting using NS, compliancy&

Page 63: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 63/401

 t the writing of this ook) Queryman sometimes gets confused and regards all lines after the * * as part of the comment& So) e careful regarding +arious client tools&

** This is an NS, form of comment that consists of a single line of user e.planation or ** addnotes to an SQL command& This is a second line and needs additional dashes

Teradata Comment

To comment a line using the Teradata form of a comment: FG the slash asterisk at the start of a line denotes the eginning of a comment

GF the asterisk slash !re+ersed from the start of a comment% is used to end acomment&

#oth the start and the end of a comment can e a single line or multiple lines& This is themost common form of comment seen in Teradata SQL) primarily since it was the originaltechni/ue a+ailale&

FG This is the Teradata form of comment that consists of a single line of user e.planation or add notes to an SQL command& Se+eral lines of comment can e added within a single

notation& This is the end of the comment& GF

'ser In,ormation %unctions

The Teradata R"#$S !Relational "ata#ase $anagement System% has incorporated into itfunctions that pro+ide data regarding a user who has performed a logon connection to thesystem& The following functions make that data a+ailale to a user for display or storage&

ACC$'NT %unction

Compatiility: Teradata 0.tension

  user within the Teradata dataase has an account numer& This numer is used to identifythe user) pro+ide a asis for charge ack) if desired and estalish a asic priority&

4re+iously) this numer was used e.clusi+ely y the dataase administrator to control andmonitor access to the system& Now) it is a+ailale for +iewing y the user +ia SQL&

Synta. for using the CC35NT function:

S0L0CTO ACC$'NT H

 s an e.ample) the following returns the account information for my user:

S0L0CT CC35NTH

1 Row returned

ACC$'NT

[$1EDB

,f your account starts with a [$) you are running at a medium priority& 2here [L is low and[= is high& t the same time) the account does not ha+e to egin with one of these and cane any site specific +alue&

Page 64: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 64/401

ATABA&E %unction

Compatiility: Teradata 0.tensionChapter 1  of this ook discussed the concept of a dataase and user area within theTeradata R"#$S& Jnowing the current dataase within Teradata is sometimes an importantpiece of information needed y a user& s mentioned ao+e) the =0L4 S0SS,3N is one way

to determine it& =owe+er) a lot of other information is also presented& Sometimes it isad+antageous to ha+e only that single tidit of data not only to see ut also for storage&2hen this is the case) the "T#S0 function is a+ailale&

Synta. for using the "T#S0 function:

S0L0CTO ATABA&E H

 s an e.ample) the following returns the account information for my user:

S0L0CT "T#S0H

1 Row returned

ATABA&E

$ikel

&E&&I$N %unction

Compatiility: Teradata 0.tensionChapter 1 of this ook discussed the 404 and the concept of a session and its role in+ol+ingthe user's SQL re/uests& The =0L4 S0SS,3N pro+ides a wealth of information regardingthe indi+idual session estalished for a user& 3ne of those pieces of data is the sessionnumer& ,t uni/uely identifies e+ery user session in e.istence at any point in time& Teradatanow makes the session numer a+ailale using SQL&

Synta. for using the S0SS,3N function:

S0L0CTO &E&&I$N H

 s an e.ample) the following returns the account information for my user:

S0L0CT S0SS,3NH

1 Row returned

&E&&I$N

19A

Page 65: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 65/401

Page 66: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 66/401

3pen tale as spreadsheet  This chart indicates hich data types that Teradatacurrently supports as AN&I &tandards/

ata Type escription ata alue "ange

,NT0I0R Signed whole numer *8)17D)7B)E7B to8)17D)7B)E7D

S$LL,NT Signed smaller wholenumer 

*8)DEB to 8)DED

"0C,$L!6)%

2here: 6M1 thru 1B)total numer of digits inthe numer nd M9thru 1B digits to the rightof the decimal

Signed decimalnumer 1B digits oneither side of thedecimal point

Largest +alue"0C!1B)9%

Smallest +alue"0C!1B)1B%

N5$0R,C!6)%

Same as "0C,$L

Synonym for  "0C,$L

Same as "0C,$L

-L3T R0L 4R0C,S,3N "35#L04R0C,S,3N

-loating 4oint -ormat!,000%

K+alue.199D  toK+alue.19*9B 

C=RCT0R!6%

C=R!6%

2here: .M1thru E7999

-i.ed lengthcharacter string) 1yte of storage per character)

1 to E7)999characters long)pads to length withspace

<RC=R!6%

C=RCT0R<R,NI!6%

C=R <R,NI!6%

2here: 6M1 thru E7999

<ariale lengthcharacter string) 1yte of storage per 

character) plus 8ytes to record lengthof actual data

1 to E7)999characters as ama.imum& The

system only storesthe characterspresented to it&

CL3# !6 P J $ I %

C=RCT0R LRI0

3#@0CT !6 P J $ I %

Large character  o(ect) for  manipulating chunks&Can also specifycharacter set andattriute&

$a. for LT,N in J)$ or I: 89AD9BB999ytes

$a. for 5N,C3"0 inJ or $: 197B77999ytes& See manual&

#L3# !6 P J $ I %

#,NR LRI0

3#@0CT !6 P J $ I %

Large inary o(ect)for manipulating

chunks&

Specified inJiloytes)

$egaytes or  Iigaytes& $a. is89AD9BB999 ytes&See manual&

"T0 Signed internalrepresentation of $$""

See chapter B  for details

T,$0 ,dentifies a field as a  

Page 67: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 67/401

3pen tale as spreadsheet  This chart indicates hich data types that Teradatacurrently supports as AN&I &tandards/

ata Type escription ata alue "ange

T,$0 +alue with =our)$inutes and Seconds

T,$0ST$4 ,dentifies a field as aT,$0ST$4 +aluewith ear) $onth)"ay) =our) $inute)and Seconds

 

%igure 10 

3pen tale as spreadsheet  This chart indicates hich data types that Teradatacurrently supports as e.tensions/

ata Type escription ata alue "ange

#T0,NT Signed wholenumer 

*18B to 18D

#T0 !6%

2here: 6M1 thruE7999

#inary 1 to E7)999 ytes

<R#T0 !6%

2here: 6M1 thruE7999

<ariale lengthinary

1 to E7)999 ytes

L3NI<RC=R

<ariale length string E7)999 characters !ma.imumdata length% The system only

stores the characterspro+ided) not trailing spaces&%

IR4=,C !6%

2here: 6M1 thru8999

-i.ed length string of 1E*it ytes !8 ytesper character%

1 to 8)999 JN@, characters

<RIR4=,C!6%

2here: 6M1 thru8999

<ariale length stringof 1E*it ytes

1 to 8)999 characters as ama.imum& The system onlystores characters pro+ided&

%igure 19 

These data types are all a+ailale for use within Teradata& Notice that there are fi.ed and+ariale length data formats& The fi.ed data types always re/uire the entire defined length ondisk for the column& The +ariale types can e used to ma.imie data storage within a locky storing only the data pro+ided within a row y the client software&

ou should use the appropriate type for the specific data& ,t is a good idea to use a <R datatype when most of the data is less than the ma.imum sie& This is due to the addition of ane.tra 8*yte length indicator that is stored along with the actual data&

Page 68: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 68/401

CA&T

Compatiility: NS,

5nder most conditions) the data types defined and stored in a tale should e appropriate&=owe+er) sometimes it is neither con+enient nor desirale to use the defined type& "ata cane con+erted from one type to another y using the CST function& s long as the datain+ol+ed does not reak any data rules !i&e& placing alphaetic or special characters into anumeric data type% the con+ersion works& The name of the CST function comes from theCon+ert nd STore operation that it performs&

Care must also e taken when con+erting data to manage any potential length issues& ,nTeradata mode) truncation occurs if a length is re/uested that is shorter than the originaldata& =owe+er) in NS, mode) an SQL error is the result ecause NS, says) ;Thou shall nottruncate data&;

The asic synta. of the CST statement follows:

S0L0CT CA&T!Kcolumn*name A& 3data1type4O(3length4))-R3$ Ktale*name H

0.amples using CST:

CST ! Ksmallint*data S C=R!% % FG smallint to character GF

CST ! Kdecimal*data S ,NT0I0R % FG truncates decimals GF

CST ! Kyteint*data S S$LL,NT % FG inary to smallint GF

CST ! Kchar*data S #T0 !18B% % FG character to inary GF

CST ! Kyteint*data S <RC=R!% % FG yteint to character GF

CST ! Kinteger*data S -L3T% FG integer to float point GF

These are only some of the potential con+ersions and are primarily here for illustration of how to code a CST& The CST could also e used within the 2=0R0 clause to control thelength characteristics or the type of the data to compare&

 gain) when using the CST in NS, mode) any attempt to truncate data causes the SQL tofail ecause NS, does not allow truncation&

The ne.t S0L0CT uses literal +alues to show the results of con+ersion:

S0L0CT CA&T('#C"0' A& C;A"(0) ) S Trunc

  )CA&T(18B A& C;A"(@) ) S 3J

  )CA&T(18D A& INTE8E") S #igger 

  )CA&T(181& A& &MALLINT) S 2hole  )CA&T(181& A& ECIMAL(@J6)) S Rounder H

1 Row Returned

Trunc $2

Bigger :hole "ounder  

  18B 18D 181 188

Page 69: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 69/401

,n the ao+e e.ample) the first CST truncates the fi+e characters !left to right% to form thesingle character ''& ,n the second CST) the integer 18B is con+erted to three charactersand left (ustified in the output& The 18D was initially stored in a S$LL,NT ! digits * up to8DED% and then con+erted to an ,NT0I0R& =ence) it uses 11 character positions for itsdisplay) ten numeric digits and a sign !positi+e assumed% and right (ustified as numeric&

The +alue of 181& is an interesting case for two reasons& -irst) it was initially stored as a"0C,$L as total digits with 8 of them to the right of the decimal point& Then it iscon+erted to a S$LL,NT using CST to remo+e the decimal positions& Therefore) ittruncates data y stripping off the decimal portion& ,t does not round data using this datatype& 3n the other hand) the CST in the fifth column called Rounder is con+erted to a"0C,$L as digits with no digits !)9% to the right of the decimal) so it will round data+alues instead of truncating& Since & is greater than &) it is rounded up to 188&

Implied CA&T

Compatiility: Teradata 0.tension

 lthough the CST function is the NS, standard) it has not always een that way& 4rior to

the CST function) Teradata had the aility to con+ert data from one type to another&

This con+ersion is re/uested y placing the ;implied' data type con+ersion in parenthesesafter the column name& Therefore) it ecomes a part of the select list and the columnre/uest& The new data type is written as an attriute for the column name&

The following is the format for re/uesting a con+ersion:

S0L0CT Kcolumn*name (3data1type4 O(3length4)

-R3$ Ktale*name H

 t first glance) this appears to e the est and shortest techni/ue for doing con+ersions&=owe+er) there is a hidden danger here when con+erting from numeric to character that isdemonstrated in this S0L0CT that uses the same data as ao+e to do implied CSTcon+ersions:

S0L0CT '#C"0' (C;A"(0))  S Shortened

  )18B (C;A"(@))  S 334S1

  )*18B (C;A"(@))  S 334S8

  )18B (INTE8E")  S #igger 

  )181&1 (&MALLINT) S 2hole H

1 Row Returned

&hortened $$P&0 $$P&9 Bigger :hole

    * 18B 181

2hat happened in the column named 3J and NW3J

The answer to this /uestion is: the +alue 18B is 1 greater than 18D and therefore too large of a +alue to store in a #T0,NT& So it is automatically stored as a S$LL,NT ! digits plus asign% efore the con+ersion& The implicit con+ersion changes it to a character type with thefirst characters eing returned& s a result) only the first spaces are seen in the report !W 

Page 70: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 70/401

 W W 18B%& Likewise) 334S8 is stored as !W W *18B% with the first three characters !8 spacesand *% shown in the output&

 lways think aout the impact of the sign as a +alid part of the data when con+erting fromnumeric to character& s mentioned earlier) if you find that con+ersions of this type areregularly necessary) the tale design needs to e re*e.amined& s demonstrated in theao+e output) it is always safer to use CST when going from character to numeric datatypes&

%ormatted ata

Compatiility: Teradata 0.tension

Rememer that truncation works in Teradata mode) ut not in NS, mode& So) another wayto make data appear to e truncated is to use the Teradata -3R$T in the S0L0CT list withone or more columns when using a tool like #T0Q& Since -3R$T does not truncate data) itworks in NS, mode&

The synta. for using -3R$T is:

S0L0CT 'Kchar*data' (%$"MAT KQ()K) FG alphaetic format 7 characters GF  )Knumeric*data' (%$"MAT KHHHK)  FG numeric format characters GF

  )Kdate*data (%$"MAT KYYYY1MM1K) FG date format characters GF

-R3$ Ktale*name H

The ne.t S0L0CT demonstrates the use of -3R$T:

S0L0CT '#C"0' (%$"MAT KQQQK)  S Shorter 

  )181& (%$"MAT KHHHHHK) S -mtW181

  )181&

  )AA1991!date% (%$"MAT KMM#dd#YyK) S -mtWNum"ate

  )AA1991!date% (%$"MAT Kmmm!ddJ!yyyyK) S -mtW"ate H

1 Row Returned

&horter %mt7090 090D@ %mt7Numate %mt7ate

 #C 99181 181& 19F91FAA 3CT 91)1AAA

There are a couple of things to notice in this output& -irst) it works in NS, mode ecausetruncation does not occur& The distinction is that all of the data from the column is in spool& ,tis only the output that is shortened) not truncated& The character data types use the '6' for the formatting character&

Second) formatting does not round a data +alue as with the 181&) the display is shortened&The numeric data types use a 'A' as the asic formatting character& 3thers are shown in thischapter&

Ne.t) "T0 type data uses the '$' for month) the '"' for day of the month and '' for the year portion of a +alid date& Lastly) the case of the formatting characters does not matter& Theformatting characters can e written in all uppercase) lowercase) or a mi.ture of oth cases&

Page 71: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 71/401

The two following charts show the +alid formatting characters for Teradata and pro+ide ane.planation of the impact each one has on the output display when using #T0Q:

#asic Numeric and Character "ata -ormatting Symols

3pen tale asspreadsheet&ym!ol

Mas+ character and ho used

6 or . Character data& 0ach 6 represents one character& Canrepeat +alue* i&e& 66666 or 6!%&

A "ecimal digit& =olds place for numeric digit for a display 9through A& ll leading eroes are shown if the format maskis longer than the data +alue& Can repeat +alue* i&e& AAAAAor A!%&

< or + ,mplied decimal point& ligns data on a decimal +alue&4rimarily used on imported data without actual decimalpoint&

0 or e 0.ponential& ligns the end of the mantissa and the

eginning of the e.ponent&

I or g Iraphic data& 0ach I represents one logical !doule yte*JN@, or Jatakana% character& Can repeat +alue* i&e&IIIII or I!%&

%igure 1@ 

3pen tale as spreadsheet Ad<anced Numeric and Character %ormatting &ym!ols

&ym!ol Mas+ character and ho used

[ -i.ed or floating dollar sign& ,nserts a [ or lea+es spaces and mo+es!floats% o+er to the first character of a currency +alue& 2ith the proper 

keyoard) additional currency signs are a+ailale: Cent) 4ound anden&

) Comma& ,nserted where appears in format mask& 5sed primarily tomake large numers easier to read&

& 4eriod& 4rimary use to align decimal point position& lso used for:dates and comma in some currencies&

* "ash character& ,nserted where appears in format mask& 5sedprimarily for dates and negati+e numeric +alues& lso used for: phonenumers) ip codes) and social security !5S%&

F Slash character& ,nserted where appears in format mask& 5sed

primarily for dates&U 4ercent character& ,nserted where appears in format mask& 5sed

primarily for display of percentage > i&e& AAU +s& &AA

Z or Zero*suppressed decimal digit& =olds place for numeric digit displays1 through A and 9) when significant& ll leading eroes !insignificant%are shown as space since their presence does not change the +alueof the numer eing displayed&

Page 72: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 72/401

3pen tale as spreadsheet Ad<anced Numeric and Character %ormatting &ym!ols

&ym!ol Mas+ character and ho used

# or #lank data& ,nsert a space where appears in format mask&

%igure 1 

The ne.t chart shows the formatting characters used in con(unction with "T0 data:

3pen tale as spreadsheet ate %ormatting &ym!ols

&ym!ol Mas+ character and ho used (not case speci,ic)

$ or m $onth& llows month to e displayed any where in the date display&2hen '$$' is specified) the numeric !91Y18% +alue is a+ailale&2hen '$$$' is specified) the three character !@NY"0C% +alue isa+ailale& Starting with <8R) you can specify '$$$$' and it willdisplay the full name of the month&

" or d "ay& llows day to e displayed any where in the date display& 2hen

'""' is specified) the numeric !91Y1% +alue is a+ailale& 2hen '"""'is specified) the three*digit day of the year !991YEE% +alue isa+ailale&

0 or e "ay of the week& 4ro+ides the day of the week as three or four  characters& 5sing 'eee' yields 'Sun' and 'eeee' yields 'Sund' for Sunday&

or y ear& llows day to e displayed any where in the date display& Thenormal '' has een used for many years for the 89 th century withthe 1A assumed& =owe+er) since we ha+e mo+ed into the 81 st

century) it is recommended that the '' e used&

%igure 1D 

There is additional information on date formatting in a later chapter dedicated e.clusi+ely todate processing&

The ne.t S0L0CT demonstrates some of the additional formatting symols:

S0L0CT '#C"0' !-3R$T '6.6'% S -mtWShorter 

  )8917BAAAA !-3R$T 'AAA*AAA*AAAA'% S -mtW4hone

  )1981& !-3R$T 'ZZZZZZA&AAAA'% S ZW4ress

  )AA1991!date% !-3R$T 'yddd'% S -mtW@ulian

  )AA1991!date% !-3R$T 'eee'% s 2eekday

  )AA1991 !-3R$T '[[[[)[[[&AA'% S -mtW4ay H

1 Row Returned

%mt7&horter %mt7Phone 7Press %mt7Sulian :ee+day %mt7

 #C 891*7B*AAAA

1981& AA8D7 -ri [AA1

Page 73: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 73/401

There are only two things that need to e watched when using the -3R$T function& -irst)the data type must match the formatting character used or a synta. error is returned& So) if the data is numeric) use a numeric formatting character and the same condition for character data& The other concern is configuring the format mask ig enough for the largest datacolumn& ,f the mask is too short) the SQL command e.ecutes) howe+er) the output containsa series of GGGGGGGGGGGGG to indicate a format o+erflow) as demonstrated y the followingS0L0CT:

S0L0CT 8917BAAAA !-3R$T 'AAA*AAAA'% S -mtW4hone H

1 Row Returned

%mt7Phone

GGGGGGGGG

 ll of these -3R$T re/uests work wonderfully if the client software is #T0Q& fter all) it isa report writer and these are report writer options& The issue is that the 3"#C andQueryman look at the data as data) not as a report& Since many of the formatting symolsare ;characters; they cannot e numeric& Therefore) the 3"#C strips off the symols andpresents the numeric data to the client software for display&

Tric+ing the $BC to Allo %ormatted ata

,f a tool uses the 3"#C) the -3R$T in the S0L0CT is ignored and the data comes ackas data) not as a formatted field& This is especially noticeale with numeric data and dates&

To force tools like Queryman to format the data) the software must e tricked into thinkingthe data is character type) which it lea+es alone& This can e done using the CST function&The ne.t S0L0CT uses the CST operation to trick the software into thinking the formatteddata is character:

S0L0CT CST! (GDHHHH (%$"MAT KHHH1HHHHK) ) S C=R!B%% FG e.plicit CST GF

  S -mtWCSTW4hone FG implicit cast GF  )AA1991!date% !-3R$T 'yyyy&mm&dd'% !C=R!19% %

  S -mtWCSTW"ate

  )CST!!AA1991 !-3R$T '[[[[)[[[&AA'%% S C=R!11% %

  S -mtWCSTW4ay H

1 Row Returned

%mt7CA&T7Phone %mt7CA&T7ate %mt7CA&T7Pay

7BYAAAA 1AAA&19&91 [AA1)991&99

"o not let the presence of S in the ao+e S0L0CT confuse you& The first S) inside theparentheses) goes with the new data type for the CST& Notice that the parentheses encloseoth the data and the -3R$T so that they are treated as a single entity& The second S isoutside the parentheses and is used to name the alias&

TITLE Attri!ute ,or ata Columns

Compatiility: Teradata 0.tension

Page 74: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 74/401

Page 75: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 75/401

Transaction Modes

Transaction mode is an area where the perspecti+e of the Teradata R"$#S and NS,e.perience a departure& Teradata) y default) is completely non*case specific& NS, re/uires

 (ust the opposite condition) e+erything is case specific and as we saw earlier) dictates thattale and column names e in capital letters&

This is proaly a little restricti+e and , tend to agree completely with the Teradataimplementation& t the same time) Teradata allows the user to work in either mode within asession when connected to the R"#$S& The choice is up to the user when #T0Q is theclient interface software&

-or instance) within #T0Q either of the following commands can e used efore loggingonto the dataase:

&&ET &E&&I$N T"AN&ACTI$N AN&I

or 

&&ET &E&&I$N T"AN&ACTI$N BTET

The #T0T transaction is simply an acronym made from a consolidation of the #0I,NTRNSCT,3N !#T% and 0N" TRNSCT,3N !0T% commands to represent Teradatamode&

2hen using SQL ssistant) an 3"#C can e configured to use the ;$ode; of NS,&

The system administrator defines the system default mode for Teradata& setting in the "#SControl record determines the default session mode& The ao+e commands allow the defaultto e o+er*ridden for each logon session& The S0T command must e e.ecuted efore thelogon to estalish the transaction mode for the ne.t session!s%&

=owe+er) not all client software supports the aility to change modes etween Teradata and NS,& 2hen it is desirale for functionality or processing characteristics of the other mode)other options are a+ailale and are presented elow& There is more information ontransactional processing later in this ook&

Case &ensiti<ity o, ata

,t has een discussed earlier that there is no need for concern regarding the use of lower or upper case characters when coding the SQL& s a matter of fact) the different case letterscan e mi.ed in a single statement& Normally) the Teradata dataase does not care aoutthe case when comparing the stored data either&

=owe+er) the NS, mode implementation of the Teradata  R"#$S is case sensiti+e)

regarding the data& This means that it knows the difference etween a lower case letter like'a' and an upper case letter ''& t the same time) when using Teradata mode within theTeradata dataase) it does not distinguish etween upper and lower case letters& ,t is themode of the session that dictates the case sensiti+ity of the data&

The SQL can always e.ecute NS, standard commands in Teradata mode and likewise) canalways e.ecute Teradata e.tensions in NS, mode& The SQL is always the same regardlessof the mode eing used& The difference comes when comparing the results of the data rowseing returned ased on the mode&

Page 76: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 76/401

-or e.ample) earlier in this chapter) it was stated that NS, mode does not allow truncation&Therefore) the -3R$T could e used in either mode ecause it did not truncate data&

To demonstrate this issue) the following uses the different modes in #T0Q:

&set session transaction ansi

&logon user1

S0L0CT 'They match' !title ''% 2=0R0 '' M 'a'H

No Rows Returned

The ao+e SQL e.ecution is case specific due NS, mode and '' is different than 'a'& Thesame SQL is e.ecuted again here) howe+er) the transaction mode for the session is set toTeradata mode !#T0T% prior to the logon:

&set session transaction tet

&logon user1

S0L0CT 'They match' !title ''% 2=0R0 '' M 'a'H

1 Row Returned

They match

Now that the defaults ha+e een demonstrated) the following functions can e used to mimicthe operation of each mode while e.ecuting in the other !NS, +s Teradata% where casesensiti+ity is concerned&

CA&E&PECI%IC

Compatiility: Teradata 0.tension

The CS0S40C,-,C attriute may e used to re/uest that Teradata compare data +alueswith a distinction made etween upper and lower case& The logic ehind this designation isthat e+en in Teradata mode) case sensiti+ity can e re/uested to make the SQL work thesame as NS, mode) which is case specific& Therefore) when CS0S40C,-,C is used) itnormally appears in the 2=0R0 clause&

The synta. of the ne.t two statements e.ecute e.actly the same:

S0L0CT Kcolumn*name

-R3$ Ktale*name

2=0R0 Kcolumn*name!CA&E&PECI%IC% M P 'Kcharacter*literal' Kcolumn*name H

3r) it may e are+iated as CS:

S0L0CT Kcolumn*name

-R3$ Ktale*name

2=0R0 Kcolumn*name!C&% M P 'Kcharacter*literal' Kcolumn*name H

Con+ersely) if NS, is the current mode and there is a need for it to e non*case specific) theN3T can e used to ad(ust the default operation of the SQL within a mode&

The following SQL forces NS, to e non*case specific:

Page 77: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 77/401

S0L0CT Kcolumn*name

-R3$ Ktale*name

2=0R0 Kcolumn*name !N$T CA&E&PECI%IC% M

  P 'Kcharacter*literal' Kcolumn*name H

3r) it may e are+iated as:S0L0CT Kcolumn*name

-R3$ Ktale*name

2=0R0 Kcolumn*name!N$T C&% M P 'Kcharacter*literal' Kcolumn*name H

The ne.t S0L0CT demonstrates the functionality of CS0S40C,-,C and CS for comparingan e/uality condition like it e.ecuted ao+e in NS, mode:

&set session transaction tet

&logon user1

S0L0CT 'They match' !title ''% 2=0R0 KAK(CA&E&PECI%IC) ? KaK(C&) H

No Rows Returned

No rows are returned) ecause '' is different than 'a' when case sensiti+ity is used& t firstglance) this seems to e unnecessary since the mode can e set to use either NS, or Teradata& =owe+er) the dot !&% commands are #T0Q commands& They do not work inQueryman& ,f case sensiti+ity is needed when using other tools) this is one of the optionsa+ailale to mimic NS, comparisons while in Teradata mode&

The SQL e.tensions in Teradata may e used to eliminate the asolute need to log off toreset the mode and then log ack onto Teradata in order to use a characteristic like casesensiti+ity& ,nstead) Teradata mode can e forced to use a case specific comparison) like

 NS, mode y incorporating the CS0S40C,-,C !CS% into the SQL& The case specificoption is not a statement le+el featureH it must e specified for each column needing this typeof comparison in oth #T0Q and Queryman&

L$:E" %unction

Compatiility: NS,

The L320R case function is used to con+ert all characters stored in a column to lower caseletters for display or comparison& ,t is a function and therefore re/uires that the data epassed to it&

The synta. for using L320R:

S0L0CT L$:E"!Kcolumn*name%

-R3$ Ktale*name

2=0R0 L$:E"!Kcolumn*name% M P 'Kcharacter*literal' Kcolumn*name H

The following S0L0CT uses an upper case literal +alue as input and outputs the same +alue)ut in lower case:

S0L0CT L$:E" !'#C"0'% S Result H

1 Row Returned

Page 78: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 78/401

"esult

acde

2hen L320R is used in a 2=0R0 clause) the result is a predictale string of all lowercasecharacters& 2hen compared to a lowercase +alue) the result is a case lind comparison&This is true regardless of how the data was originally stored&

S0L0CT 'They match' !title '"o they match'%

2=0R0 L$:E"!'a#c"e'% M 'acde' H

1 Row Returned

o They match

They match

'PPE" %unction

Compatiility: NS,

The 5440R case function is used to con+ert all characters stored in a column to the samecharacters in upper case& ,t is a function and therefore re/uires that data e passed to it&

The synta. for using 5440R:

S0L0CT 'PPE"!Kcolumn*name%

-R3$ Ktale*name

2=0R0 'PPE"!Kcolumn*name% M P 'Kcharacter*literal' Kcolumn*name H

The ne.t e.ample uses a literal +alue within 5440R to show the output all in upper case:

S0L0CT 'PPE"!'a#c"e'% S Result H

1 Row Returned

"esult

 #C"0

,t is also possile to use oth the L320R and 5440R case functions within the 2=0R0clause& This techni/ue can e used to make NS, non*case specific) like Teradata) ycon+erting all the data to a known state) regardless of the starting case& Thus) it does notcheck the original data) ut instead it checks the data after the con+ersion&

The following S0L0CT uses the 5440R function in the 2=0R0:

S0L0CT'They match' !title '"o they match'%

2=0R0 'PPE"!'a#c"e'% M '#C"0' H

1 Row Returned

o They match

They match

Page 79: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 79/401

2hen the data does not meet the re/uirements of the output format) it is time to con+ert thedata& The 5440R and L320R functions can e used to change the appearance or characteristics of the data to a known state&

2hen case sensiti+ity is needed) NS, is one way to accomplish it& ,f that is not an option)the CS0S40C,-,C function can e incorporated into the SQL&

Page 80: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 80/401

Chapter : Aggregation

Aggregate Processing

The aggregate functions are used to summarie column data +alues stored in rows& ggregates eliminate the detail information from the rows and only return the answer&

Therefore) the result is one or more aggregated +alues as a single line or one line per uni/ue+alue) as a group& The other characteristic of these functions is that they all ignore null+alues stored in column data passed to them&

Math Aggregates

The math aggregates are the original functions used to pro+ide simple types of arithmeticoperations for the data +alues& Their names are descripti+e of the operation performed& Thefunctions are listed elow with e.amples following their descriptions& The newer) <8R7statistical aggregates are co+ered later in this chapter&

The &'M %unction

 ccumulates the +alues for the named column and prints one total from the addition&

The A8 %unction

 ccumulates the +alues for the named column and counts the numer of +alues added for the final di+ision to otain the a+erage&

The MIN %unction

Compares all the +alues in the named column and returns the smallest +alue&

The MAQ %unctionCompares all the +alues in the named column and returns the largest +alue&

The C$'NT %unction

 dds one to the counter each time a +alue other than null is encountered&

Page 81: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 81/401

Page 82: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 82/401

Since the name of the selected column appears as the heading for the column) aggregatenames make for funny looking headings& To make the output look etter) it is a good idea touse an alias to dress up the name used in the output& dditionally) the alias can e usedelsewhere in the SQL as the column name&

The ne.t S0L0CT demonstrates the use of alias names for the aggregates:

S0L0CT S5$!IradeW4t% S ;Total;  )<I!IradeW4t% S ;+erage;

  )$,N!IradeW4t% S Smallest

  )$6!IradeW4t% S =ighest

  )C35NT!IradeW4t% S ;Count;

-R3$ StudentWtale H

1 Row Returned

Total A<erage &mallest Largest Count

87&BB 8&DE 9&99 7&99 A

Notice that when using aliases in the ao+e S0L0CT they appear as the heading for eachcolumn& lso the words Total) +erage and Count are in doule /uotes& s mentioned earlier in this ook) the doule /uoting techni/ue is used to tell the 40 that this is a column name)opposed to eing the reser+ed word& 2hereas) the single /uotes are used to identify a literaldata +alue&

Aggregates and eri<ed ata

The +arious aggregates can work on any column& =owe+er) most of the aggregates onlywork with numeric data& The C35NT function might e the primary one used on either character or numeric data& The aggregates can also e used with deri+ed data&

The following tale is used to demonstrate deri+ed data and aggregation:

%igure D19 

This S0L0CT totals the salaries for all employees and show what the total salaries will e if e+eryone is gi+en a U or a 19U raise:

S0L0CT S5$!salary% !Title 'Salary Total') -ormat '[[[[)[[A&AA'%

  )S5$!salaryG1&9% !Title 'XU Raise') -ormat '[[[[)[[A&AA'%

  )S5$!salaryG1&19% !Title 'X19U Raise') format '[[[[)[[A&AA'%

  )<I!salary% !Title '+erage Salary') format '[[[[)[[A&AA'%

  )S5$!salary% F C35NT!salary% !Title 'Computed +erage Salary'%

Page 83: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 83/401

Page 84: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 84/401

aggregate is not part of an associated group& Therefore) the IR354 # is re/uired in theSQL statement to identify e+ery column selected that is not an aggregate&

The resulting output consists of one line for all aggregate +alues for each uni/ue data +aluestored in the column!s% named in the IR354 #& -or e.ample) if the department numer isused from the 0mployee tale) the output consists of one line per department with at leastone employee working in it&

The ne.t S0L0CT uses the IR354 # to create one line of output per uni/ue +alue in theclass code column:

S0L0CT Class7code

  )S5$!IradeW4t% S ;Total;

  )<I!IradeW4t% S ;+erage;

  )$,N!IradeW4t% S Smallest

  )$6!IradeW4t% S =ighest

  )C35NT!IradeW4t% S ;Count;

-R3$ StudentWtale

8"$'P BY Class7code H

Rows Returned

Class7code Total A<erage &mallest Largest Count

-R E&BB 8&8A 9&99 7&99 8

9

@R &B 8&A8 1&A9 &A 8

SR E& &1D &99 & 8

S3 &B9 8&A 8&99 &B9 8

Notice that the null +alue in the class code column is returned& t first) this may seemcontrary to the aggregates ignoring nulls& =owe+er) class code is not eing aggregated andis selected as a ;uni/ue +alue&; ll the aggregate +alues on the grade point for this row arenull) e.cept for C35NT& lthough) the C35NT is ero and this does indicate that the null+alue is ignored& The C35NT +alue initially starts at ero) so: 9 X 9 M 9&

The IR354 # is only re/uired when a non*aggregate column is selected along with one or more aggregates& 2ithout oth a non*aggregate and a IR354 # clause) the aggregatesreturn only one row& 2hereas) with a non*aggregate and a IR354 # clause designatingthe column!s%) the aggregates return one row per uni/ue +alue in the column) as seenao+e&

 dditionally) more than one non*aggregate column can e specified in the S0L0CT and inthe IR354 # clause& The normal result of this is that more rows are returned& This isecause one row appears whene+er any single column +alue changes) the comination of each column constitutes a new +alue& Rememer) all non*aggregates selected with anaggregate must e included in the IR354 #) or a 97 error is returned&

 s an e.ample) the last name might e added as a second non*aggregate& Then) eachcomination of last name and class code are compared to other students in the same class&This comination creates more lines of output& s a result) each aggregate +alue is primarilythe aggregation of a single row& The only time multiple rows are processed together is when

Page 85: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 85/401

Page 86: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 86/401

 s pre+iously shown) the default for a column heading is the column name& ,t is not +erypretty to see the name of the aggregate and column used as a heading& Therefore) an aliasis suggested in all tools or optionally) a T,TL0 in #T0Q to define a heading&

 lso seen earlier) a C35NT on the grade point for department null is ero& ctually) this ismisleading in that 1 row contains a null not ero rows& #ut) ecause of the null +alue) the rowis not counted& etter techni/ue might e the use of C35NT!G%) for a row count& lthoughthis implies counting all columns) in reality it counts the row& The o(ecti+e of this re/uest isto find any column that contains a non*null data +alue&

 nother method to pro+ide the same result is to count any column that is defined as N3TN5LL& =owe+er) since it takes time to determine such a column and its name is longer thantyping an asterisk !G%) it is easier to use the C35NT!G%&

 gain) the IR354 # clause creates one line of output per uni/ue +alue) ut does notperform a sort& ,t only creates the distinct grouping for all of the columns specified&Therefore) it is suggested that you always include an 3R"0R # to sort the output&

The following might e a etter way to code the pre+ious re/uest) using the C35NT!G% andan 3R"0R #:

S0L0CT ClassWcode

  )S5$!IradeW4t% S ;Total;

  )<I!IradeW4t% S ;+erage;

  )$,N!IradeW4t% S Smallest

  )$6!IradeW4t% S =ighest

  )C35NT!G% S ;Count;

-R3$ StudentWtale

IR354 # 1

$"E" BY 0 H

Rows Returned

Class7code Total A<erage &mallest Largest Count

1  

-R E&BB 8&8A 9&99 7&99

@R &B 8&A8 1&A9 &A 8

S3 &B9 8&A 8&99 &B9 8

SR E& &1D &99 & 8

Now the output is sorted y the class code with the null appearing first) as the lowest ;+alue&; lso notice the count is one for the row containing mostly N5LL data& The C35NT!G% countsthe row&

Limiting $utput alues 'sing ;AIN8

 s in any S0L0CT statement) a 2=0R0 clause can always e used to limit the numer or types of rows used in the aggregate processing& Therefore) something esides a 2=0R0 is

Page 87: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 87/401

needed to e+aluate aggregate +alues ecause the aggregate is not finished until all eligilerows ha+e een read& gain) a 2=0R0 clause eliminates rows during the process of reading the ase tale rows& To allow for the elimination of specific aggregate results) the=<,NI clause is used to make the final comparison efore the aggregate results arereturned&

The pre+ious S0L0CT is modified elow to compare the aggregates and only return thestudents from spool with a grade point a+erage of # !&9% or etter:

S0L0CT ClassWcode

  )S5$!IradeW4t% S ;Total;

  JA8(8rade7Pt)  A& VA<erageV

  )C35NT!IradeW4t% S ;Count;

-R3$ StudentWtale

;AIN8 VA<erageV 4 @66

IR354 # 1

3R"0R # 1H

1 Rows Returned

Class7code Total A<erage Count

SR E& &1B 8

Notice that all of the pre+iously seen output with an a+erage +alue less than &99 has eeneliminated as a result of using the =<,NI clause& The 2=0R0 clause eliminates rowsH the=<,NI pro+ides the last comparison after the calculation of the aggregate and eforeresults are returned to the user client&

&tatistical Aggregates

,n Teradata Release 7 !<8R7% there are se+eral new aggregates that perform statisticaloperations& $any of them are used in other internal functions and now they are a+ailale for use within SQL&

Not only are these statistical functions the newest) ut there are two types of statisticalfunctions& They are unary !single input +alue% functions) and inary !dual input +alue%functions&

The unary functions look at indi+idual column +alues for each row included and compare allof the +alues for trends) similarities and groupings& ll the original aggregate functions areunary in that they accept a single +alue to perform their processing&

The statistical unary functions are:

JurtosisSkewStandard "e+iation of a sampleStandard "e+iation of a population

<ariance of a sample<ariance of a population

The inary functions e.amine the relationship etween the two different +alues& Normallythese two +alues represent two separate points on an 6 a.is and *a.is&

Page 88: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 88/401

The inary functions are:CorrelationCo+arianceRegression Line ,nterceptRegression Line Slope

The results from the statistical functions are not as o+ious to demonstrate and figure out as

the original functions) like S5$ or <I& The Stats tale in -igure * is used to demonstratethe statistical functions& ,ts column +alues ha+e certain patterns in them& -or instance C3L1increases se/uentially from 1 to 9 while C3L7 decreases se/uentially from 9 to 1& Theremaining columns tend to ha+e the same +alue repeated and some +alues repeat morethan others& These +alues are used in oth the unary and inary functions to illustrate thetypes of answers generated using these statistical functions&

%igure D1@ 

The following tale demonstrates the operation and output from the new statistical aggregatefunctions in <8R7&

The 2'"T$&I& %unction

The J5RT3S,S function is used to return a numer that represents the sharpness of a peakon a plotted cur+e of a proaility function for a distriution compared with the normaldistriution&

  high +alue result is referred to as leptokurtic& 2hile a medium result is referred to asmesokurtic and a low result is referred to as platykurtic&

  positi+e +alue indicates a sharp or peaked distriution and a negati+e numer represents aflat distriution& peaked distriution means that one +alue e.ists more often than the other +alues& flat distriution means there is the same /uantity +alues e.ist for each numer&

Page 89: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 89/401

,f you compare this to the row distriution associated within Teradata) most of the time a flatdistriution is est) with the same numer of rows stored on each $4& =a+ing skewed datarepresents more of a lumpy distriution&

Synta. for using J5RT3S,S:

J5RT3S,S!Kcolumn*name%

The ne.t S0L0CT uses J5RT3S,S to compare the distriution of the Stats tale:

S0L0CT 2'"T$&I&(col0) S JofCol1

  )J5RT3S,S!col8% S JofCol8

  )J5RT3S,S!col% S JofCol

  )J5RT3S,S!col7% S JofCol7

  )J5RT3S,S!col% S JofCol

  )J5RT3S,S!colE% S JofColE

-R3$ StatsWtaleH

1 Row Returned

2o,Col0 2o,Col9 2o,Col@ 2o,Col 2o,ColD 2o,Col

−1   −1 1   −1   −1   −1

The &2E: %unction

The Skew indicates that a distriution does not ha+e e/ual proailities ao+e and elow themean !a+erage%& ,n a skew distriution) the median and the mean are not coincident) or e/ual&

2here:

a median +alue K mean +alue M a positi+e skew a median +alue mean +alue M a negati+e skew

a median +alue M mean +alue M no skew

Synta. for using SJ02:

SJ02!Kcolumn*name%

The following S0L0CT uses SJ02 to compare the distriution of the Stats tale:

S0L0CT &2E:(col0) S SJofCol1

  )SJ02!col8% S SJofCol8

  )SJ02!col% S SJofCol

  )SJ02!col7% S SJofCol7  )SJ02!col% S SJofCol

  )SJ02!colE% S SJofColE

-R3$ StatsWtaleH

1 Row Returned

Page 90: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 90/401

Page 91: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 91/401

Page 92: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 92/401

The A"7&AMP %unction

The <ariance function is a measure of dispersion !spread of the distriution% as the s/uare of the standard de+iation& There are two forms of <ariance in Teradata) <RWS$4 is used for a random sampling of the data rows allowed through y the 2=0R0 clause&

 lthough standard de+iation and +ariance are regularly used in statistical calculations) themeaning of +ariance is not easy to elaorate& $ost often +ariance is used in theoretical workwhere a +ariance of the sample is needed to look for consistency&

There are two methods for using +ariance& These are the Jruskal*2allis one*way nalysis of <ariance and -riedman two*way nalysis of <ariance y rank&

Synta. for using <RWS$4:

<RWS$4!Kcolumn*name%

The ne.t S0L0CT uses <RWS$4 to compare the +ariance of the distriution on a rowsample from the Stats tale:

S0L0CT A"7&AMP(col0) S <SofCol1

  )<RWS$4!col8% S <SofCol8

  )<RWS$4!col% S <SofCol

  )<RWS$4!col7% S <SofCol7

  )<RWS$4!col% S <SofCol

  )<RWS$4!colE% S <SofColE

-R3$ StatsWtaleH

1 Row Returned

&o,Col0 &o,Col9 &o,Col@ &o,Col &o,ColD &o,Col

DB 89 1AB DB 89 D7B

The C$"" %unction

The C3RR function is a inary function) meaning that two +ariales are used as input to it& ,tmeasures the association etween 8 random +ariales& ,f the +ariales are such that whenone changes the other does so in a related manner) they are correlated& ,ndependent+ariales are not correlated ecause the change in one does not necessarily cause the other to change&

The correlation coefficient is a numer etween *1 and 1& ,t is calculated from a numer of pairs of oser+ations or linear points !6)%&

2here: 1 M perfect positi+e correlation 9 M no correlation   −1 M perfect negati+e correlation

Synta. for using C3RR:

C3RR!Kcolumn*name1) Kcolumn*name8%

Page 93: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 93/401

The following S0L0CT uses C3RR to compare the association of +alues stored in +ariouscolumns from the Stats tale:

S0L0CT C$""(col0J col9) S CofCol1\8

  )C3RR!col1) col% S CofCol1\

  )C3RR!col1) col7% S CofCol1\7

  )C3RR!col1) col% S CofCol1\

  )C3RR!col1) colE% S CofCol1\E

-R3$ StatsWtaleH

1 Row Returned

Co,Col0W9 Co,Col0W@ Co,Col0W Co,Col0WD Co,Col0W

9&ABE7B9 9&BB1   −1&999999   −9&11BDD 9&AA1E18

Since there are two column +alues passed to this function and the first e.ample has data+alues that se/uentially ascend) the ne.t e.ample uses col7 as the first +alue ecause it

se/uentially descends& ,t demonstrates the impact of this se/uence change on the result:

S0L0CT C$""(colJ col9) S CofCol7\8

  )C3RR!col7) col% S CofCol7\

  )C3RR!col7) col1% S CofCol7\1

  )C3RR!col7) col% S CofCol7\

  )C3RR!col7) colE% S CofCol7\E

-R3$ StatsWtaleH

1 Row Returned

Co,ColW9 Co,ColW@ Co,ColW0 Co,ColWD Co,ColW

−9&ABE7B9   −9&BB1   −1&999999 9&11BDD   −9&AA1E18

The C$A" %unction

The co+ariance is a statistical measure of the tendency of two +ariales to change incon(unction with each other& ,t is e/ual to the product of their standard de+iations andcorrelation coefficients&

The co+ariance is a statistic used for i+ariate samples or i+ariate distriution& ,t is used for working out the e/uations for regression lines and the product*moment correlation

coefficient&

Synta.:

C3<R!Kcolumn*name1) Kcolumn*name8%

The ne.t S0L0CT uses C3<R to compare the co+ariance association of +alues stored in+arious columns from the Stats tale:

S0L0CT C$A"7P$P(col0J col9) S C<ofCol1\8

  )C3<RW434!col1) col% S C<ofCol1\

Page 94: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 94/401

  )C3<RW434!col1) col7% S C<ofCol1\7

  )C3<RW434!col1) col% S C<ofCol1\

  )C3<RW434!col1) colE% S C<ofCol1\E

-R3$ StatsWtaleH

1 Row ReturnedCo,Col0W9 Co,Col0W@ Co,Col0W Co,Col0WD Co,Col0W

B 19E   −D   −E 81

Since there are two column +alues passed to this function and the first e.ample has data+alues that se/uentially ascend) the ne.t e.ample uses col7 as the first +alue ecause itse/uentially descends& ,t demonstrates the impact of this se/uence change on the result:

S0L0CT C$A"7P$P(colJ col9) S C+ofCol7\8

  )C3<RW434!col7) col% S C+ofCol7\

  )C3<RW434!col7) col1% S C+ofCol7\1

  )C3<RW434!col7) col% S C+ofCol7\

  )C3<RW434!col7) colE% S C+ofCol7\E

-R3$ StatsWtaleH

1 Row Returned

C<o,ColW9 C<o,ColW@ C<o,ColW0 C<o,ColWD C<o,ColW

−D   −19E   −D E   −81

The "E8"7INTE"CEPT %unction  regression line is a line of est fit) drawn through a set of points on a graph for 6 and coordinates& ,t uses the coordinate as the "ependent <ariale and the 6 +alue as the,ndependent <ariale&

Two regression lines always meet or intercept at the mean of the data points!.)y%) where.M<I!.% and yM<I!y% and is not usually one of the original data points&

Synta. for using R0IRW,NT0RC04T:

R0IRW,NT0RC04T!dependent*e.pression) independent*e.pression%

The following S0L0CT uses R0IRW,NT0RC04T to find the intercept point etween the

+alues stored in +arious columns from the Stats tale:S0L0CT "E8"7INTE"CEPT(col0J col9) S R,ofCol1\8

  )R0IRW,NT0RC04T!col1) col% S R,ofCol1\

  )R0IRW,NT0RC04T!col1) col7% S R,ofCol1\7

  )R0IRW,NT0RC04T!col1) col% S R,ofCol1\

  )R0IRW,NT0RC04T!col1) colE% S R,ofCol1\E

-R3$ StatsWtaleH

Page 95: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 95/401

1 Row Returned

"Io,Col0W9 "Io,Col0W@ "Io,Col0W "Io,Col0WD "Io,Col0W

−1 1 1B   −1

Since there are two column +alues passed to this function and the first e.ample has data+alues that se/uentially ascend) the ne.t e.ample uses col7 as the first +alue ecause itse/uentially descends& ,t demonstrates the impact of this se/uence change on the result:

S0L0CT "E8"7INTE"CEPT(colJ col9) S R,ofCol7\8

  )R0IRW,NT0RC04T!col7) col% S R,ofCol7\

  )R0IRW,NT0RC04T!col7) col7% S R,ofCol7\1

  )R0IRW,NT0RC04T!col7) col% S R,ofCol7\

  )R0IRW,NT0RC04T!col7) colE% S R,ofCol7\E

-R3$ StatsWtaleH

1 Row Returned

"Io,ColW9 "Io,ColW@ "Io,ColW0 "Io,ColWD "Io,ColW

8 8B 9 1 8

The "E8"7&L$PE %unction

  regression line is a line of est fit) drawn through a set of points on a graph of 6 and coordinates& ,t uses the coordinate as the "ependent <ariale and the 6 +alue as the,ndependent <ariale&

The slope of the line is the angle at which it mo+es on the 6 and coordinates& The +erticalslope is on 6 and the horiontal slope is 6 on &

Synta. for using R0IRWSL340:

R0IRWSL340!dependent*e.pression) independent*e.pression%

The ne.t S0L0CT uses R0IRWSL340 to find the slope for the +alues stored in +ariouscolumns from the Stats tale:

S0L0CT "E8"7&L$PE(col0J col9) S RSofCol1\8

  )R0IRWSL340!col1) col% S RSofCol1\

  )R0IRWSL340!col1) col7% S RSofCol1\7

  )R0IRWSL340!col1) col% S RSofCol1\

  )R0IRWSL340!col1) colE% S RSofCol1\E

-R3$ StatsWtaleH

1 Row Returned

"&o,Col0W9 "&o,Col0W@ "&o,Col0W "&o,Col0WD "&o,Col0W

8 1   −1   −9 9

Page 96: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 96/401

Since there are two column +alues passed to this function and the first e.ample has data+alues that se/uentially ascend) the ne.t e.ample uses col7 as the first +alue ecause itse/uentially descends& ,t demonstrates the impact of this se/uence change on the result:

S0L0CT "E8"7&L$PE(colJ col9) S RSofCol7\8

  )R0IRWSL340!col7) col% S RSofCol7\  )R0IRWSL340!col7) col7% S RSofCol7\1

  )R0IRWSL340!col7) col% S RSofCol7\

  )R0IRWSL340!col7) colE% S RSofCol7\E

  -R3$ StatsWtaleH

1 Row Returned

"&o,ColW9 "&o,ColW@ "&o,ColW0 "&o,ColWD "&o,ColW

−8   −1 1 9   −9

'sing 8"$'P BY

Like the original aggregates) the new statistical aggregates may also take ad+antage of using non*aggregates with the aggregates& The IR354 # is used to identify and formgroups for each uni/ue +alue in the selected non*aggregate column&

Likewise) the new statistical aggregates are compatile with the original aggregates as seenin the following S0L0CT:

S0L0CT col

  )count!G% S Cnt

  )a+g!col1% S +g1

  )stdde+Wpop!col1% S S"1

  )+arWpop!col1% S <41

  )a+g!col7% S +g7

  )stdde+Wpop!col7% S S"7

  )+arWpop!col7% S <47

  )a+g!colE% S +gE

  )stdde+Wpop!colE% S S"E

  )+arWpop!colE% S <4E

-R3$ StatsWtale

8"$'P BY 03R"0R # 1H

D Rows Returned

col@ Cnt A<g0 &0 P0 A<g & P

1 8 8 9 9 9 9 9

19 D E 8 7 8 8 7

Page 97: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 97/401

col@ Cnt A<g0 &0 P0 A<g & P

89 17 1E 7 1E 17 7 1E

9 8 87 9 9 E 9 9

79 8 8E 9 9 7 9 99 8 8B 9 9 8 9 9

E9 1 9 9 9 1 9 9

'se o, ;AIN8

 lso like the original aggregates) the =<,NI may e used to eliminate specific output linesased on one or more of the final aggregate +alues&

The ne.t S0L0CT uses the =<,NI to perform a compound comparison on oth the countand the co+ariance:

S0L0CT col

  )count!G% S Cnt

  )a+g!col1% S +g1

  )stdde+Wpop!col1% S S"1

  )+arWpop!col1% S <41

-R3$ StatsWtale

IR354 # 1

3R"0R # 1

;AIN8 Cnt 4 9 and P0 3 96=

8 Rows Returned

col@ Cnt A<g0 &0 P0

19 D E 8 7

89 17 1E 7 1E

'sing the I&TINCT %unction ith Aggregates

 t times throughout this ook) e.amples are shown using a function within a function and thepower it pro+ides& The C35NT aggregate pro+ides another opportunity to demonstrate a

capaility that might pro+e itself useful& ,t comines the ",ST,NCT and aggregate functions&

The following may e used to determine how many courses are eing taken instead of thetotal numer of students !19% with a +alid class code:

S0L0CT C35NT!I&TINCT!ClassWcode%% S 5ni/ueWCourses

-R3$ StudentWTale H

1 Row Returned

Page 98: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 98/401

'ni>ue7Courses

7

<ersus using all of the +alues:

S0L0CT C35NT!ClassWcode% S 5ni/ueWCourses-R3$ StudentWTale H

1 Row Returned

'ni>ue7Courses

A

,t is allowale to use the ",ST,NCT in multiple aggregates within a S0L0CT& The onlyrestriction is that all aggregates must use the same column for each ",ST,NCT function&

Aggregates and ery Large ata Bases (LB)

 s great as huge dataases might e) there are considerations to take into account whenprocessing large numers of rows& This section enumerates a few of the situations thatmight e encountered& Read them and think aout the re/uirement or enefit of incorporating them into your SQL&

Potential o, E.ecution Error 

 ggregates use the data type of the column they are aggregating& 3n most dataases) thisworks fine& =owe+er) when working on a <L"#) this may cause the S0L0CT to fail on anumeric o+erflow condition& n o+erflow occurs when the +alue eing calculated e.ceeds thema.imum sie or +alue for the data type eing used&

-or e.ample) one illion !1)999)999)999% is a +alid +alue for an integer column ecause it isless than 8)17D)7B)E7D& =owe+er) if three rows each ha+e one illion as their +alue and aS5$ operation is performed) it fails on the third row&

Try the following series of commands to demonstrate an o+erflow and its fi.:

** Create a tale called 3+erflow with 8 columns

CT 3+erflowWtl !3+rWyte #T0,NT) 3+rWint ,NT%H

** ,nsert rows with +ery large +alues of 1 illion where ma. +alue is 8)17D)7B)E7D

,NS o+erflowWtl +alues !1) 19GGA%H

,NS o+erflowWtl +alues !8) 19GGA%H,NS o+erflowWtl +alues !) 19GGA%H

** S5$ aggregate on these +alues will result in illion

S0L S5$!o+rWint% S sumWcol -R3$ o+erflowWtlH

GGGGG 8E1E numeric o+erflow

Page 99: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 99/401

 ttempting this S5$) as written) results in a 8E1E numeric o+erflow error& That is ecause illion is too large to e stored in the default data type of integer& This is the default ecauseof the data type of the column eing used within the aggregate& To fi. it) use either of thefollowing techni/ues to con+ert the data column to a different type efore performing theaggregation&

FG 0.plicit CST con+ersion GF

S0L S5$! CA&T(o<r7int A& ECIMAL(09J6)) % S sumWcol

-R3$ o+erflowWtlH

FG ,mplicit con+ersion GF

S0L S5$! (o<r7int (ECIMAL(09J6))) % S sumWcol -R3$ o+erflowWtlH

1 Row Returned

sum7col

)999)999)999

2hene+er you find yourself in a situation where the SQL is failing due to a numeric o+erflow)it is most likely due to the inherited data type of the column& 2hen this happens) e sure tocon+ert the type efore doing the math&

8"$'P BY <ersus I&TINCT s seen in chapter 8) ",ST,NCT is used to eliminate duplicate +alues& ,n this chapter) theIR354 # is used to consolidate multiple rows with the same +alue into the same group& ,tdoes the consolidation y eliminating duplicates& 3n the surface) they pro+ide the samefunctionality&

The ne.t S0L0CT uses IR354 # without aggregation to eliminate duplicates:

S0L0CT classWcode

-R3$ studentWtale

8"$'P BY 0

3R"0R # 1H

Rows Returned

class7code

-R

@R

S3

SR

The IR354 # without aggregation returns the same rows as the ",ST,NCT& So theo+ious /uestion ecomes) which is more efficient The answer is not a simple one& ,nstead)something must e known aout the characteristics of the data& Ienerally) with moreduplicate data +alues Y IR354 # is more efficient& =owe+er) if only a few duplicates e.ist

 Y ",ST,NCT is more efficient& To understand the reason) it is important to know how each of them eliminates the duplicate +alues&

Page 100: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 100/401

Techni/ue used to eliminate duplicates !can e seen in 064L,N%: ",ST,NCT

o Reads a row on each $4o =ashes the column!s% +alue identified in the ",ST,NCTo Redistriutes the row +alue to the appropriate $4

o 3nce all participating rows ha+e een redistriuted

o Sorts the data to comine duplicates on each $4

o 0liminates duplicates on each $4 IR354 #

o Reads all the participating rowso 0liminates duplicates on each $4 using ;uckets;

o =ashes the uni/ue +alues on each $4o Redistriutes the uni/ue +alues to the appropriate

 $4o 3nce all uni/ue +alues ha+e een redistriuted from

e+ery $4o Sorts the uni/ue +alues to comine

duplicates on each $4o 0liminates duplicates on each $4

#ack to the original /uestion: which is more efficient

Since ",ST,NCT redistriutes the rows immediately) more data may mo+e etween the $4s) compared to IR354 # that only sends uni/ue +alues etween the $4s& So)IR354 # sounds more efficient& =owe+er) when you consider that if the data is nearlyuni/ue) IR354 # spends time attempting to eliminate duplicates that do not e.ist&Therefore) it is wasting the time to check for duplicates the first time& Then) it mustredistriute the same amount of data anyway&

Therefore) for efficiency) when there are: $any duplicates Y use IR354 #

-ew to no duplicates Y use ",ST,NCT S433L space is e.ceeded Y try IR354 #

Per,ormance $pportunities

The Teradata optimier has always had options a+ailale to it when performing SQL& ,talways attempts to use the most efficient path to pro+ide the answer set& This is true for aggregation as well&

2hen performing aggregation) the main shortcut a+ailale might include the use of asecondary inde.& The inde. row is maintained in a sutale& This row contains the row ,"!row hash X uni/ueness +alue% and the actual data +alue stored in the data row&

Therefore) an inde. row is normally much shorter than a data row& =ence) more inde. rowse.ist in an inde. lock than in a data lock&

 s a result) the read of an inde. lock makes more +alues a+ailale than the actual datalock& Since ,F3 is the slowest operation on all computer systems) less ,F3 e/uates to faster processing& ,f the optimier can otain all the +alues it needs for processing y using thesecondary inde.) it will& This is referred to as a ;co+ered /uery&;

Page 101: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 101/401

The creation of a secondary inde. is co+ered in this ook as part of the "ata "efinitionLanguage !""L% chapter&

Chapter E: &u!>uery Processing

&u!>uery

The su/uery is a commonly used techni/ue and powerful way to select rows from one taleased on +alues in another tale& ,t is predicated on the use of a S0L0CT statement within aS0L0CT and takes ad+antage of the relationships uilt into a relational dataase& The asicconcept ehind a su/uery is that it retrie+es a list of +alues that are used for comparisonagainst one or more columns in the main /uery& To accomplish the comparison) thesu/uery is written after the 2=0R0 clause and normally as part of an ,N list&

,n an earlier chapter) the ,N was used to uild a +alue list for comparison against the rows of a tale to determine which rows to select& The ne.t e.ample illustrates how this techni/uecan e used to S0L0CT all the columns for rows containing any of the three different +alues

19) 89 and 9:S0L0CT G

-R3$ $yWtale

2=0R0 column1 ,N ! 19) 89) 9 % H

7 Rows Returned

Column0 Column9 7  

19 row with 19 in column1

9 row with 9 in column1

19 row with 19 in column1

89 row with 89 in column1

 s powerful as this is) what if the three +alues turned into a thousand +alues& That is toomuch work and too many opportunities to forget one of the +alues& ,nstead of writing the+alues manually) a su/uery can e used to generate the +alues automatically&

The coding techni/ue of a su/uery replaces the +alues pre+iously written in the ,N list witha +alid S0L0CT& Then the su/uery S0L0CT dynamically generates the +alue list& 3nce the+alues ha+e een retrie+ed) it eliminates the duplicates y automatically performing a",ST,NCT&

The following is the synta. for a su/uery:

S0L0CT Kcolumn*name

  )Kcolumn*nameO

-R3$ Ktale*name

** the su/uery starts here to form the list of +alues to compare for the ,N

2=0R0 Kcolumn*name) Kcolumn*name8 )Kcolumn*nameN OO IN

  ( &ELECT 3column1name4 OJ3column1name94OJ 3column1nameN4

Page 102: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 102/401

  %"$M 3ta!le1name4 )

H

Conceptually) the su/uery is processed first so that all the +alues are e.panded into the listfor comparison with the column specified in the 2=0R0 clause& These +alues in thesu/uery S0L0CT can only e used for comparison against the column or columns

referenced in the 2=0R0&

Columns inside the su/uery S0L0CT cannot e returned to the user +ia the main S0L0CT&The only columns a+ailale to the client are those in the tales named in the main !first%-R3$ clause& The /uery in parentheses is called the su/uery and it is responsile for uilding the ,N list&

 t the writing of this document) Teradata allows up to E7 tales in a single /uery& Therefore)if each S0L0CT accessed only one tale) a /uery might contain E su/ueries in a singlestatement&

The ne.t two tales are used to demonstrate the functionality of su/ueries:

%igure 10 

%igure 19 

The ne.t S0L0CT uses a su/uery to find all customers that ha+e an order of more than[19)999&99:

S0L0CT CustomerWname

  )4honeWnumer 

-R3$ CustomerWTale

2=0R0 Customer7num!er IN ( &ELECT Customer7num!er 

  %"$M $rder7ta!le :;E"E $rder7total 4 06666 ) H

Rows Returned

Customer7name Phone7num!er  

#illy's #est Choice *187

Page 103: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 103/401

Customer7name Phone7num!er  

6Z 4luming 7D*BA7

"ataases N*5 88*1918

This is an appropriate place to mention that the columns eing compared etween the mainand su/ueries must e from the same domain& 3therwise) if no e/ual condition e.ists) norows are returned& The ao+e S0L0CT uses the customer numer !-J% in the 3rder tale tomatch the customer numer !4J% in the Customer tale& They are oth customer numersand therefore ha+e the opportunity to compare e/ual from oth tales&

The ne.t su/uery swaps the /ueries to find all the orders y a specific customer:

S0L0CT 3rderWnumer 

  )3rderWtotal

-R3$ 3rderWTale

2=0R0 Customer7num!er IN ( &ELECT Customer7num!er 

  %"$M Customer7ta!le :;E"E Customer7name LI2E KBillK)H

Rows Returned

$rder7num!er $rder7total

187E 187D&

1818 B99&A1

Notice that the Customer tale is used in the main /uery to answer a customer /uestion andthe 3rder tale is used in the main /uery to answer an order /uestion& =owe+er) they othcompare on the customer numer as the common domain etween the two tales&

#oth of the pre+ious su/ueries work fine for comparing a single column in the main tale toa +alue list in the su/uery& Thus) it is possile to answer /uestions like) ;2hich customer has placed the largest order; =owe+er) it cannot answer this /uestion) ;2hat is thema.imum order for each customer;

To make Su/ueries more sophisticated and powerful) they can compare more than onecolumn at a time& The multiple columns are referenced in the 2=0R0 clause) of the main/uery and also enclosed in parentheses&

The key is this: if multiple columns are named efore the ,N portion of the 2=0R0 clause)the e.act same numer of columns must e referenced in the S0L0CT of the su/uery tootain all the re/uired +alues for comparison&

-urthermore) the corresponding columns !outside and inside the su/uery% mustrespecti+ely e of the same domain& 0ach of the columns must e e/ual to a corresponding+alue in order for the row to e returned& ,t works like an N" comparison&

The following S0L0CT uses a su/uery to match two columns with two +alues in thesu/uery to find the highest dollar orders for each customer:

S0L0CT CustomerWnumer S Customer 

  )3rderWnumer 

  )3rderWtotal

Page 104: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 104/401

Page 105: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 105/401

'sing N$T IN

 s seen in a pre+ious chapter) when using the ,N and a +alue list) the N3T ,N can e used tofind all of the rows that do not match&

5sing this techni/ue) the su/uery ao+e can e modified to find the customers without an

order& The only changes made are to 1% add the N3T efore the ,N and 8% eliminate the2=0R0 clause in the su/uery:

S0L0CT CustomerWname

  )4honeWnumer 

-R3$ CustomerWTale

2=0R0 CustomerWnumer N$T IN

  ! S0L0CT CustomerWnumer -R3$ 3rderWtale% H

1 Row Returned

Customer7name Phone7num!er  

"ataases R 5s 88*1918

Caution needs to e used regarding the N3T ,N when there is a potential for including aN5LL in the +alue list& Since the comparison of a N5LL and any other +alue is unknown) andthe N3T of an unknown is still an unknown no rows are returned& Therefore when there ispotential for a N5LL in the su/uery) it is est to also code a compound comparison as seenin the following S0L0CT:

S0L0CT CustomerWname

  )4honeWnumer 

-R3$ CustomerWTale

2=0R0 CustomerWnumer N3T ,N

  ! S0L0CT CustomerWnumer -R3$ 3rderWtale

  2=0R0 customerWnumer I& N$T N'LL% H

'sing -uanti,iers

,n other R"#$S systems and early Teradata +ersions) using an e/uality symol !M% in acomparison normally pro+ed to e more efficient than using an ,N list& The reason was that itallowed for indices) if they e.isted) to e used instead of a se/uential read of all rows& Today)Teradata  automatically uses indices whene+er they are more efficient& So) the use of /uantifiers is optional and an ,N works e.actly the same&

 nother powerful use for /uantifiers is when using ine/ualities& ,t is sometimes necessary tofind all rows that are greater than or less than one or more other +alues&

To use /uantifiers) replace the ,N with an M) K) ) N) S3$0 or LL as demonstrated in thefollowing synta.:

S0L0CT Kcolumn*name

  )Kcolumn*name O

-R3$ Ktale*name

Page 106: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 106/401

2=0R0 Kcolumn*name) Kcolumn*name8 )Kcolumn*nameN O O

  ? 4 3 4? 3? 34* ANY &$ME ALL *

  ! S0L0CT Kcolumn*name)Kcolumn*name8) Kcolumn*nameN O O

  -R3$ Ktale*name %

H

0arlier in this chapter) a two le+el su/uery was used to find the customer who spent themost money on a single order& ,t used an ,N list to find e/ual +alues& The ne.t S0L0CT usesM N to find the same customers:

S0L0CT CustomerWname

  )4honeWnumer 

-R3$ CustomerWTale

2=0R0 customerWnumer ? ANY

  (&ELECT customer7num!er %"$M $rder7Ta!le

  2=0R0 3rderWtotal

  ( &ELECT A8($rder7total) %"$M $rder7Ta!le ) %H

8 Rows Returned

Customer7name Phone7num!er  

#illy's #est Choice *187

6Z 4luming 7D*BA7

,n order to accomplish this) the 3rder tale is first used to determine the a+erage order amount& Then) the 3rder tale is used again to compare the a+erage with each order andfinally) compared to the Customer tale to determine which of the customers /ualify&

The /uantifiers of S3$0 and N are interchangeale& =owe+er) the use of N conformsto NS, standard and S3$0 is the Teradata e.tension& The M N is functionally e/ui+alentto using an ,N list&

The LL and the M are more limited in their scope& ,n order for them to work) there can onlye a single +alue from the su/uery for each of the +alues in the 2=0R0 clause& =owe+er)earlier the N3T ,N was e.plored& 2hen using /uantifiers and the N3T) consider thefollowing:

%igure 1@ 

3f these) the N3T M LL takes the most thought& ,t forces the system to e.amine e+ery+alue in the list to make sure that the +alue eing compared is checked against all the+alues& 3therwise) as soon as any of the +alues is different) the row is returned withoutlooking at the other +alues !LL%&

 lthough the ao+e descries the conceptual approach of a su/uery) the Teradataoptimier will normally use a (oin to optimie and locate the rows that are needed from withinthe dataase& This usage may e seen using the 064L,N& @oins are discussed in the ne.tchapter &

Page 107: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 107/401

-uali,ying Ta!le Names and Creating a Ta!le Alias

This section pro+ides techni/ues to specifically reference tale and columns throughout alldataases and to temporarily rename tales with an alias name& #oth of these techni/uesare necessary to pro+ide specific and uni/ue names to the optimier at SQL e.ecution time&

-uali,ying Column Names

Since column names within a tale must e uni/ue) the system knows which data to accesssimply y using the column name& =owe+er) when more that one tale is referenced y the-R3$ in a single S0L0CT) this may not e the case& The potential e.ists for columns of thesame domain to ha+e the same name in more than one tale& 2hen this happens) thesystem does not guess which column to reference& The SQL must e.plicitly declare whichtale to use for accessing the column&This declaration is called /ualifying the column name& ,f the SQL does not /ualify the columnname appearing in more than one tale) the system displays an error message that indicatestoo much amiguity e.ists in the /uery& Correlated su/ueries) addressed ne.t) and (oinprocessing) in the ne.t chapter ) oth make use of more than one tale at the same time&Therefore) many times it is important to make sure the system knows which tale's columns

to use for all portions of the SQL statement&

To /ualify a column name) the tale name and column name are connected using a periodor sometimes referred to as a dot !&%& The dot connects the names without a space to makethe two names work as a single reference name& =owe+er) if the column has different namesin the multiple tales) there is no confusion within the system and therefore) no need to/ualify the name&

To illustrate this concept) lets consider people instead of tales& -or instance) $ike is acommon name& ,f two $ikes are in different rooms and someone uses the name in either room) there is no confusion& =owe+er) if oth $ikes are in the same room and someoneuses the name) oth $ikes respond and therefore confusion e.ists& To eliminate the conflict)the use of the first and last names makes the identification uni/ue&

The synta. for /ualification le+els follow:

*le+el reference: Kdataase*name&Ktale*name&Kcolumn*name

8*le+el reference: Kdataase*name&Ktale*name

8*le+el reference: Ktale*name&Kcolumn*name

2hene+er all le+els are used) the first name is always the dataase) the second is thetale and the last is the column& =owe+er) when two names appear in a 8*le+el /ualification)the location of the names within the SQL must e e.amined to know for sure their meaning&Since the -R3$ names the tales) the first name of the /ualified names is a dataase nameand the second is a tale& Since columns are referenced in the S0L0CT list and 2=0R0clause) the first name is a tale name and the second is an G !all columns% or a single

column&,n Teradata) the following is a +alid statement) including the are+iation for S0L0CT andmissing -R3$:

S0L "#C&T#L0S&G H

This techni/ue is not NS, standard) howe+er) the 40 has e+erything needed to get allcolumns and rows out of the T#L0S tale in the "#C dataase&

Page 108: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 108/401

Creating an Alias ,or a Ta!le

Since tale names can e up to 9 characters long) to sa+e typing when the name is usedmore than once) a commonly used techni/ue is to pro+ide a temporary name for the talewithin the S0L0CT& The new temporary name for a tale is called an alias name&

3nce the alias is created for the tale) it is important to use the alias name throughout there/uest& 3therwise the system looks at the use of the full tale name as another tale and itcauses undesirale results& To estalish an alias for a tale) in the -R3$) simply follow thename of the tale with an S: -R3$ Ktale*name S Ktale*alias*name&

Correlated &u!>uery Processing

The correlated su/uery is a +ery powerful tool& ,t is an e.cellent techni/ue to use whenthere is a need to determine which rows to S0L0CT ased on one or more +alues fromanother tale& This is especially true when the +alue for comparison is ased on anaggregate& ,t comines su/uery processing and (oin processing into a single re/uest&

-or e.ample) one Teradata user has the need to ill their customers and incorporate the

latest payment date& Therefore) the latest date needs to e otained from the tale& So) thepayment date is found using the $6 aggregate in the su/uery& =owe+er) it must e thelatest payment date for that customer) which might e different for each customer& Theprocessing in+ol+es the su/uery locating the ma.imum date only for one customer account&

The correlated su/uery is perfect for this processing& ,t is more efficient and faster thanusing a normal su/uery with multiple +alues& 3ne reason for its speed is that it can performsome processing steps in parallel) as seen in an 064L,N& The other reason is that it onlyfinds the ma.imum date when a particular account is read for processing) not for allaccounts like a normal su/uery&

The operation for a correlated su/uery differs from that of a normal su/uery& ,nstead of comparing the selected su/uery +alues against all the rows in the main /uery) thecorrelated su/uery works ackward& ,t first reads a row in the main /uery) and then goesinto the su/uery to find all the rows that match the specified column +alue& Then) it gets thene.t row in the main /uery and retrie+es all the su/uery rows that match the ne.t +alue inthis row& This processing continues until all the /ualifying rows from the main S0L0CT aresatisfied&

 lthough this sounds terrily inefficient and is inefficient on other dataases) it is e.tremelyefficient in Teradata& This is due to the way the $4s handle this type of re/uest& The $4sare smart enough to rememer and share each +alue that is located&

Thus) when a second row comes into the comparison that contains the same +alue as anearlier row) there is no need to re*read the matching rows again& That operation has alreadyeen done once and the $4s rememer the answer from the first comparison&

The following is the synta. for writing a correlated su/uery:S0L0CT Kcolumn*name

  )Kcolumn*name O

-R3$ 3ta!le1name04  S Ktale*alias*nameO

2=0R0 Kcolumn*name ? 3 4 3? 4? 34 *

 ! S0L0CT MIN MAQ A8 *!Kcolumn*name%

  -R3$ 3ta!le1name94 S Ktale*alias*name O

Page 109: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 109/401

  2=0R0 3ta!le1name043column1name4?3ta!le1name943column1name4 %

H

The su/uery does not ha+e a semi*colon of its own& The S0L0CT in the su/uery is all partof the same primary /uery and shares the one semi*colon&

The aggregate +alue is normally otained using $,N) $6 or <I& Then this aggregate+alue is in turn used to locate the row or rows within a tale that compares e/uals) less thanor greater than this +alue&

This tale is used to demonstrate correlated su/ueries:

%igure 1 

5sing the ao+e tale) this Correlated su/uery finds the highest paid employee in eachdepartment:

S0L0CT LastWname

  )-irstWname

  )"eptWno

  )Salary ! format '[[[[)[[A&AA' %

-R3$ Employee7Ta!le A& emp

2=0R0 Salary M

 ! S0L0CT $6!Salary% -R3$ Employee7ta!le A& emt

  :;E"E empept7no ? emtept7no )

3R"0R # )1 H

Rows Returned

Last7name %irst7name ept7no &alary 7  

Smythe Richard 19 [E7)99&99

Chamers $andee 199 [7B)B9&99

Smith @ohn 899 [7B)999&99

Larkins Loraine 99 [79)899&99

Strickling Cletus 799 [7)99&99

Notice that oth of the tales ha+e een assigned alias names !emp for the main /uery andemt for the correlated su/uery%& #ecause the same 0mployee tale is used in the main/uery and the su/uery) one of them must e assigned an alias& The aliases are used in thesu/uery to /ualify and match the common domain +alues etween the two tales& Thiscoding techni/ue ;correlates; the main /uery tale to the one in the su/uery&

Page 110: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 110/401

The following Correlated su/uery uses the <I function to find all employees who earnless than the a+erage pay in their department:

S0L0CT LastWname

  )-irstWname

  )"eptWno

  )Salary ! format '[[[[)[[A&AA' %

-R3$ Employee7Ta!le A& emp

2=0R0 Salary KM ! S0L0CT <I!Salary% -R3$ Employee7ta!le A& e

  2=0R0 empept7no ? eept7no %

3R"0R # )1 H

Rows Returned

Last7name 7 

%irst7name ept7no &alary 7  

Smythe Richard 19 [E7)99&99Chamers $andee 199 [7B)B9&99

Coffing #illy 899 [71)BBB&BB

Larkins Loraine 99 [79)899&99

Reilly 2illiam 799 [E)999&99

0arlier in this chapter) it was indicated that a column from the su/uery cannot ereferenced in the main /uery& This is still true& =owe+er) nothing is wrong with using one or more column references from the main /uery within the su/uery to create a Correlatedsu/uery&

EQI&T&

 nother powerful resource that can e used with a correlated su/uery is the 06,STS& ,tpro+ides a true*false test within the 2=0R0 clause&

,n the synta. that follows) it is used to test whether or not a single row is returned from thesu/uery S0L0CT:

S0L0CT 'Kcharacter*literal'

 2=0R0 EQI&T& ! S0L0CT Kcolumn*name )Kcolumn*name O

  -R3$ Ktale*name

  2=0R0 Kcolumn*name P M K KM M K

  ! S0L0CT P$,N $6 <I !Kcolumn*name%

  -R3$ Ktale*name% %

H

,f a row is found) the 06,STS test is true) and con+ersely) if a row is not found) the result isfalse& 2hen a true condition is determined) the +alue in the S0L0CT is returned from themain /uery& 2hen the condition is determined to e false) no rows are selected&

Page 111: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 111/401

Since 06,STS returns one or no rows) it is a fast way to determine whether or not acondition is present within one or more dataase tales& The correlated su/uery can alsoe part of a (oin to add another le+el of test& ,t has potential to e +ery sophisticated&

 s an e.ample) to find all customers that ha+e not placed an order the N3T ,N su/uery cane used& Rememer) when you use the N3T ,N clause the N5LL needs to e consideredand eliminated using the ,S N3T N5LL check in the su/uery& 2hen using the N3T 06,STSwith a correlated su/uery) the same answer is otained) it is faster than a normal su/ueryand there is no concern for getting a null into the su/uery& These ne.t e.amples show the06,STS and the N3T 06,STS tests&

Notice that the ne.t S0L0CT is the same correlated su/uery as seen earlier) e.cept here itis utiliing the su/uery to find all customers with orders:

S0L0CT CustomerWname

-R3$ CustomerWtale S C5ST

2=0R0 EQI&T& ! S0L0CT G -R3$ 3rderWtale S 3T

  2=0R0 C5ST&CustomerWnumer M 3T&CustomerWnumer % H

7 Rows ReturnedCustomer7name 7

 ce Consulting

"ataases R 5s

#illy's #est Choice

6Z 4luming#y changing the 06,STS to a N$T EQI&T&) the ne.t S0L0CT finds all customers withoutorders:

S0L0CT CustomerWname

-R3$ CustomerWtale S C5ST

2=0R0 N$T EQI&T& ! S0L0CT G -R3$ 3rderWtale S 3T

  2=0R0 C5ST&CustomerWnumer M 3T&CustomerWnumer % H

1 Row Returned

Customer7name

 cme 4roducts

Since the Customer and 3rder tales are used in the ao+e Correlated su/uery) the talenames did not re/uire an alias& =owe+er) it was done to shorten the names to ease thee/uality coding in the su/uery&

 n added enefit of this techni/ue !N3T 06,STS% is that the presence of a N5LL does notaffect the performance& Notice that in oth su/ueries) the asterisk !G% is used for thecolumns& Since it is a true or false test) the columns are not used and it is the shortest way tocode the S0L0CT& ,f the column in the su/uery tale is a 4rimary ,nde. or a 5ni/ueSecondary ,nde.) the correlated su/uery can e +ery fast&The e.amples in this chapter only use a single column for the correlation& =owe+er) it iscommon to use more than one column from the main /uery in the correlated su/uery&

 lthough the techni/ues presented in this last chapter  seem relati+ely simple) they can e

Page 112: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 112/401

+ery powerful& 5nderstanding su/ueries and Correlated su/ueries can help you unleashthe power&

Chapter D: Soin Processing

Page 113: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 113/401

Soin Processing

  (oin is the comination of two or more tales in the same -R3$ of a single S0L0CTstatement& 2hen writing a (oin) the key is to locate a column in oth tales that is from acommon domain& Like the correlated su/uery) (oins are normally ased on an e/ualcomparison etween the (oin columns&

 n e.ample of a common domain column might e a customer numer& 2hether itrepresents a particular customer) as the primary key) in the Customer tale) or the customer that placed a specific order) as a foreign key) in the 3rder tale) it represents the same entityin oth tales& 2ithout a common +alue) a match cannot e made and therefore) no rowscan e selected using a (oin& n e/uality (oin returns matching rows&

 ny answer set that a su/uery can return) a (oin can also pro+ide& 5nlike the su/uery) a (oin lists all of its tales in the same -R3$ clause of the S0L0CT& Therefore) columns frommultiple tales are a+ailale for return to the user& The desired columns are the main factor in deciding whether to use a (oin or a su/uery& ,f only the columns come from a single taleare desired) a su/uery or a (oin work fine& =owe+er) if columns from more than one taleare needed) a (oin must e used& ,n <ersion 8 Release ) the numer of tales allowed in asingle (oin increased from si.teen !1E% to si.ty*four !E7% tales&

$riginal Soin &ynta.

The SQL (oin is a traditional and powerful tool in a relational dataase& The first differenceetween a (oin and a single tale S0L0CT is that multiple tales are listed using the -R3$clause& The first techni/ue) shown elow) uses a comma etween the tale names& This isthe same techni/ue used when listing multiple columns in the S0L0CT) 3R"0R # or mostother area that allows for the identification of more than one o(ect&

The following is the original (oin synta. for a two*tale (oin:

S0L0CT Ktale*name&OKcolumn*name

  )Ktale*name&Kcolumn*name O-R3$ 3ta!le1name04 O A& 3alias1name04

  J3ta!le1name94 O A& 3alias1name94

O :;E"E O3ta!le1name043column1name4? O3ta!le1name943column1name4

H

The following tales will e used to demonstrate the (oin synta.:

%igure F10 

Page 114: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 114/401

%igure F19 

The common domain etween these two tales is the customer numer& ,t is used in the2=0R0 clause with the e/ual condition to find all the rows from oth tales with matching+alues& Since the column has e.actly the same name in oth tales) it ecomes mandatoryto /ualify this column's name so that the 40 knows which tale to reference for the data&0+ery appearance of the customer numer in the S0L0CT must e /ualified&

The ne.t S0L0CT finds all of the orders for each customer and shows the Customer's name)3rder numer and 3rder total using a (oin:

S0L0CT cust&CustomerWnumer   )CustomerWname

  )3rderWnumer 

  )3rderWtotal !-3R$T '[[[)[[A&AA' %

%"$M Customer7ta!le A& cust

  J$rder7ta!le A& ord

:;E"E custcustomer7num!er ? ordcustomer7num!er 

3R"0R # 8 H

Rows Returned

Customer7num!er Customer7name $rder7num!er $rder7total

1817 C0 Consulting 188 [)111&7D

11111111 #illy's #estChoice

187E [18)7D&

11111111 #illy's #estChoice

1818 [B)99&A1

BD87E "ataases N*5 18B [1)81&E8

DBAEBB 6Z 4luming 18DDD [8)77&B7

,n the ao+e output) all of the customers) e.cept one) ha+e a single order on file& =owe+er)#illy's #est Choice has placed two orders and is displayed twice) once for each order& Noticethat the Customer numer in the S0L0CT list is /ualified and returned from the Customer tale& "oes it matter) in this (oin which tale is used to otain the +alue for the Customer numer

our answer should e no& This is ecause the +alue in the two tales is checked for e/ualin the 2=0R0 clause of the (oin& Therefore) the +alue is the same regardless of which taleis used& =owe+er) as mentioned earlier) you must use the tale name to /ualify any column

Page 115: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 115/401

name that e.ists in more than one tale with the same name& Teradata will not assumewhich column to use&

The following shows the synta. for a three*tale (oin:

S0L0CT Ktale*name1&OKcolumn*name

  )Ktale*name8&OKcolumn*name OO

  )Ktale*name&OKcolumn*name OO

-R3$ 3ta!le1name04 O A& 3alias1name04

  J3ta!le1name94 O A& 3alias1name94

  J3ta!le1name@4 O A& 3alias1name@4

:;E"E O3ta!le1name043column1name4 ? O3ta!le1name943column1name4

 OAN O3ta!le1name043column1name4 ? O3ta!le1name@43column1name4

H

The ne.t three tales are used to demonstrate a three*tale (oin:

%igure F1@ 

%igure F1 

Page 116: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 116/401

%igure F1D 

The first two tales represent the students and courses they can attend& Since a student cantake more than one class) the third tale StudentWCourse is used to associate the two maintales& ,t allows for one student to take many classes and one class to e taken y manystudents !a many*to*many relationship%&

The following S0L0CT (oins these three tales on the common domain columns to find allcourses eing taken y the students:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW,"

  )C&CourseWName S Course

-R3$ StudentWtale S S

  )CourseWtale S C

  )StudentWCourseWtale S SC

2=0R0 S&studentWid M SC&studentWid

  N" C&courseWid M SC&courseWid

3R"0R # Course) LastWname H

1 Rows Returned

LastName

%irst &tudent7I Course

$cRoerts Richard 8B998 d+ancedSQL

Page 117: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 117/401

Page 118: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 118/401

Page 119: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 119/401

Customer7name $rder7num!er $rder7total

#illy's #est Choice 18B 111&7D

#illy's #est Choice 18DDD 877&B7

The ao+e output resulted from 1 row in the customer tale eing (oined to all the rows of the order tale& The 2=0R0 limited the customer rows that participated in the (oin) ut didnot specify an e/ual comparison etween the (oin columns& s a result) it looks like #illyplaced fi+e orders) which is not correct& So) e careful when using product (oins ecauseSQL answers the /uestion as asked) not necessarily as intended&

2hen all rows of one tale are (oined to all rows of another tale) it is called a Cartesianproduct (oin or an unconstrained product (oin& Think aout this: if one tale has one millionrows and the other tale contains one thousand rows) the output is one trillion rows!1)999)999 rows G 1)999 rows M 1)999)999)999 rows%&

 s seen ao+e) the +ast ma(ority of the time) a product (oin has no meaningful output and isusually a mistake& The mistake is either that the 2=0R0 clause is omitted) a column

comparison is omitted for one of the tales using an N") or the tale is gi+en an alias andthe alias is not used !system thought it was an additional tale without a comparison%&

The ne.t S0L0CT is the same as the one ao+e) e.cept this time the entire 2=0R0 clausehas een commented out using FG and GF:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW,"

  ) CST!CourseWname S char!1A%% S Course

-R3$ StudentWtale S S

  )CourseWtale S C

  )StudentWCourseWtale S SC

 #5 the !olded comment eliminates the Roin and residual conditions

:;E"E &student7id ? &Cstudent7id

  AN Ccourse7id ? &Ccourse7id

  AN course7name LI2E K9"@K 5#

3R"0R # Course) LastWnameH

Since the (oin condition is con+erted into a comment) the output from the S0L0CT is aCartesian product that will return AB9 rows !19GD9G17MAB9% using these +ery small tales&The output is completely meaningless and implies that e+ery student is taking e+ery class&This output does not reflect the correct situation&

-orgetting to include the 2=0R0 clause does not make the (oin synta. incorrect& ,nstead) itresults in a Cartesian product (oin& lways use the 064L,N to +erify that the result of the

 (oin is reasonale efore e.ecuting the actual (oin& The following shows the output from an064L,N of the ao+e classic Cartesian product (oin& Notice that steps E and D indicate aproduct (oin on the condition that !1M1%& Since 1 is always e/ual to 1 e+ery time a row isread) all rows are (oined with all rows&0.planation

1& -irst) we lock a distinct $,J0L&;pseudo tale; for read on a Row=ash topre+ent gloal deadlock for $,J0L&SC&

Page 120: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 120/401

Page 121: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 121/401

Page 122: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 122/401

each tale and the columns eing compared& There is always one less @3,N F 3Ncomination than the numer of tales referenced in the -R3$&

The following synta. is for an ,NN0R @3,N with more than two tales:

S0L0CT Ktale*name1&OKcolumn*name

  ) Ktale*name8&OKcolumn*name OO

  ) Ktale*nameN&OKcolumn*name OO

%"$M Ktale*name1 S Kalias*name1 O

 OINNE" S$IN Ktale*name8 S Kalias*name8 O

 $N O3ta!le1name043column1name4 ? O3ta!le1name943column1name4

  OINNE" S$IN Ktale*nameN S Kalias*nameN O

  $N O3ta!le1name943column1name4 ? O3ta!le1nameN43column1name4

2=0R0 Kcondition*test O

H

The Ktale*nameN reference ao+e is intended to represent a +ariale numer of tales& ,t

might e a *tale) a 19*tale or up to a E7*tale (oin& The same approach is usedregardless of the numer of tales eing (oined together in a single S0L0CT&

The other difference etween these two (oin formats is that regardless of the numer of tales in the original synta.) there was only a single 2=0R0 clause& =ere) each additional,NN0R @3,N has its own 3N condition&

,f one 3N is omitted from the ,NN0R @3,N) an error code of D9E will e returned& This error keeps the (oin from e.ecuting) unlike the original synta.) where a forgotten (oin condition inthe 2=0R0 is allowed) ut creates an accidental Cartesian product (oin&

The ne.t ,NN0R @3,N is con+erted from the *tale (oin seen earlier:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW,"

  )CourseWname S Course

%"$M  StudentWtale S S INNE" S$IN StudentWCourseWtale S SC

  $N &student7id ? &Cstudent7id

  INNE" S$IN Course7ta!le A& C

  $N C&courseWid M SC&courseWid

  AN course7name LI2E K9"@K

3R"0R # Course) LastWnameH

Rows Returned

LastName

%irst &tudent7I Course

#ond @immy 881 <8RSQL-eatures

Page 123: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 123/401

LastName

%irst &tudent7I Course

=anson =enry 18E7 <8RSQL

-eatures2ilson Susie 81888 <8R

SQL-eatures

The ,NN0R @3,N synta. can use a 2=0R0 clause instead of a compound 3N comparison&,t can e used to add one or more residual conditions& residual condition is a comparisonthat is in addition to the (oin condition& 2hen it is used) the intent is to potentially eliminaterows from one or more of the tales&

,n other words) as rows are read the 2=0R0 clause compares each row with a condition todecide whether or not it should e included or eliminated from the (oin processing& The2=0R0 clause is applied as rows are read) efore the 3N clause& 0liminated rows do not

participate in the (oin against rows from another tale& -or more details) read the section on2=0R0 clauses at the end of this chapter&

The following is the same S0L0CT using a 2=0R0 to compare the Course name as aresidual condition instead of a compound !N"% comparison in the 3N:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW," )CourseWname S Course

-R3$ StudentWtale S S INNE" S$IN StudentWCourseWtale S SC

  $N  S&studentWid M SC&studentWid

  INNE" S$IN CourseWtale S C

  $N C&courseWid M SC&courseWid

:;E"E course7name LI2E K9"@K

3R"0R # Course) LastWnameH

 s far as the ,NN0R @3,N processing is concerned) the 40 will normally optimie oth of these last two (oins e.actly the same& The 064L,N is the est way to determine how theoptimier uses specific Teradata tales in a (oin operation&

$'TE" S$IN

 s seen pre+iously) the (oin processing matches rows from multiple tales on a columncontaining +alues from a common domain& $ost of the time) each row in a tale has amatching row in the other tale& =owe+er) we do not li+e in a perfect world and sometimesour data is not perfect& ,mperfect data is ne+er returned when a normal (oin is used and theimperfection may go unnoticed&

The sole purpose of an 35T0R @3,N is to find and return rows that do not match at leastone row from another tale& ,t is for ;e.ception; reporting) ut at the same time) it does the,NN0R @3,N processing too& Therefore) the intersecting !matching% common domain rowsare returned along with all rows without a matching +alue from another tale& This non*

Page 124: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 124/401

matching condition might e due to the e.istence of a N5LL or in+alid data +alue in the (oincolumn!s%&

-or instance) if the employee and department tales are (oined using an ,NN0R @3,N) itdisplays all the employees who work in a +alid department& $echanically) this means itreturns all of the employee rows that contain a +alue in the department numer column) as aforeign key) that matches a department numer +alue in the department tale) as a primarykey&

2hat it does not display are employees without a department numer !N5LL% andemployees with in+alid department numers !reaks referential integrity rules%& Theseadditional rows can e returned with the intersecting rows using one of the three formats for an 35T0R @3,N listed elow&

The three formats of an 35T0R @3,N are:

LeftWtale LE%T $'TE" S$IN RightWtale *left tale is outer tale

LeftWtale "I8;T $'TE" S$IN RightWtale *right tale is outer tale

LeftWtale %'LL $'TE" S$IN RightWtale *oth are outer tales

The 35T0R @3,N has an outer tale& The outer tale is used to direct which e.ception rowsare output& Simply put) it is the controlling tale of the 35T0R @3,N& s a result of thisfeature) all the rows from the outer tale will e returned) those containing matching domain+alues and those with non*matching +alues& The ,NN0R @3,N has only inner tales& To codean 35T0R @3,N it is wise to start with an ,NN0R @3,N& 3nce the (oin is working) the ne.tstep is to con+ert the word ,NN0R to 35T0R& The S0L0CT list for matching rows candisplay data from any of the tales in the -R3$& This is ecause a row with a matching rowe.ists in the tales& =owe+er) all non*matching rows with N5LL or in+alid data in the outer tale do not ha+e a matching row in the inner tale& Therefore) the entire inner tale row ismissing and no column is a+ailale for the S0L0CT list& This is the e/ui+alent of a N5LL&Since the e.ception row is missing) there is no data a+ailale for display& ll referencedcolumns from the missing inner tale rows will e represented as a N5LL in the display&

The asic synta. for a two*tale 35T0R @3,N follows:S0L0CT Ktale*name1&OKcolumn*name

  )Ktale*name8&OKcolumn*name

%"$M Ktale*name1 S Kalias*name1O

  LE%T "I8;T %'LL* O$'TE" S$IN

  Ktale*name8 S Kalias*name8O

  $N O3ta!le1name043column1name4 ? O3ta!le1name943column1name4

2=0R0 Kcondition*test O

H

5nlike the ,NN0R @3,N) there is no original (oin synta. operation for an 35T0R @3,N& The35T0R @3,N is a uni/ue answer set& The closest functionality to an 35T0R @3,N comesfrom the 5N,3N set operator) which is co+ered later in this ook& The other fantastic /ualityof the newer ,NN0R and 35T0R (oin synta. is that they oth can e used in the sameS0L0CT with three or more tales&

The ne.t se+eral sections e.plain and demonstrate all three formats of the 35T0R @3,N&The primary issue when using an 35T0R @3,N is that only one format can e used in aS0L0CT etween any two tales& The -R3$ list determines the outer tale for processing&,t is important to understand the functionality in order to chose the correct outer (oin&

Page 125: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 125/401

LE%T $'TE" S$IN

The outer tale is determined y its location in the -R3$ clause of the S0L0CT as shownhere:

K3uter*tale LE%T $'TE" S$IN K,nner*tale

3r 

K3uter*tale LE%T S$IN K,nner*tale

,n this format) the Customer tale is the one on the left of the word @3,N& Since this is aL0-T 35T0R @3,N) the Customer is the outer tale& This synta. can return all customer rows that match a +alid order numer !,NN0R @3,N% and Customers with N5LL or in+alidorder numers !35T0R @3,N%&

The ne.t S0L0CT shows customers with matching orders and those that need to e calledecause they ha+e not placed an order:

S0L0CT CustomerWname

  )3rderWnumer 

  )3rderWtotal !format '[[[)[[A&AA*' %

-R3$ CustomerWtale cust LE%T $'TE" S$IN 3rderWtale ord

  $N custcustomer7num!er ? ordcustomer7num!er 

3R"0R # 1

H

E Rows Returned

Customer7name $rder7num!er $rder7total

 ce Consulting 188 [)111&7D

 cme 4roducts

#illy's #est Choice 187E [18)7D&

#illy's #est Choice 1818 [B)99&A1

"ataases N*5 18B [1)81&E8

6Z 4luming 18DDD [8)77&B7

The ao+e output consists of all the rows from the Customer tale ecause it is the outer tale and there are no residual conditions& 5nlike the earlier ,NN0R @3,N) cme 4roducts isnow easily seen as the only customer without an order& Since cme 4roducts has no order 

at this time) the order numer and the order total are oth e.tended with the ;; to representa N5LL) or missing +alue from a non*matching row of the inner tale& This is a +eryimportant concept&

The result of the S0L0CT pro+ides the matching rows like the ,NN0R @3,N and the non*matching rows) or e.ceptions that are missed y the ,NN0R @3,N& ,t is possile to add theorder numer to an 3R"0R # to put all e.ceptions either at the front !SC% or ack!"0SC% of the output report&

Page 126: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 126/401

2hen using an 35T0R @3,N) the results of this (oin are stored in the spool area and containall of the rows from the outer tale& This includes the rows that match and all the rows thatdo not match from the (oin step& The only difference is that the non*matching rows arecarrying the N5LL +alues for all columns for missing rows from the inner tale&

The concept of a L0-T 35T0R @3,N is pretty straight forward with two tales& =owe+er)additional thought is re/uired when using more then two tales to preser+e rows from thefirst outer tale&

Rememer that the result of the first (oin is sa+ed in spool& This same spool is then used toperform all suse/uent (oins against any additional tales) or other spool areas& So if you

 (oin tales using an outer (oin the first two tales are (oined together with the spooledresults representing the new outer tale and then (oined with the third tale which ecomesthe R,I=T tale&

5sing the Student) Course and StudentWCourse tales) the following S0L0CT preser+es thee.ception rows from the Student tale as the outer tale) throughout the entire (oin& Sinceoth (oins are written using the L0-T 35T0R @3,N and the Student tale is the tale namethat is the furthest to the left it remains as the outer tale:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW," )CourseWname S Course

%"$M StudentWtale S S

  LE%T $'TE" S$IN StudentWCourseWtale S SC

  $N &student7id ? &Cstudent7id

  LE%T $'TE" S$IN CourseWtale S C

  $N Ccourse7id ? &Ccourse7id

3R"0R # Course) LastWname H

17 Rows Returned

LastName

%irst &tudent7I Course

Larkins $ichael 78799

$cRoerts Richard 8B998 d+ancedSQL

2ilson Susie 81888 d+ancedSQL

@ohnson Stanley 8E9999 "ataase dministration

Smith ndy 79 "ataase dministration

"elaney "anny 87E8 ,ntroduction toSQL

=anson =enry 18E7 ,ntroduction toSQL

#ond @immy 881 4hysical

Page 127: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 127/401

LastName

%irst &tudent7I Course

"ataase"esign

=anson =enry 18E7 TeradataConcepts

4hillips $artin 1889 TeradataConcepts

Thomas 2endy 87181 TeradataConcepts

#ond @immy 881 <8R SQL-eatures

=anson =enry 18E7 <8R SQL-eatures

2ilson Susie 81888 <8R SQL-eatures

The ao+e output contains all the rows from the Student tale as the outer tale in the three*tale L0-T 35T0R @3,N& The 35T0R @3,N returns a row for a student named $ichaelLarkins e+en though he is not taking a course& Since) his course row is missing) no coursename is a+ailale for display& s a result) the output is e.tended with a N5LL in coursename) ut ecomes part of the answer set&

Now) it is known that a student isn't taking a course& ,t might e important to know if there areany courses without students& The pre+ious (oin can e con+erted to determine this fact yrearranging the tale names in the -R3$ to make the Course tale the outer tale) or yusing the R,I=T 35T0R @3,N&

"I8;T $'TE" S$IN

 s indicated earlier) the outer tale is determined y its position in the -R3$ clause of theS0L0CT& Consider the following:

K,nner*tale "I8;T $'TE" S$IN K3uter*tale

3r 

K,nner*tale "I8;T S$IN K3uter*tale

,n the ne.t e.ample) the Customer tale is still written efore the 3rder tale& Since it is now

a R,I=T 35T0R @3,N and the 3rder tale is on the right of the word @3,N) it is now theouter tale& Rememer) all rows can e returned from the outer tale?

To include the orders without customers) the pre+iously seen L0-T 35T0R @3,N has eencon+erted to a R,I=T 35T0R @3,N& ,t can e used to return all of the rows in the 3rder tale) those that match customer rows and those that do not match customers&

The following is con+erted to a R,I=T 35T0R @3,N to find all orders:

S0L0CT CustomerWname

Page 128: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 128/401

Page 129: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 129/401

B Rows Returned

LastName

%irst &tudent7I Course

$cRoerts Richard 8B998 d+anced

SQL2ilson Susie 81888 d+anced

SQL

"elaney "anny 87E8 ,ntroductionto SQL

=anson =enry 18E7 ,ntroductionto SQL

Logical"ataase"esign

#ond @immy 881 <8R SQL

-eatures

=anson =enry 18E7 <8R SQL-eatures

2ilson Susie 81888 <8R SQL-eatures

Now) using the output from the 35T0R @3,N on the Course tale) it is apparent that no oneis enrolled in the Logical "ataase "esign course& The enrollment needs to e increased or the room needs to e freed up for another course& 2here inner (oins are great at findingmatches) outer (oins are great at finding oth matches and prolems&

%'LL $'TE" S$IN

The last form of the 35T0R @3,N is a -5LL 35T0R @3,N& ,f oth Customer and 3rder e.ceptions are to e included in the output report) then the synta. should appear as:

K3uter*tale %'LL $'TE" S$IN K3uter*tale

3r 

K3uter*tale %'LL S$IN K3uter*tale

  -5LL 35T0R @3,N uses oth of the tales as outer tales& The e.ceptions are returnedfrom oth tales and the missing column +alues from either tale are e.tended with N5LL&This puts the L0-T and R,I=T 35T0R @3,N output into a single report&

To return the customers with orders) and include the orders without customers andcustomers without orders) the following -5LL 35T0R @3,N can e used:

S0L0CT CustomerWname

  )3rderWnumer 

  )3rderWtotal !format '[[[)[[A&AA*' %

-R3$ CustomerWtale cust %'LL $'TE" S$IN 3rderWtale ord

  $N custcustomer7num!er ? ordcustomer7num!er 

Page 130: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 130/401

3R"0R # 1 H

D Rows Returned

Customer7name $rder7num!er $rder7total

AAAAAA [1&99*

 ce Consulting 188 [)111&7D

 cme 4roducts

#illy's #est Choice 1818 [B)99&A1

#illy's #est Choice 187E [18)7D&

"ataases N*5 18B [1)81&E8

6Z 4luming 18DDD [8)77&B7

The output from the S0L0CT consists of all the rows from the 3rder and Customer talesecause they are now oth outer tales in a -5LL 35T0R @3,N&

The total numer of rows returned is more difficult to predict with a -5LL 35T0R @3,N& Theanswer set contains: one row for each of the matching rows from the tales) plus one row for each of the missing rows in the left tale) plus one for each of the missing rows in the righttale&

Since oth tales are outer tales) not as much thought is re/uired for choosing the outer tale& =owe+er) as mentioned earlier the ,NN0R and 35T0R (oin processing can ecomined in a single S0L0CT& The ,NN0R @3,N still eliminates all non*matching rows& Thisis when the most consideration needs to e gi+en to the appropriate outer tales&

Like all (oins) more than two tales can e (oined using a -5LL 35T0R @3,N) up to E7tales& The ne.t -5LL 35T0R @3,N synta. uses Student and Course tales for the outer tales through the entire (oin process:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW,"

  )CourseWname S Course

-R3$ StudentWtale S S

  %'LL $'TE" S$IN StudentWCourseWtale S SC

  $N &student7id ? &Cstudent7id

  %'LL $'TE" S$IN CourseWtale S C

  $N Ccourse7id ? &Ccourse7id

3R"0R # Course) LastWname H

1 Rows Returned

LastName

%irst &tudent7I Course

Larkins $ichael 78799

$cRoerts Richard 8B998 d+anced

Page 131: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 131/401

LastName

%irst &tudent7I Course

SQL

2ilson Susie 81888 d+anced

SQL

@ohnson Stanley 8E9999 "ataase dministration

Smith ndy 79 "ataase dministration

"elaney "anny 87E8 ,ntroduction toSQL

=anson =enry 18E7 ,ntroduction toSQL

Logical

"ataase"esign

#ond @immy 881 4hysical"ataase"esign

=anson =enry 18E7 TeradataConcepts

4hillips $artin 1889 TeradataConcepts

Thomas 2endy 87181 TeradataConcepts

#ond @immy 881 <8R SQL-eatures

=anson =enry 18E7 <8R SQL-eatures

2ilson Susie 81888 <8R SQL-eatures

The ao+e S0L0CT uses the Student) Course and ;Student Course; !associati+e% tales in a-5LL 35T0R @3,N& ll three tales are outer tales& The ao+e includes one non*matchingrow from the Student tale with a null in the course name and one non*matching row fromthe course tale with nulls in all three columns from the Student tale& Since the StudentCourse tale is also an outer tale) if there were any non*matching rows in it) they can also

e returned containing a null in its columns& =owe+er) since it is an associati+e tale usedonly for a many*to*many relationship etween the Student and Course tales) missing rowsin it would indicate a serious usiness prolem&

 s a reminder) the result of the first (oin step is stored in spool) which is temporary workspace that the system uses to complete each step of the S0L0CT& Then) the spool area isused for each consecuti+e @3,N step& This continues until all of the tales ha+e een (oinedtogether) two at a time& =owe+er) the spool areas are not held until the end of the S0L0CT&,nstead) when the spool is no longer needed) it is released immediately& This makes more

Page 132: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 132/401

spool a+ailale for another step) or y another user& The release can e seen in the064L,N output as !Last 5se% for a spool area&

 lso) when using Teradata) do not spend a lot of time worrying aout which tales to (oinfirst& The optimier makes this choice at e.ecution time& The optimier always looks for thefastest method to otain the re/uested rows& ,t uses data distriution and inde.demographics to make its final decision on a methodology& So) the tales (oined first in thesynta.) might e the last tales (oined in the e.ecution plan&

 ll dataases (oin tales two at a time) ut most dataases (ust pick which tales to (oinased on their position in the -R3$& Sometimes when the SQL runs slow) the user (ustchanges the order of the tales in the (oin& 3therwise) (oin schemas must e uilt to tell theR"#$S how to (oin specific tales&

Teradata is smart enough) using e.plicit or implicit STT,ST,CS) to e+aluate which tales to (oin together first& 2hene+er possile) four tales might e (oined at the same time) ut it isstill done as two) two*tale (oins in parallel& @oins in+ol+ing millions of rows are considereddifficult for most dataases) ut Teradata (oins them with ease&

,t is a good idea to use the Teradata 064L,N) to see what steps the optimier plans to use

to accomplish the re/uest& 4rimarily in the eginning you are looking for an estimate of thenumer of rows that will e returned and the time cost to accomplish it& , recommend usingthe 064L,N efore each (oin as you are learning to make sure that the result is reasonale&

,f these numers appear to e too high for the tales in+ol+ed) it is proaly a CartesianproductH which is not good& The 064L,N disco+ers the product (oin within seconds insteadof hours& ,f it were actually running) it would e wasting resources y doing all the e.tra workto accomplish nothing& 5se the 064L,N to learn this fact the easy way and fi. it&

C"$&& S$IN

  CR3SS @3,N is the NS, way to write a product (oin& This means that it (oins one or morerows participating from one tale with all the participating rows from the other tale& s

mentioned earlier in this chapter) there is not a large application for a product (oin and e+enfewer for a Cartesian (oin&

 lthough there are not many applications for a CR3SS @3,N) consider this: an airline mightuse one to determine the location and numer of routes needed to fly from one hu to all of the other cities they ser+e& potential route ;(oins; e+ery city to the hu& Therefore) the resultneeds a product (oin& 4roaly what should still e a+oided is to fly from e+ery city to e+eryother city !Cartesian (oin%&

  CR3SS @3,N is controlled using a 2=0R0 clause& 5nlike the other (oin synta.) a CR3SS@3,N results in a synta. error if an 3N clause is used&

The following is the synta. for the CR3SS @3,N:

S0L0CT Ktale*name1&OKcolumn*name

  )Ktale*name8&OKcolumn*name O

%"$M Ktale*name1 S Kalias*name1O

  C"$&& S$IN Ktale*name8 S Kalias*name8O

2=0R0 Kcondition*test O

H

Page 133: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 133/401

The ne.t S0L0CT performs a CR3SS @3,N !product (oin% using the Student and Coursetales:

S0L0CT LastWname) CourseWname

-R3$ StudentWtale C"$&& S$IN CourseWtale

:;E"E Course7I ? 066 =

19 Rows Returned

Last7name Course7name

4hillips TeradataConcepts

=anson TeradataConcepts

Thomas TeradataConcepts

2ilson Teradata

Concepts

@ohnson TeradataConcepts

$cRoerts TeradataConcepts

#ond TeradataConcepts

"elaney TeradataConcepts

Smith Teradata

ConceptsLarkins Teradata

Concepts

Since e+ery student is not taking e+ery course) this output has +ery little meaning from astudent and course perspecti+e& =owe+er) this same data can e +aluale in determining apotential for a situation or the resources that are needed to determine ma.imum roomcapacities& -or e.ample) it helps if the "ean wants to know the ma.imum numer of seatsneeded in a classroom if e+ery student were to enroll for e+ery SQL class& =owe+er) therows are proaly counted !C35NT!G%% and not displayed&

This S0L0CT uses a CR3SS @3,N to populate a deri+ed tale !discussed later%) which isthen used to otain the final count:

S0L0CT S5$!nrstudent% !T,TL0 'Total SQL Seats Needed'%

-R3$ (&ELECT Course7IJ C$'NT(5) A& N!r&tudent

  %"$M &tudent7ta!le C"$&& S$IN Course7ta!le

  :;E"E Course7I BET:EEN 966 and 9HH

  8"$'P BY 0) "T H

1 Row Returned

Page 134: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 134/401

Total &-L &eats Needed

9

The pre+ious S0L0CT can also e written to use the 2=0R0 clause to the main S0L0CT tocompare the rows of the deri+ed tale called "T instead of only uilding those rows&Compare the pre+ious S0L0CT with the ne.t one and determine which is more efficient&

S0L0CT S5$ !nrstudent% !T,TL0 'Total SQL Seats Needed'%

-R3$ !S0L0CT CourseW,") C35NT!G% S NrStudent

  -R3$ StudentWtale C"$&& S$IN CourseWtale

  IR354 # 1% "T

:;E"E Course7I BET:EEN 966 and 9HH=

2hich do you find to e more efficient

 t first glance) it would appear that the first is more efficient ecause the CR3SS @3,Ninside the parentheses for a deri+ed tale is not a Cartesian product& ,nstead) the CR3SS

@3,N that populates the deri+ed tale is constrained in the 2=0R0 to only SQL coursesrather than all courses& =owe+er) the 40 optimies them the same& , told you that Teradatawas smart?

&el, Soin

  Self @oin is simply a (oin that uses the same tale more than once in a single (oinoperation& The first re/uirement for this type of (oin is that the tale must contain two differentcolumns of the same domain& This may in+ol+e de*normalied tales&

-or instance) if the 0mployee tale contained a column for the manager's employee numer and the manager is an employee) these two columns ha+e the same domain& #y (oining onthese two columns in the 0mployee tale) the managers can e (oined to the employees&

The ne.t S0L0CT (oins the 0mployee tale to itself as an employee tale and also as amanager tale to find managers& Then) the managers are (oined to the "epartment tale toreturn the first ten characters of the manager's name and their entire department name:

S0L0CT $gr&LastWname !Title '$anager Name') format '6!19% %

  )"epartmentWname !Title '-or "epartment '%

-R3$ Employee7ta!le A& Emp

  INNE" S$IN Employee7ta!le A& Mgr 

  3N 0mp&$anagerW0mpW," M $gr&0mployeeWNumer 

  ,NN0R @3,N "epartmentWtale S "ept  3N 0mp&"epartmentWnumer M "ept&"epartmentWnumer 

3R"0R # 8 H

The self (oin can e the original synta. !tale ) tale%) an ,NN0R) 35T0R) or CR3SS (oin& nother re/uirement is that at least one of the tale references must e assigned an alias&Since the alias name ecomes the tale name) the tale is now treated as two completelydifferent tales&

Page 135: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 135/401

Normally) a self (oin re/uires some degree of de*normaliation to allow for two columns inthe same tale to e part of the same domain& Since our 0mployee tale does not containthe manager's employee numer) the output cannot e shown& =owe+er) the concept isshown here&

Alternati<e S$IN # $N Coding

There is another format that may e used for coding oth the ,NN0R and 35T0R @3,Nprocessing& 4re+iously) all of the e.amples and synta. for (oins of more than two tales usedan 3N immediately following the @3,N tale list&

The following demonstrates the other coding synta. techni/ue:

S0L0CT Ktale*name1&OKcolumn*name

  )Ktale*name8&OKcolumn*name

  )Ktale*name&OKcolumn*name

-R3$ Ktale*name1 S Kalias*name1 O

  ,NN0R O @3,N Ktale*name8 S Kalias*name8 O

  ,NN0R O @3,N Ktale*nameN S Kalias*nameN O

  3N Ktale*name8&OKcolumn*name M Ktale*nameN&OKcolumn*name

 3N Ktale*name1&OKcolumn*name M Ktale*name8&OKcolumn*name

H

2hen using this techni/ue) care should e taken to se/uence the @3,N and 3N portionscorrectly& There are two primary differences with this style compared to the early synta.&-irst) the @3,N statements and tale names are all together& ,n one sense) this is more likethe synta. of: talename1) talename8 as seen in the original (oin&

Second) the 3N statement se/uence is re+ersed& ,n the ao+e synta. diagram) the 3Nreference for talename8 and talenameN is efore the 3N reference for talename1 and

talename8& =owe+er) the @3,N for Ktale*name1 and Ktale*name8 are still efore the@3,N of Ktale*name8 and Ktale*nameN& ,n other words) the first 3N goes with the last@3,N when they are nested using this techni/ue&

The following three*tale ,NN0R @3,N seen earlier is con+erted here to use this re+ersedform of the 3N comparisons:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW," )CourseWname S Course

-R3$ StudentWtale S S

  INNE" S$IN StudentWCourseWtale S SC

  INNE" S$IN CourseWtale S C

  $N C&courseWid M SC&courseWid

  $N S&studentWid M SC&studentWid

2=0R0 courseWname L,J0 'U<8RU'

3R"0R # Course) LastWnameH

4ersonally) we prefer the first techni/ue in which e+ery @3,N is followed immediately y its3N condition& =ere are our reasons:

Page 136: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 136/401

,t is harder to accidentally forget to code an 3N for a @3,N) they are together& Less deugging time needed) and when it is needed) it is easier&

#ecause the (oin allows E7 tales in a single S0L0CT) the SQL in+ol+ingse+eral tales may e longer than a single page can display& Therefore)many of the @3,N clauses will e on a different page than its corresponding3N condition& ,t might re/uire paging ack and forth multiple times to locate

all of the 3N conditions for e+ery @3,N clause& This in+ol+es too much effort&5sing the @3,N F 3N) they are physically ne.t to each other&  dding another tale into the (oin re/uires careful thought and placement for 

oth the @3,N and the 3N& 2hen using the @3,N F 3N) they can e placedalmost anywhere in the -R3$ clause&

Adding "esidual Conditions to a Soin

$ost of the e.amples in this ook ha+e included all rows from the tales eing (oined&=owe+er) in the world of Teradata with millions of rows eing stored in a single tale)additional comparisons are proaly needed to reduce the numer of rows returned& Thereare two ways to code residual conditions& They are: the use of a compound condition usingthe 3N) or a 2=0R0 clause may e used in the new @3,N& These residual conditions are in

addition to the (oin e/uality in the 3N clause&

Consideration should e gi+en to the type of (oin when including the 2=0R0 clause& Thefollowing paragraphs discuss the operational aspects of mi.ing an 3N with a 2=0R0 for ,NN0R and 35T0R @3,N operations&

INNE" S$IN

The 2=0R0 clause works e.actly the same when used with the ,NN0R @3,N as it does onall other forms of the S0L0CT& ,t eliminates rows at read time ased on the condition eingchecked and any inde. columns in+ol+ed in the comparison&

Normally) as fewer rows are read) the faster the SQL will run& ,t is more efficient ecause

fewer resources such as disk) ,F3) cache space) spool space) and C45 are needed&Therefore) whene+er possile) it is est to eliminate unneeded rows using a 2=0R0condition with an ,NN0R @3,N& , like the use of 2=0R0 ecause all residual conditions arelocated in one place&

The following samples are the same (oin that was performed earlier in this chapter& =ere)one uses a 2=0R0 clause and the other a compound comparison +ia the 3N:

S0L0CT CustomerWname

  )3rderWnumer 

  )3rderWtotal !-3R$T '[[[)[[A&AA' %

-R3$ CustomerWtale S cust INNE" S$IN 3rderWtale S ord

  $N cust&customerWnumer M ord&customerWnumer :;E"E CustomerWname L,J0 '#illyU'

3R"0R # "0SC

H

3r 

S0L0CT CustomerWname

  )3rderWnumer 

Page 137: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 137/401

  )3rderWtotal !-3R$T '[[[)[[A&AA' %

-R3$ CustomerWtale S cust INNE" S$IN 3rderWtale S ord

  $N cust&customerWnumer M ord&customerWnumer 

  AN CustomerWname L,J0 '#illyU'

3R"0R # "0SC H

8 Rows Returned

Customer7name $rder7num!er $rder7total

#illy's #est Choice 187E [18)7D&

#illy's #est Choice 1818 [B)99&A1

The output is e.actly the same with oth coding methods& This can e +erified using the064L,N& 2e recommend using the 2=0R0 clause with an inner (oin ecause itconsolidates all residual conditions in a single location that is easy to find when changes areneeded& lthough there are multiple 3N comparisons) there is only one 2=0R0 clause&

$'TE" S$IN

Like the ,NN0R @3,N) the 2=0R0 clause can also e used with the 35T0R @3,N&=owe+er) its processing is the opposite of the techni/ue used with an ,NN0R @3,N and other SQL constructs& ,f you rememer) with the ,NN0R @3,N the intent of the 2=0R0 clause wasto eliminate rows from one or all tales referenced y the S0L0CT&

2hen the 2=0R0 clause is coded with an 35T0R @3,N) it is e.ecuted last) instead of first&Rememer) the 35T0R @3,N returns e.ceptions& The e.ceptions must e determined usingthe (oin !matching and non*matching rows% and therefore rows cannot e eliminated at readtime& ,nstead) they go into the (oin and into spool& Then) (ust efore the rows are returned tothe client) the 2=0R0 checks to see if rows can e eliminated from the spooled (oin rows&

The following demonstrates the difference when using the same two techni/ues in the35T0R @3,N& Notice that the results are different:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW,"

  )CourseWname S Course

-R3$ StudentWtale S S

  "I8;T $'TE" S$IN StudentWCourseWtale S SC

  $N S&studentWid M SC&studentWid

  "I8;T $'TE" S$IN CourseWtale S C  $N C&courseWid M SC&courseWid

:;E"E Course LI2E K&-LK

3R"0R # CourseWname) LastWname

H

D Rows Returned

Page 138: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 138/401

LastName

%irst &tudent7I Course

$cRoerts Richard 8B998 d+ancedSQL

2ilson Susie 81888 d+ancedSQL

"elaney "anny 87E8 ,ntroductionto SQL

=anson =enry 18E7 ,ntroductionto SQL

#ond @immy 881 <8R SQL-eatures

=anson =enry 18E7 <8R SQL-eatures

2ilson Susie 81888 <8R SQL-eatures

Notice that only courses with SQL as part of the name are returned&

2hereas the ne.t S0L0CT using the same condition as a compound comparison has adifferent result:

S0L0CT LastWname !Title 'Last Name'%

  )-irstWname S -irst

  )S&StudentW,"

  )CourseWname S Course

-R3$ StudentWtale S S

  R,I=T 35T0R @3,N StudentWCourseWtale S SC

  3N S&studentWid M SC&studentWid

  R,I=T 35T0R @3,N CourseWtale S C

  $N Ccourse7id ? &Ccourse7id AN Course LI2E K&-LK

3R"0R # Course) LastWname H

11 Rows Returned

LastName

%irst &tudent7I Course

$cRoerts Richard 8B998 d+ancedSQL

2ilson Susie 81888 d+ancedSQL

"ataase dministration

Page 139: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 139/401

LastName

%irst &tudent7I Course

"elaney "anny 87E8 ,ntroduction toSQL

=anson =enry 18E7 ,ntroduction toSQL

Logical"ataase"esign

4hysical"ataase"esign

TeradataConcepts

#ond @immy 881 <8R SQL

-eatures

=anson =enry 18E7 <8R SQL-eatures

2ilson Susie 81888 <8R SQL-eatures

The reason for the difference makes sense after you think aout the functionality of the35T0R @3,N& Rememer that an 35T0R @3,N retains all rows from the outer tale) thosethat match and those that do not match the 3N comparison& Therefore) the row shows up)ut as a non*matching row instead of as a matching row&

There is one last consideration when using a 2=0R0 clause with an 35T0R @3,N& lways

use columns from the outer tale in the 2=0R0& The reason: if columns of the inner taleare referenced in a 2=0R0) the optimier will perform an ,NN0R @3,N and not an 35T0R@3,N) as coded& ,t does this since no rows will e returned e.cept those of the inner tale&Therefore) an ,NN0R @3,N is more efficient& The phrase ;merge (oin; can found e in the064L,N output instead of ;outer (oin; to +erify this e+ent&

The ne.t S0L0CT was e.ecuted earlier as an inner (oin and returned 8 rows& =ere it haseen con+erted to an outer (oin& =owe+er) the output from the 064L,N shows in step thatan inner !merge% (oin will e used ecause customer name is a column from the inner tale!Customer tale%:

064L,N

S0L0CT CustomerWname

  )cust&CustomerWnumer   )3rderWnumer 

  )3rderWtotal !-3R$T '[[[)[[A&AA' %

-R3$ CustomerWtale S cust R,I=T 35T0R @3,N 3rderWtale S ord

  3N cust&customerWnumer M ord&customerWnumer 

2=0R0 CustomerWname L,J0 '#illyU'

3R"0R # "0SC H

Page 140: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 140/401

0.planation1& -irst) we lock a distinct $,J0L&;pseudo tale; for read on a Row=ash to

pre+ent gloal deadlock for $,J0L&cust&8& Ne.t) we lock a distinct $,J0L&;pseudo tale; for read on a Row=ash to

pre+ent gloal deadlock for $,J0L&ord&& 2e lock $,J0L&cust for read) and we lock $,J0L&ord for read&7& 2e do an all*$4s R0TR,0<0 step from $,J0L&ord y way of an all*rows

scan with no residual conditions into Spool 8) which is redistriuted yhash code to all $4s& Then we do a S3RT to order Spool 8 y row hash&The sie of Spool 8 is estimated with low confidence to e 7 rows& Theestimated time for this step is 9&9 seconds&

& 2e do an all*$4s @3,N step from $,J0L&cust y way of a Row=ashmatch scan with a condition of !;$,J0L&cust&CustomerWname L,J0 ]#illyU^;%) which is (oined to Spool 8 !Last 5se%& $,J0L&cust and Spool 8 are

 (oined using a merge Roin) with a (oin condition of  ! ;$,J0L&cust&CustomerWnumer M CustomerWnumer;%& The result goesinto Spool 1) which is uilt locally on the $4s& Then we do a S3RT toorder Spool 1 y the sort key in spool field1& The sie of Spool 1 isestimated with no confidence to e 7 rows& The estimated time for thisstep is 9&1B seconds&

E& -inally) we send out an 0N" TRNSCT,3N step to all $4s in+ol+ed inprocessing the re/uest&* The contents of Spool 1 are sent ack to the user as the result of statement 1& The total estimated time is 9&88 seconds&

$'TE" S$IN ;ints

The easiest way to egin writing an 35T0R @3,N is to:1& Start with an ,NN0R @3,N and con+ert to an 35T0R @3,N&

3nce the ,NN0R @3,N is working) change the appropriate ,NN0R descriptors toL0-T 35T0R) R,I=T 35T0R or -5LL 35T0R (oin ased on the desire toinclude the e.ception rows& Since ,NN0R and 35T0R (oins can e used together)one (oin at a time can e changed to +alidate the output& 5se the (oin diagram

elow to con+ert the ,NN0R @3,N to an 35T0R @3,N&8& -or (oins with greater than two tales) think of it as: @3,N two tales at atime&

,t makes the entire process easier y concentrating on only two tales instead of all tales& The optimier will always (oin two tales) whether serially or in paralleland it is smart enough to do it in the most efficient manner possile&& "on't worry aout which tales you (oin first&

The optimier will determine which tales should e (oined first for the optimalplan&7& The 2=0R0 clause) if used in an 35T0R @3,N to eliminate rows&

 & ,t is applied after then (oin is complete) not when rows are read likethe ,nner @oin&

#& ,t should reference columns from the outer tale& ,f columns from the

,nner tale are referenced in a 2=0R0 clause) the optimier willmost likely perform a merge (oin !,NN0R% for efficiency& This isactually an ,NN0R @3,N operation and can e seen in the 064L,Noutput&

Page 141: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 141/401

Parallel Soin Processing

There are four asic types of (oins that Teradata can perform depending on thecharacteristics of the tale definition& 2hen the (oin domain is the primary inde. !4,% column)with a uni/ue secondary inde. !5S,% the (oin is referred to as a nested (oin and in+ol+es) atmost) three $4s& The second type of (oin is a merge (oin) with three different forms of amerge (oin) ased on the re/uest& The newest type of (oin in Teradata is the Row =ash (oinusing the pre*sorted Row =ash +alue instead of a sorted data +alue match& This is eneficialsince the data row is stored ased on the row hash +alue and not the data +alue& The lasttype is the product (oin&

,n Teradata) each $4 performs all (oin processing in parallel locally& This means thatmatching +alues in the (oin columns must e on the same $4 to e matched& 2hen therows are not distriuted and stored on the same $4) they must e temporarily mo+ed to thesame $4) in spool& Rememer) rows are distriuted on the +alue in the 4, column!s%& ,f 

 (oins are performed on the 4, of oth tales) no row mo+ement is necessary& This is ecausethe rows with the same 4, +alue are on the same $4 Y easy) ut not always practical& $ost

 (oins use a primary key) which might e the 54, and a foreign key) which is proaly not the4,&

Regardless of the (oin type) in a parallel en+ironment) the mo+ement of at least one row isnormally re/uired& This mo+ement puts all matching rows together on the same $4& Themo+ement is usually re/uired due to the user's choice of a 4,& Rememer) it is the 4, data

+alue that is used for hashing and row distriution to an $4& Therefore) since the (oinedcolumns are mostly columns other than the 4,) rows need to e redistriuted to another 

 $4& The redistriuted rows will e temporarily stored in spool space and used from therefor the (oin processing&

The optimier will attempt to determine the most efficient path for data row mo+ement& ,tschoice will e ased on the amount of data in+ol+ed& The three (oin strategies a+ailale are:1* duplicate all rows of one tale onto e+ery $4) 8* redistriute the rows of one tale y

Page 142: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 142/401

hashing the non*4, (oin column and sending them to the $4 containing the matching 4,row) and * redistriute oth tales y hashed (oin column +alue&

The duplication of all rows is a popular approach when the non*4, column is on a smalltale& Therefore) copying all rows is faster than hashing and distriuting all rows& Thistechni/ue is also used when doing a product (oin and worse) a Cartesian product (oin&

2hen oth tales are large) the redistriution of the non*4, column row to the $4 with the4, column will e used to sa+e space on each $4& ll participating rows are redistriuted sothat they are on the same $4 with the same data +alue used y the 4, for the other tale&

The last choice is the redistriution of all participating row from oth tales y hashing on the (oin column& This is re/uired when the (oin is on a column that is not the 4, in either tale&5sing this last type of (oin strategy will re/uire the most spool space& Still) this techni/ueallows Teradata to /uickly (oin tales together in a parallel en+ironment& #y comining thespeed of the #N0T) the e.perience of the 40 optimier) and the hashing capailities of Teradata the data can e temporarily mo+ed to meet the demands of the SQL /uery& "o notunderestimate the importance or rilliance of this capaility& s /ueries change and placenew demands on the data) Teradata is fle.ile and powerful enough to mo+e the datatemporarily and /uickly to the proper location&

Redistriution re/uires o+erhead processing& ,t has nothing to do with the (oin processing)ut e+erything to do with preparing for the (oin& This is the primary reason that many taleswill use a column that is not the primary key column as a N54,& This way) the (oin columnsused in the 2=0R0 or the 3N are used for distriution and the rows are stored on the same

 $4& Therefore) the (oin is performed without need to redistriute data& =owe+er) normallysome re*distriution is needed& So) make sure to C3LL0CT STT,ST,CS !see ""L chapter %on the (oin columns& The strategy that the optimie chooses can e seen in output from an064L,N&

Soin Inde. Processing

Sometimes) regardless of the (oin plan or indices defined) certain (oins cannot e performedin a short enough time frame to satisfy the users& 2hen this is the case) another alternati+e

must e e.plored& Later chapters in this ook discuss temporary tales and summary talesas a+ailale techni/ues& ,f none of these pro+ide a +iale solution) yet another option isneeded&

The other way to impro+e (oin processing is the use of a @3,N ,N"06& ,t is a pre*(oin thatstores the (oined rows& Then) when the (oin inde. ;co+ers; the user's S0L0CT columns) theoptimier automatically uses the stored (oin inde. rows to retrie+e the pre*(oined rows frommultiple tales instead of doing the (oin again& The term used here is co+ers& ,t means that if all columns re/uested y the user are present in the (oin inde. it is used& ,f e+en one columnis re/uested that is not in the (oin inde.) it cannot e used& Therefore) the actual (oin must eprocessed to get that e.tra column&

The speed of the (oin inde. is its main ad+antage& To enhance its on*going use) whene+er a

+alue in a column in a row for a tale used within a (oin inde. is changed) the corresponding+alue in the (oin inde. row!s% is also changed& This keeps the (oin inde. consistent with therows in the actual tales&

The synta. for using a (oin inde.:

CR0T0 @3,N ,N"06 K(oin*inde.*name S

K+alid*(oin*select*goes*here

H

Page 143: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 143/401

There is no way for a client to directly reference a (oin inde.& The optimier is the onlycompound that has access to the (oin inde.&

-or more information on (oin inde. usage) see the NCR reference manual&

Chapter B: ate and Time Processing

ATEJ TIMEJ and TIME&TAMP

Teradata has a date function and a time function uilt into the dataase and the aility tore/uest this data from the system& ,n the early releases) "T0 was a +alid data type for storing the comination of year) month and day) ut T,$0 was not& Now) T,$0 andT,$0ST$4 are oth +alid data types that can e defined and stored within a tale&

The Teradata R"#$S stores the date in $$"" format on disk& The is an offset+alue from the ase year of 1A99& The $$ is the month +alue from 1 to 18 and the "" is theday of the month& 5sing this format) the dataase can currently work with dates eyond the

year 999& So) it appears that Teradata is J compliant& Teradata always stores a date as anumeric ,NT0I0R +alue&

The following calculation demonstrates how Teradata con+erts a date to the $$"" dateformat) for storage of @anuary 1) 1AAA:

The stored data for the date @anuary 1) 1AAA is con+erted to:

 lthough years prior to 8999 look fairly ;normal; with an implied year for the 89 th Century)after 8999 years do not look like the normal concept of a year !199%& -ortunately) Teradataautomatically does all the con+ersion and makes it transparent to the user& The remainder of this ook will pro+ide SQL e.amples using oth a numeric date as well as the character formats of ]F$$F""^ and ]*$$*""^&

The ne.t con+ersion shows the data stored for @anuary 1) 8999 !notice that M199 or 199years from 1A99%:

 dditionally) since the date is stored as an integer and an integer is a signed +alue) datesprior to the ase year of 1A99 can also e stored& The same formula applies for the datecon+ersion regardless of which century& =owe+er) since dates prior to 1A99) like 1B99 aresmaller +alues) the result of the sutraction is a negati+e numer&

AN&I &tandard ATE "e,erence

Page 144: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 144/401

C5RR0NTW"T0 is the NS, Standard name for the date function& ll references to theoriginal "T0 function continues to work and return the same date information& -urthermore)they oth display the date in the same format&

INTE8E"ATE

,NT0I0R"T0 is the default display format for most Teradata dataase client utilities& ,t isin the form of F$$F""& ,t has nothing to do with the way the data is stored on disk) onlythe format of the output display& The current e.ception to this is Queryman& Since it uses the3"#C) it displays only the NS, date) as seen elow&

Later in this ook) the Teradata  -3R$T function is also addressed to demonstratealternati+e arrangements regarding year) month and day for output presentation&

%igure G10 To change the output default display) see the "T0-3R$ options in the ne.t section of thischapter&

AN&IATE

Teradata was updated in release <8R to include the NS, date display and reser+ed name&The NS, format is: *$$*""&

%igure G19 

Since we are now eyond the year 1AAA) it is ad+isale to use this NS, format to guaranteethat e+eryone knows the difference etween all the years of each century as: 8999) 1A99and 1B99& ,f you regularly use tools +ia the 3"#C) which is software for 3pen "ata #aseConnecti+ity) this is the default display format for the date&

ATE%$"M

Teradata has traditionally een 8J compliant& ,n reality) it is compliant to the years eyond999& =owe+er) the default display format using F$$F"" is not NS, compliant&

,n Teradata) release <8R allows a choice of whether to display the date in the originaldisplay format !F$$F""% or the newer NS, format !*$$*""%& 2hen installed)Teradata defaults at the system le+el to the original format) called ,NT0I0R"T0& =owe+er)this system default "T0-3R$ may e o+er*ridden y updating the "#S Control record&

The "T0-3R$:Controls default display of selected datesControls e.pected format for import and e.port of dates as character strings

!]F$$F""^ or ]*$$*""^% in the load utilitiesCan e o+er*ridden y 5S0R or within a Session at any time&

&ystem Le<el e,inition

$3",- I0N0RL 17 M 9 FG ,NT0I0R"T0 !F$$F""% GF

Page 145: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 145/401

$3",- I0N0RL 17 M 1 FG NS,"T0 !*$$*""% GF

'ser Le<el e,inition

CR0T0 5S0R username &&&&&&&

  _

  _

  _

  "T0-3R$MP,NT0I0R"T0 NS,"T0 H

&ession Le<el eclaration

,n addition to setting the system default in the control record) a user can re/uest the formatfor their indi+idual session& The synta. is:

S0T S0SS,3N "T0-3R$ M PNS,"T0 ,NT0I0R"T0 H

,n the ao+e settings) the ;; is used to represent an 3R condition& The setting can e

 NS,"T0 or ,NT0I0R"T0& Regardless of the "T0-3R$ eing used) NS,"T0 or ,NT0I0R"T0) these define load and display characteristics only& Rememer) the date isalways stored on disk in the $$"" format) ut the "T0-3R$ allows you to select theformat for display&

ATE Processing

$uch of the time spent processing dates is dedicated to storage and reference& et) thereare times that one date yields or deri+es a second date& -or instance) once a ill has eensent to a customer) the e.pectation is that payment comes E9 days later& The challengeecomes the correct calculation of the e.act due date&

Since Teradata stores the date as an ,NT0I0R) it allows simple and comple. mathematics

to calculate new dates from dates& The ne.t S0L0CT operation uses the Teradata datearithmetic and "T0-3R$M,NT0I0R"T0 to show the month and day of the payment duedate in E9 days:

S0L0CT $rder7dateU6 !Title '"ue "ate'%

  )3rderWdate

  )3rderWtotal !-3R$T '[[[[)[[[&AA'%

-R3$ 3rderWtale

2=0R0 3rderWdate 'ABF18F1' H

7 Rows Returned

ue

ate

$rder7date $rder7total

AAF18F9A AAF19F19 [1)81&E8

AAF9F98 AAF91F91 [B)99&A1

AAF11F9B AAF9AF9A [8)77&B7

AAF11F9 AAF19F91 [)111&7D

Page 146: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 146/401

Page 147: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 147/401

ages in years& To con+ert the days to years) again math can e used as seen in the followingS0L0CT:

sel !!1991991!date%% * !81991!date%%%FE !Title '$ike;s ge ,n ears'%H

1 Row Returned

Mi+eKs Age in Years

7B

2ow? , feel so much younger now& This is where di+ision egins to make sense) utrememer) the ,NT0I0R is not a "T0& t the same time) it assumes that all years ha+eE days& ,t only does the math operations specified in the SQL statement&

Now) what day was he orn

The ne.t S0L0CT uses the concatenation) date arithmetic and a lank T,TL0 to produce thedesired output:

sel '$ike was orn on day ' !!81991!date%% * !191!date%%% $3" D !T,TL0 ;%H

1 Row Returned

$ike wasorn on day

8

The ao+e sutraction results in the numer of days etween the two dates& Then) the $3"D di+ides y D to get rid of the numer of weeks and results in the remainder& $3" D canonly result in +alues 9 thru E !always 1 less than the $3" operator%& Since @anuary 1) 1A99 !191!date% % is a $onday) $ike was orn on a 2ednesday&

%igure G1 

The following S0L0CT uses a year's worth of days to deri+e a new date that is E daysaway:

S0L0CT 3rderWdate

  )3rderWdate XE !Title 'ear Later "ate'%

  )3rderWtotal !-3R$T '[[[[)[[[&AA'%

-R3$ 3rderWtale

3R"0R # 1 H

Rows Returned

$rder7date Year  Later ate

$rder7total

ABF9F97 AAF9F97 [18)7D&

Page 148: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 148/401

Page 149: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 149/401

sutraction or going ack in time +ersus ahead& dditionally) ecause months ha+e a +aryingnumer of days) the output from math is likely to e different than the ""W$3NT=S&

The ne.t S0L0CT uses the ""W$3NT=S function as an alternati+e to the pre+iousS0L0CT operations for showing the month and day of the payment due date in 8 months:

S0L0CT ""W$3NT=S!3rderWdate) 8% !Title '"ue "ate'%

  )3rderWdate !-3R$T '*$$*""'%

  )3rderWtotal !-3R$T '[[[[)[[[&AA'%

-R3$ 3rderWtale

3R"0R # 8 H

Rows Returned

ueate

$rder7date $rder7total

1AAB*9D*97

1AAB*9*97 [18)7D&

1AAA*9*91

1AAA*91*91 [B)99&A1

1AAA*11*9A

1AAA*9A*9A [8)77&B7

1AAA*18*91

1AAA*19*91 [)111&7D

1AAA*18*19

1AAA*19*19 [1)81&E8

The ""W$3NT=S function also takes into account the last day of each month& Thefollowing goes from the last day of one month to the last day of another month:

S0L0CT ""W$3NT=S!'1AAB*98*8B')18G8% S LeapWheadW8yrs

  ) ""W$3NT=S!'8999*9*1')*1% S LeapW#ackW8yrs

  ) ""W$3NT=S!'8991*9E*9')1% S 2ith9W1 H

1 Row Returned

Leap7Ahead79yrs Leap7Bac+79yrs :ith@67@07  

8999*98*8A 8999*98*8A 8991*9D*1

2hether going forward or ackward or ackward in time) a leap year is still recognied using ""W$3NT=S&

AN&I TIME

Teradata has also een updated in <8R to include the NS, time display) reser+ed nameand the new T,$0 data type& dditionally) the clock is now intelligent and can carry secondso+er into minutes&

C5RR0NTWT,$0 is the NS, name of the time function& ll current SQL references to theoriginal Teradata T,$0 function continue to work&

Page 150: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 150/401

%igure G1D 

 lthough the time could e displayed prior to release <8R) when stored) it was con+erted toa character column type& Now) T,$0 is also a +alid data type) may e defined in a tale) andretains the ==:$$:SS properties&

 s well as creating a T,$0 data type) intelligence has een added to the clock software& ,tcan increment or decrement T,$0 with the result increasing to the ne.t minute or decreasingfrom the pre+ious minute ased on the addition or sutraction of seconds&

%igure G1 

T,$0 representation character display length:

T,$0 !9% * 19:17:B C=R!B%

T,$0 !E% * 19:17:B&8911E C=R!1%

EQT"ACT

Compatiility: NS,

#oth "T0 and T,$0 data are special in terms of relational design& Since each is comprisedof parts and they are decomposale& "ecomposale data is data that is not at its mostgranular le+el& -or e.ample) you may only want to see the hour&

The 06TRCT function is designed to do the decomposition on these data types& ,t workswith oth the "T0 and T,$0 functions& This includes the original and newer NS,e.pressions& The operation is to pull a specific portion of the SQL techni/ues&

The synta. for 06TRCT:

S0L0CT EQT"ACT(YEA" %"$M Kdate*data%

  )EQT"ACT(M$NT; %"$M Kdate*data%

  )EQT"ACT(AY %"$M Kdate*data%

  )EQT"ACT(;$'" %"$M Ktime*data%

  )EQT"ACT(MIN'TE %"$M Ktime*data%

  )EQT"ACT(&EC$N %"$M Ktime*data%

-R3$ Ktale*nameH

The ne.t S0L0CT uses the 06TRCT with date and time literals to demonstrate the codingtechni/ue and the resulting output:

S0L0CT 06TRCT!0R -R3$ '8999*19*91'% S rW4art

  )06TRCT!$3NT= -R3$ '8999*19*91'% S $thW4art

  )06TRCT!" -R3$ '8999*19*91'% S "ayW4art

Page 151: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 151/401

Page 152: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 152/401

and 7 days) notice it uses doule /uotes to allow reser+ed words as alias names and NS,"T0 in the comparison and display:

S0L0CT '"ue "ate:' !Title ;% FG title as 8 single /uotes for no title GF

  )EQT"ACT(Month %"$M $rder7dateU) A& VMonthV

  )EQT"ACT(ay %"$M $rder7dateU) A& VayV

  )EQT"ACT(Year %"$M $rder7dateU) A& VYearV

  )3rderWdate !-3R$T 'mmmdd)yyyy'%

  )3rderWtotal

-R3$ 3rderWtale

2=0R0 3rderWdate '1AAB*18*1'

3R"0R # 8) H

7 Rows Returned

 Month ay Year $rder7date $rder7total

"ue"ate:

E 1AAA @an 91)1AAA

B99&A1

"ue"ate:

11 18 1AAA ug 9A)1AAA

877&B7

"ue"ate:

18 7 1AAA 3ct 19)1AAA

111&7D

"ue"ate:

18 1 1AAA 3ct 19)1AAA

181&E8

Implied E.tract o, ayJ Month and Year 

Compatiility: Teradata 0.tension

 lthough the 06TRCT works great and it is NS, compliant) it is a function& Therefore) itmust e e.ecuted and the parameters passed to it to identify the desired portion as data&Then) it must pass ack the answer& s a result) there is additional o+erhead processingre/uired to use it&

,t was mentioned earlier that Teradata stores a date as an integer and therefore allows mathoperations to e performed on a date&

The synta. for implied e.tract:

S0L0CT 3date1data4 M$ 066 #5 e.tracts the day 5#

  J(3date1data4 #066) M$ 066 #5 e.tracts the month 5#

  J3date1data4 #06666 U0H66 #5 e.tracts the year 5#

-R3$ Ktale*name

H

The following S0L0CT uses math to e.tract the three portions of $ike's literal irthday:

Page 153: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 153/401

S0L0CT ((0600660(date)) M$ 066 ) S "ayWportion

  J (((0600660(date))#066) M$ 066 ) S $onthWportion

  J ((0600660(date))#06666 U 0H66) S earWportion H

1 Row Returned

ay7portion Month7portion Year7portion

1 19 8991

Rememer that the date is stored as yyymmdd& The literal +alues are used here to pro+ide adate of 3ct& 1) 8991& The day portion is otained here y making the dd portion !last 8 digits%the remainder from the $3" 199& The month portion is otained y di+iding y 199 toeliminate the dd to lea+e the mm !new last 8 digits% portion the remainder of the $3" 199&The year portion is the trickiest& Since it is stored as yyy !yyyy Y 1A99%) we must add 1A99 tothe stored +alue to con+ert it ack to the yyyy format& 2hat do you suppose the 06TRCTfunction does Same thing&

AN&I TIME&TAMP nother new data type) added to Teradata in <8R to comply with the NS, standard) is theT,$0ST$4& T,$0ST$4 is now a display format) a reser+ed name and a new data type& ,tis a comination of the "T0 and T,$0 data types comined together into a single columndata type&

%igure G1G 

Timestamp representation character display length:

T,$0ST$4!9% 1AAB*18*9D 11:D:B C=R!1A%

T,$0ST$4!E% 1AAB*18*9D 11:D:B&81999 C=R!8E%

Notice that there is a space etween the "T0 and T,$0 portions of a timestamp& This is are/uired element to delimit or separate the day from the hour&

TIME $NE&

,n <8R) Teradata has the aility to access and store oth the hours and the minutesreflecting the difference etween the user's time one and the system time one& -rom a2orld perspecti+e) this difference is normally the numer of hours etween a specificlocation on 0arth and the 5nited Jingdom location that was historically called Ireenwich$ean Time !I$T%& Since the Ireenwich oser+atory has een ;decommissioned); the new

reference to this same time one is called 5ni+ersal Time Coordinate !5TC%&

  time one relati+e to London !5TC% might e:

  time one relati+e to New ork !0ST% might e:

Page 154: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 154/401

=ere) the time ones used are represented from the perspecti+e of the system at 0ST& ,n theao+e) it appears to e ackward& This is ecause the time one is set using the numer of hours that the system is from the user&

To show an e.ample of T,$0 +alues) we randomly chose a time (ust after 19:99$& #elow)the +arious T,$0 with time one +alues are designated as:

T,$0 '19:1D:B' * T,$0!9%T,$0 '19:1D:B*9B:99' * T,$0!9% 2,T= T,$0 Z3N0

T,$0 '19:1D:B&81999X9A:9' * T,$0 2,T= T,$0 Z3N0

T,$0ST$4 with time one is represented as:

T,$0ST$4 '1AAA*19*91 19:1D:B' * T,$0ST$4!9%

T,$0ST$4 '1AAA*19*91 19:1D:B*9B:99'

  * T,$0ST$4!9% 2,T= T,$0 Z3N0

T,$0ST$4 '1AAA*19*91 19:1D:B&81999X9A:9'

  * T,$0ST$4 2,T= T,$0 Z3N0

The default) for oth T,$0 and T,$0ST$4) is to display si. digits of decimal precision inthe second's portion&

Time ones are set either at the system le+el !"#S Control%) the user le+el !when user iscreated or modified%) or at the session le+el as an o+erride&

&etting TIME $NE&

  Time Zone should e estalished for the system and e+ery user in each different timeone&

Setting the system default time one:

$3",- I0N0RL 1E M . FG =ours) nM *18 to 1 GF$3",- I0N0RL 1D M . FG $inutes) n M *A to A GF

Setting a 5ser's time one re/uires choosing either L3CL) N5LL) or a +ariety of e.plicit+alues:

CR0T0 5S0R m(l

  T,$0 Z3N0 M L3CL FG use system le+el GF

  M N5LL FG no default) set to system or session le+el at logon

  GF

  M '1E:99' FG e.plicit setting GF

  M *'9E:9' FG e.plicit setting GFSetting a Session's time one:

S0T T,$0 Z3N0 L3CL H FG use system le+el GF

S0T T,$0 Z3N0 5S0R H FG use user le+el GF

S0T T,$0 Z3N0 ,NT0R<L '9B:99' =35R T3 $,N5T0 H FG e.plicit setting GF

  Teradata session can modify the time one during normal operations without re/uiring alogoff and logon&

Page 155: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 155/401

Page 156: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 156/401

Page 157: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 157/401

NormaliXing TIME $NE&

Teradata has the aility to incorporate the use of time ones into SQL for a relati+e +iew of the data ased on one locality +ersus another&

This S0L0CT ad(usts the data rows ased on their T,$0 Z3N0 data in the tale:

S0L0CT TsWone

  )TSWwithWone

  JCA&T(T&7ith7Xone A& TIME&TAMP()) A& T7Normal

-R3$ TstampWtest

3R"0R # H

7 Rows Returned

T&7Xone T&7ith7Xone T7Normal

5TC 8999*19*919B:18:99&999999X9:99

8999*19*919:18:99&999999

0ST 8999*19*919B:18:99&999999X99:99

8999*19*919B:18:99&999999

4ST 8999*19*919B:18:99&999999*9:99

8999*19*9111:18:99&999999

=JT 8999*19*919B:18:99&999999*11:99

8999*19*911A:18:99&999999

Notice that the Time Zone +alue was added to or sutracted from the time portion of the timestamp to ad(ust them to a perspecti+e of the same time one& s a result) at that moment) ithas normalied the different Times Zones in respect to the system time&

 s an illustration) when the transaction occurred at B:18 $ locally in the 4ST Time Zone) itwas already 11:18 $ in 0ST) the location of the system& The times in the columns ha+eeen normalied in respect to the time one of the system&

ATE and TIME Inter<als

To make Teradata SQL more NS, compliant and compatile with other R"#$S SQL) NCRhas added ,NT0R<L processing& ,nter+als are used to perform "T0) T,$0 andT,$0ST$4 arithmetic and con+ersion&

 lthough Teradata allowed arithmetic on "T0 and T,$0) it was not performed inaccordance to NS, standards and therefore) an e.tension instead of a standard& 2ith,NT0R<L eing a standard instead of an e.tension) more SQL can e ported directly from

an NS, compliant dataase to Teradata without con+ersion&

 dditionally) when a data +alue was used to perform date or time math) it was always;assumed; to e at the lowest le+el for the definition !days for "T0 and seconds for T,$0%&Now) any portion of either can e e.pressed and used&

Page 158: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 158/401

%igure G1H 

'sing Inter<als

To use the NS, synta. for inter+als) the SQL statement must e +ery specific as to what thedata +alues mean and the format in which they are coded& NS, standards tend to elengthier to write and more restricti+e as to what is and what is not allowed regarding the+alues and their use&

Simple ,NT0R<L 0.amples using literals:

,NT0R<L '99' "!%

,NT0R<L '' $3NT=

,NT0R<L *'8B' =35R

Comple. ,NT0R<L 0.amples using literals:

,NT0R<L '7 1B:9:19' " T3 S0C3N"

,NT0R<L '18:18' =35R T3 $,N5T0

,NT0R<L '18:18' $,N5T0 T3 S0C3N"

-or se+eral of the ,NT0R<L literals) their use seems o+ious ased on the literalnonnumeric literals used& =owe+er) notice that the =35R T3 $,N5T0 and the $,N5T0 T3S0C3N" ao+e) are not so o+ious& Therefore) the declaration of the meaning is important&-or instance) notice that they are coded as character literals& This allows for use of a slash!F%) colon !: % and space as part of the literal& lso) notice the use of a negati+e time frame

re/uires a ;−; sign to e outside of the /uotes& The presence of the /uotes also denotes thatthe numeric +alues are treated as character for con+ersion to a point in time&

The format of a timestamp re/uires the space etween the day and hour when usinginter+als& -or e.ample) notice the lank space etween the day and hour in the compound" T3 =35R inter+al& 2ithout the space) it is an error&

INTE"AL Arithmetic ith ATE and TIME

To use "T0 and T,$0 arithmetic) it is important to keep in mind the results of +ariousoperations&

%igure G106 

Page 159: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 159/401

%igure G100 

Note: ,t makes little sense to add two dates together&

Traditionally) the output of the sutraction is an integer) up to 8&17D illion& =owe+er)Teradata knows that when an integer is used in a formula with a date) it must represent anumer of days& The following uses the NS, representation for a "T0:

S0L0CT !"T0 '1AAA*19*91' * "T0 '1ABB*19*91'% S ssumedW"ays H

1 Row Returned

Assumed7ays

791D

The ne.t S0L0CT uses the NS, e.plicit " inter+al:

S0L0CT !"T0 '1AAA*19*91' * "T0 '1ABB*19*91'% " S ctualW"ays H

GGGG -ailure D7 ,nternal -ield 3+erflow

The ao+e re/uest fails on an o+erflow of the ,NT0R<L& 5sing this NS, inter+al) the outputof the sutraction is an inter+al with 7 digits& The default for all inter+als is 8 digits andtherefore the o+erflow occurs until the S0L0CT is modified with "!7%) elow:

S0L0CT !"T0 '1AAA*19*91' * "T0 '1ABB*19*91'% AY() S ctualW"ays H

1 Row Returned

Actual7ays

791D

Normally) a date minus a date yields the numer of days etween them& To see monthsinstead) the following S0L0CT operations use literals to demonstrate the con+ersionsperformed on +arious "T0 and ,NT0R<L data:

S0L0CT !"T0 '8999*19*91' Y "T0 '1AAA*19*91'% $3NT= !Title '$onths'% H

1 Row Returned

Months

18

The ne.t S0L0CT shows ,NT0R<L operations used with T,$0:

S0L0CT !T,$0 '18:7:91' * T,$0 '19:19:91'% =35R S ctualWhours

  )!T,$0 '18:7:91' * T,$0 '19:19:91'% $,N5T0!% S ctualWminutes

  )!T,$0 '18:7:91' * T,$0 '19:19:91'% S0C3N"!7% S ctualWseconds

Page 160: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 160/401

  )!T,$0 '18:7:91' * T,$0 '19:19:91'% S0C3N"!7)7% S ctualWseconds7 H

1 Row Returned

Actual7hours Actual7minutes Actual7seconds Actual7seconds

8 1 A99&999999 A99&9999

 lthough ,nter+als tend to e more accurate) they are more restricti+e and therefore) morecare is re/uired when coding them into the SQL constructs& =owe+er) one miscalculation)like in the o+erflow e.ample) and the SQL fails& dditionally) AAAA is the largest +alue for anyinter+al& Therefore) it might e re/uired to use a comination of inter+als) such as: $3NT=Sto "S in order to recei+e an answer without an o+erflow occurring&

CA&T 'sing Inter<als

Compliance: NS,

The CST function was seen in an earlier chapter as the NS, method for con+erting data

from one type to another& ,t can also e used to con+ert one ,NT0R<L to another ,NT0R<L representation& lthough the CST is normally used in the S0L0CT list) it worksin the 2=0R0 clause for comparison reasons&

#elow is the synta. for using the CST with a date:

S0L0CT CA&T (3inter<al4 A& INTE"AL 3inter<al4 )

-R3$ Ktale*name H

K,nter+al M P " " T3 =35R " T3 $,N5T0 " T3 S0C3N"

  =35R =35R T3 $,N5T0 $,N5T0 $,N5T0 T3 S0C3N"

The following con+erts an ,NT0R<L of E years and 8 months to an ,NT0R<L numer of months:

S0L0CT CST! !,NT0R<L 'E*98' 0R T3 $3NT=% S ,NT0R<L $3NT= %H

1 Row Returned

169Z

D7

Logic seems to dictate that if months can e shown) the years and months should also ea+ailale& This re/uest attempts to con+ert 199 months to show the numer of years andmonths:

S0L0CT CST!,NT0R<L '199' $3NT= S 0R T3 $3NT=%  !Title 'ears ` $onths'% H

GGG -ailure D7 ,nter+al -ield 3+erflow&

The ao+e failed ecause the numer of months takes more than two digits to hold anumer of years greater than AA& The fi. is to change the 0R to 0R!% and rerun:

S0L0CT CST!!,NT0R<L '1898' $3NT=% S ,NT0R<L 0R!% T3 $3NT= %

  !Title 'ears ` $onths'% H

Page 161: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 161/401

1 Row Returned

 Years [ Months

199*98

The iggest ad+antage in using the ,NT0R<L processing is that SQL written on another system is now compatile with Teradata&

 t the same time) care must e taken to use a representation that is large enough to containthe answer& The default is 8 digits and anything larger) 7 digits ma.imum) must e literallyre/uested& The incorrect sie results in an SQL runtime error& The ne.t section  on theSystem Calendar demonstrates another way to con+ert from one inter+al of time to another&

$E"LAP&

Compatiility: Teradata 0.tension

2hen working with dates and times) sometimes it is necessary to determine whether twodifferent ranges ha+e common points in time& Teradata pro+ides a #oolean function to make

this test for you& ,t is called 3<0RL4SH it e+aluates true) if multiple points are in common)otherwise it returns a false&

The synta. of the 3<0RL4S is:

S0L0CT Kliteral

  2=0R0 (3start1date1time4J 3end1date1time4) $E"LAP&

  (3start1date1time4J 3end1date1time4)

H

The following S0L0CT tests two literal dates and uses the 3<0RL4S to determine whether or not to display the character literal:

S0L0CT 'The dates o+erlap' !T,TL0 ;%

2=0R0 (ATE K9660160160KJ ATE K96601001@6K) $E"LAP&

  (ATE K966010610DKJ ATE K96601091@0K) H

1 Row Returned

The dates o+erlap

The literal is returned ecause oth date ranges ha+e from 3ctoer 1 through No+emer 9 in common&

The ne.t S0L0CT tests two literal dates and uses the 3<0RL4S to determine whether or not to display the character literal:

S0L0CT 'The dates o+erlap' !T,TL0 ;%2=0R0 !"T0 '8991*91*91') "T0 '8991*11*9'% 3<0RL4S

  !"T0 '8991*11*9') "T0 '8991*18*1'% H

No Rows -ound

The literal was not selected ecause the ranges do not o+erlap& So) the common single dateof No+emer 9 does not constitute an o+erlap& 2hen dates are used) 8 days must ein+ol+ed and when time is used) 8 seconds must e contained in oth ranges&

Page 162: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 162/401

Page 163: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 163/401

The ne.t page contains a list of column names) their respecti+e data types) and a rief e.planation of the potential +alues calculated for each when using the CL0N"R +iew:

Column Name ata Type escription

calendarWdate "T0 Standard

Teradatadate

  0/ui+ancy: "T0

dayWofWweek #T0,NT 1*D) where 1is Sunday

  0/ui+ancy: !"T0 Y"T0% $3"D

dayWofWmonth #T0,NT 1*1) somemonths ha+eless

  0/ui+ancy: "T0 $3"D

dayWofWyear S$LL,NT 1*EE) @ulianday of theyear 

  0/ui+ancy: "T0 $3"199 or  06TRCT"ay

dayWofWcalendar ,NT0I0R Numer of  days since91F91F1A99

  0/ui+ancy: "T0 Y191!date%

weekdayWofWmonth #T0,NT These/uence of a day withina month)firstSundayM1)secondSundayM8)etc

 0/ui+ancy: None known

weekWofWmonth #T0,NT 9*)se/uentialweeknumer within amonth)partial weekstarts at 9

Page 164: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 164/401

Column Name ata Type escription

  0/ui+ancy: None known

weekWofWyear #T0,NT 9*)se/uential

weeknumer within ayear) partialweek startsat 9

  0/ui+ancy: None known

weekWofWcalendar ,NT0I0R Numer of  weeks since91F91F1A99

  0/ui+ancy: !"T0 Y191!date%%FD

monthWofW/uarter #T0,NT 1*) each/uarter has months

  0/ui+ancy: CS006TRCT$onth

monthWofWyear #T0,NT 1*18) up to18 monthsper year 

  0/ui+ancy: "T0F199$3" 199 or 06TRCT$onth

monthWofWcalendar ,NT0I0R Numer of  monthssince91F91F1A99

  0/ui+ancy: Noneneeded

/uarterWofWyear #T0,NT 1*7) up to 7/uarters per year 

  0/ui+ancy: CS006TRCT$onth

/uarterWofWcalendar ,NT0I0R Numer of  /uarterssince91F91F1A99

  0/ui+ancy: None

Page 165: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 165/401

Column Name ata Type escription

needed

yearWofWcalendar S$LL,NT Starts at1A99

  0/ui+ancy: 06TRCTear 

,t appears that the least useful of these columns are all the names that end with;WofWcalendar&; s seen in the ao+e descriptions) these +alues are all calculated starting atthe calendar reference date of @anuary 1) 1A99& 5nless a usiness transaction occurred onthat date) they are meaningless&

The iggest enefit of the System Calendar is for determining the following: "ay of the2eek) 2eek of the $onth) 2eek of the ear) $onth of the Quarter and Quarter of the ear&

$ost of the +alues are +ery straightforward& =owe+er) the column called 2eekWofW$onthdeser+es some discussion& The description indicates that a partial week is week numer 9&

partial week is any first week of a month that does not start on a Sunday& Therefore) not allmonths ha+e a week 9 ecause some do start on Sunday&

=a+ing these column references a+ailale) there is less need to make as many compoundcomparisons in SQL& -or instance) to simply determine a /uarter re/uires comparisons)one for each month in that /uarter& 2orse yet) each /uarter of the year will ha+e differentmonths& Therefore) the SQL might re/uire modification each time a different /uarter wasdesired&

The ne.t S0L0CT uses the System Calendar to otain the +arious date related rows for 3ctoer 1) 8991:

,n #T0Q

&foldline on&sidetitles on

sel G from sys7calendarcalendar 

where calendar7date?0600660 H

1 Row Returned

calendarWdate 91F19F91

dayWofWweek 8

dayWofWmonth 1

dayWofWyear 8D7

dayWofWcalendar D1E7

weekdayWofWmonth 1

weekWofWmonth 9

weekWofWyear A

weekWofWcalendar 9A

monthWofW/uarter 1

Page 166: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 166/401

Page 167: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 167/401

  )2kdayW"ay C=R!A% % H

ins into 2eekW"ays !1)'Sunday'%H

ins into 2eekW"ays !8)'$onday'%H

ins into 2eekW"ays !)'Tuesday'%H

ins into 2eekW"ays !7)'2ednesday'%H

ins into 2eekW"ays !)'Thursday'%H

ins into 2eekW"ays !E)'-riday'%H

ins into 2eekW"ays !D)'Saturday'%H

3nce the tale is a+ailale) it can e incorporated into SQL to make the output easier to readand understand) like the following:

S0L0CT 3rderWdate

  )3rderWtotal !-3R$T '[[[[)[[[&AA'%

  )"ayWofW2eek

  )2kdayW"ay

-R3$ $rder7ta!le INNE" S$IN &ys7CalendarCalendar 

  $N order7date ? calendar7date

  INNE" S$IN :ee+7ays

  $N ay7o,7:ee+ ? :+day7no

2=0R0 QuarterWofWear M

  N" 2eekWofW$onth K 8

H

8 Rows Returned

$rder7date $rder7total ay7o,7:ee+ :+day7ay

AAF9AF9A [8)77&B7 Thursday

AAF19F91 [)111&7D E -riday

 s demonstrated in this chapter) there are many ways to incorporate dates and date logicinto SQL& The format of the date can e ad(usted using the "T0-3R$& The SQL may use

 NS, functions or Teradata capailities and functions& Now you are ready to go ack andforth with a date !pun intended%&

Page 168: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 168/401

Chapter A: Character &tring Processing

Trans,orming Character ata

$ost of the time) it is acceptale to display data directly as it is stored in the dataase&=owe+er) there are times when it is not acceptale and the character data must etemporarily transformed& ,t might need shortening or something as simple as eliminatingundesired spaces from a +alue& The tools to make these changes are discussed here&

0arlier) we saw the CST function as a techni/ue to con+ert data& ,t can e used to truncatedata unless running in NS, mode) which does not allow truncation& These functions pro+idean alternati+e to using CST) ecause they do not truncate data& ,nstead) they allow aportion of the data to e returned& This is a slight distinction) ut enough to allow theprocessing to pro+ide some interesting capailities&

2e will e.amine the C=RCT0RS) TR,$) S5#STR,NI) S5#STR) 43S,T,3N and ,N"06functions& lone) each function pro+ides a capaility that can e useful within SQL& =owe+er)when comined) they pro+ide some powerful functionality&

This is an e.cellent time to rememer one of the primary differences etween NS, modeand Teradata mode& NS, mode is case sensiti+e and Teradata mode is not& Therefore) theoutput from most of these functions is shown here in oth modes&

C;A"ACTE"& %unction

Compatiility: Teradata 0.tension

The C=RCT0RS function is used to count the numer of characters stored in a datacolumn& ,t is easiest to use and the most helpful when the characters eing counted arestored in a +ariale length as a <RC=R column& <RC=R stores only the charactersinput and no trailing spaces after the last non*space character&

2hen referencing a fi.ed length C=R column) the C=RCT0RS function always returnsa numer that represents the ma.imum numer of characters defined& This is ecause the

Page 169: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 169/401

dataase must store the data and pad to the full length using literal spaces& space is a+alid character and therefore) the C=RCT0RS function counts e+ery space&

The synta. of the C=RCT0RS function:

C;A"ACTE"& ! Kcolumn*name %

3r C;A" ! Kcolumn*name %

To use the C=RCT0RS !can e are+iated as C=R% function) simply pass it a columnname& 2hen referenced in the S0L0CT list) it displays the numer of characters& 2henwritten into the 2=0R0 clause) it can e used as a comparison +alue to decide whether or not the row should e returned&

The 0mployee tale is used to demonstrate the functions in this chapter& The contents of thistale is listed elow:

%igure H10 

The ne.t S0L0CT demonstrates how to code using the C=R function in oth the S0L0CTlist as well as in the 2=0R0) plus the answer set:

S0L0CT -irstWname FG a <RC=R!18% column GF

  JC;A"ACTE"&(%irst7name) S CWlength

-R3$ 0mployeeWtale

2=0R0 C;A"ACTE"&(%irst7name) 3 F =

7 Rows Returned

%irst7name C7length

$andee E

Cletus E

#illy

@ohn 7

,f there are leading and imedded spaces stored within the column) the C=R functioncounts them as +alid or significant data characters&

The answer is e.actly the same using C=R in the S0L0CT list and the alias in the 2=0R0instead of repeating the C=R function:

Page 170: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 170/401

Page 171: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 171/401

The C=RCT0RWL0NIT= function is used to count the numer of characters stored in adata column& ,t is the NS, e/ui+alent of the Teradata C=RCT0RS function a+ailale in<8R7& Like C=RCT0RS) it's easiest to use and the most helpful when the characterseing counted are stored in a +ariale length <RC=R column& <RC=R stores onlythe characters input and no trailing spaces&

2hen referencing a fi.ed length C=R column) the C=RCT0RWL0NIT= function alwaysreturns a numer that represents the ma.imum numer of characters defined& This isecause the dataase must store the data and pad to the full length using literal spaces& space is a +alid character and therefore) the C=RCT0RWL0NIT= function counts e+eryspace&

The synta. of the C=RCT0RWL0NIT= function:

C;A"ACTE"7LEN8T;  ! Kcolumn*name %

To use the C=RCT0RWL0NIT= function) simply pass it a column name& 2henreferenced in the S0L0CT list) it displays the numer of characters& 2hen written into the2=0R0 clause) it can e used as a comparison +alue to decide whether or not the rowshould e returned&

The contents of the same 0mployee tale ao+e is also used to demonstrate theC=RCT0RWL0NIT= function&

The ne.t S0L0CT demonstrates how to code using the C=RCT0RWL0NIT= function inoth the S0L0CT list as well as in the 2=0R0) plus the answer set:

S0L0CT -irstWname FG a <RC=R!18% column GF

  JC;A"ACTE"7LEN8T;(%irst7name) A& C7length

-R3$ 0mployeeWtale

:;E"E C;A"ACTE"7LEN8T;(%irst7name) 3 F =

7 Rows Returned

%irst7name C7length

$andee E

Cletus E

#illy

@ohn 7

,f there are leading and imedded spaces stored within the column) theC=RCT0RWL0NIT= function counts them as +alid or significant data characters&

 s mentioned earlier) the C=RCT0RWL0NIT= function works est on <RC=R data&

The following demonstrates its result on C=R data y retrie+ing the last name and thelength of the last name where the first name contains more than D characters:

S0L0CT LastWname FG a C=R!89% column GF

  JC;A"(Last7name) A& C7length

-R3$ 0mployeeWtale

11 notice it compares ,irst name !ut displays last name

Page 172: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 172/401

:;E"E C;A"ACTE"7LEN8T;(%irst7name) 3 F

3R"0R # 1 H

7 Rows Returned

Last7name C7length

Chamers 89

Coffing 89

Smith 89

Strickling 89

 gain) the space characters are present in the data and therefore counted& =ence) all thelast names are 89 characters long& The comparison is on the first name ut the display isased entirely on the last name&

The C=RCT0RWL0NIT= function is helpful for determining demographic informationregarding the <RC=R data stored within the Teradata dataase& =owe+er) sometimes this

same information is needed on fi.ed length C=R data& 2hen this is the case) the TR,$function is helpful&

$CTET7LEN8T; %unction

Compatiility: NS,

The 3CT0TWL0NIT= function is used to count the numer of characters stored in a datacolumn& ,t is another NS, e/ui+alent of the Teradata C=RCT0RS function a+ailale in<8R7& Like C=RCT0RS) it's easiest to use and the most helpful when the characterseing counted are stored in a +ariale length <RC=R column& <RC=R stores only

the characters input and no trailing spaces&

2hen referencing a fi.ed length C=R column) the 3CT0TWL0NIT= function alwaysreturns a numer that represents the ma.imum numer of characters defined& This isecause the dataase must store the data and pad to the full length using literal spaces& space is a +alid character and therefore) the 3CT0TWL0NIT= function counts e+ery space&

The synta. of the 3CT0TWL0NIT= function:

$CTET7LEN8T; ! Kcolumn*name %

To use the 3CT0TWL0NIT= function) simply pass it a column name& 2hen referenced inthe S0L0CT list) it displays the numer of characters& 2hen written into the 2=0R0 clause)it can e used as a comparison +alue to decide whether or not the row should e returned&

The contents of the same 0mployee tale ao+e is also used to demonstrate the3CT0TWL0NIT= function&

The ne.t S0L0CT demonstrates how to code using the 3CT0TWL0NIT= function in oththe S0L0CT list as well as in the 2=0R0) plus the answer set:

S0L0CT -irstWname FG a <RC=R!18% column GF

  J$CTET7LEN8T;(%irst7name) A& C7length

-R3$ 0mployeeWtale

Page 173: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 173/401

:;E"E $CTET7LEN8T;(%irst7name) 3 F =

7 Rows Returned

%irst7name C7length

$andee E

Cletus E

#illy

@ohn 7

,f there are leading and imedded spaces stored within the column) the 3CT0TWL0NIT=function counts them as +alid or significant data characters&

 s mentioned earlier) the 3CT0TWL0NIT= function works est on <RC=R data& Thefollowing demonstrates its result on C=R data y retrie+ing the last name and the length of the last name where the first name contains more than D characters:

S0L0CT LastWname FG a C=R!89% column GF

  JC;A"(Last7name) A& C7length

-R3$ 0mployeeWtale

11 notice it compares ,irst name !ut displays last name

:;E"E $CTET7LEN8T;(%irst7name) 3 F

3R"0R # 1 H

7 Rows Returned

Last7name C7length

Chamers 89

Coffing 89

Smith 89

Strickling 89

 gain) the space characters are present in the data and therefore counted& =ence) all thelast names are 89 characters long& The comparison is on the first name ut the display isased entirely on the last name&

The 3CT0TWL0NIT= function is helpful for determining demographic information regardingthe <RC=R data stored within the Teradata dataase& =owe+er) sometimes this sameinformation is needed on fi.ed length C=R data& 2hen this is the case) the TR,$ functionis helpful&

T"IM

Compatiility: NS,

The TR,$ function is used to eliminate space characters from fi.ed length data +alues& ,t hasthe aility to get rid of trailing spaces) those after the last non*space character as well asleading spaces) those efore the first data character&

Page 174: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 174/401

Page 175: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 175/401

  JT"IM(column0 ) )  S #othWIone

  )C=R! T"IM(column0 )% !T,TL0 'Ct8'%

  JT"IM(T"AILIN8 %"$M column0 )  S NoWTrail

  )C=R! T"IM(T"AILIN8 %"$M column0 ) % !T,TL0 'Ct'%

-R3$ -i.edWLengthWtale H

7 Rows Returned

Column0 Ct0 Both78one Ct9 No7Trail Ct@

 #C "0 19 #C "0 E #C "0 E

- I = 19 - I = - I = E

, @ J L 19 , @ JL , @ J L E

$N34 19 $N34 7 $N34 E

,n this e.ample) the TR,$ function is used to eliminate the trailing spaces) following the lastnon*space character& #y default) the TR,$ function eliminates the trailing and the leadingspaces& ,n none of the +alues did it eliminate the imedded spaces&

These two aree/ui+alentcoding:

TR,$!column1%

  TR,$!#3T=-R3$column1%

The TR,$ function is helpful anytime the normal storage of spaces in a fi.ed length columnneeds to e eliminated for the output or e+aluation&

&'B&T"IN8

Compatiility: NS,

The S5#STR,NI function is used to retrie+e a portion of the data stored in a column&0arlier) we saw the CST function and that a column's data could e con+erted and thatcon+ersion might include truncation) allowed in Teradata mode&

There are potential prolems associated with the CST function& -irst) NS, mode does notallow truncation and second) it only allows for the return of one or more characters at theeginning of the string) not the last or center characters& 2hen characters other than the first

ones are needed) or the session is in NS, mode) the S5#STR,NI is the correct SQLfunction to use& Like other functions) when using S5#STR,NI) the name of the column ispassed to the function along with the starting character location for the retrie+al and lastly)the numer of characters to retrie+e !length%&

The synta. of the S5#STR,NI follows:

&'B&T"IN8!Kcolumn*name %"$M Kstart*location O %$" 3length4  %

Notice that the -3R is optional& 2hen it is omitted) the length defaults to the end of the data)including the last character&

Page 176: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 176/401

Page 177: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 177/401

-R3$ -i.edWLengthWtale H

7 Row Returned

Last7to

"0

  =

  L

34

,t is important in this re/uest to TR,$ TR,L,NI instead of #3T=& 3therwise) the wronglength is used when there are L0",NI spaces& n alternati+e is to TR,$ column1 in oththe S5#STR,NI and the -R3$&

&'B&T"

Compatiility: Teradata 0.tension

The S5#STR function is the original Teradata sustring operation& ,t was written to ecompatile with "#F8& Like the newer NS, S5#STR,NI function) it can e used in theS0L0CT list to return any portion of the character data stored in a column to a client or in the2=0R0 clause&

2hen using the S5#STR function) like S5#STR,NI) the name of the column needs to epro+ided along with the starting character location and the length or numer of characters toreturn& The main difference is that commas are used as delimiters etween these threeparameters instead of -R3$ and -3R&

The synta. of the S5#STR follows:

&'B&T" ! Kcolumn*name) Kstart*location ) Klength O %

The following produces e.actly the same output as the S5#STR,NI using the originalS5#STR Teradata synta.:

S0L0CT &'B&T"(KPartnersKJ 9 J @) S -8-

  J &'B&T"(KPartnersK J 9) S -8LL

  J &'B&T"(KPartnersK J 10 J ) S #efore-E

  J &'B&T"(KPartnersK J J @) S Too-ar )

  &'B&T"(KPartnersK J J 6).s S -ENoneH

1 Row Returned%9%@ %9ALL Be,ore% Too%ar %None

art artners 4art ers  

Like the S5#STR,NI function) the length is optional& 2hen it is not included) all remainingcharacters to the end of the column are returned& ,n the earlier releases of Teradata) theS5#STR was much more restricti+e in the +alues allowed& This situation increased thechances of the SQL statement failing due to une.pected data or +alues&

Page 178: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 178/401

Page 179: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 179/401

&hortened $2 N7$2

  18B   −18B

 s seen in these e.amples) it is a good idea to use CST to e.plicitly con+ert the numeric

data to character data first& Then) the S5#STR,NI or S5#STR operations perform ase.pected&

P$&ITI$N

Compatiility: NS,

The 43S,T,3N function is used to return a numer that represents the starting location of aspecified character string with character data& To use the 43S,T,3N function) you mustspecify two pieces of information& -irst) pass it the name of the column containing the data toe.amine and second) the character string that it should look for within the data&

The function returns a single numeric +alue that points to the location of the first occurrence

of the character string in the data& ,f the character string is not found) the function returns aero to indicate that the string does not e.ist& This is important to rememer: a ero meansthe character string was not found?

Since 43S,T,3N returns a single +alue) it does not indicate all locations or the numer of times the search string might occur in the data& ,t only shows the first& $ultiple 43S,T,3Nfunctions and one or more S5#STR,NI functions are re/uired to do this type of search& ne.ample of this is shown at the end of this chapter&

The synta. of the 43S,T,3N follows:

P$&ITI$N ! Kcharacter*string IN Kcolumn*name %

,t is possile to use the 43S,T,3N function in the 2=0R0 clause as well as in the S0L0CT

list& This pro+ides the aility to return data ased on the presence or asence of a character string within the data&

The following is an e.ample of using the 43S,T,3N function in a S0L0CTH it uses a columncalled lphaet that contains all 8E letters) through Z:

S0L0CT P$&ITI$N(KAK IN alpha!et) S -indW

FG alphaet is a 8E*yte character column that contains *Z GF

  )P$&ITI$N(KMK IN alpha!et) S -indW$

  )P$&ITI$N(KmK IN alpha!et) S -indWm

FG returns the location of the 6 when the string has all ) 6Z GF

  )P$&ITI$N(KQYK IN alpha!et) S -indW6Z

-R3$ lphaWTale

2=0R0 P$&ITI$N(KABCK IN alpha!et) 4 6 H

1 Row Returned !in Teradata $ode%

%ind7A %ind7M %ind7m %ind7QY

1 1 1 87

Page 180: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 180/401

1 Row Returned !in Teradata $ode%

%ind7A %ind7M %ind7m %ind7QY

1 1 9 87

Notice that the -indWm in Teradata mode returns the +alue of 1& et) in NS, mode) itreturns 9 ecause it was not found& Rememer) NS, is case specific and it considers ]m^and ]$^ different characters&

ou may notice that using the 43S,T,3N function in the 2=0R0 clause works the same asthe L,J0 comparison that we used earlier in this ook& The good news is that it works as fastas the L,J0 and there is no need to use the wildcard characters& t the same time) it doesnot ha+e the aility to use wildcard characters to force the search to look in a certain locationor for multiple non*consecuti+e characters) as does the L,J0&The case sensiti+ity issue is applied in the 2=0R0 clause (ust as in the S0L0CT list&Therefore) it is est to always code it as if NS, is the default mode) or else force case yusing either the 5440R or L320R con+ersions !see "ata Con+ersion Chapter %&

INEQ

Compatiility: Teradata 0.tension

The ,N"06 function is used to return a numer that represents the starting position of aspecified character string with character data& To use the ,N"06 function) specify the nameof the column containing the data to e.amine and the character string to find& ,t returns anumeric +alue that is the first occurrence of the character string& ,f the character string is notfound) a ero is returned to indicate that the string does not e.ist&

The ,N"06 function is the original Teradata function to search for a character string withindata& =owe+er) 43S,T,3N is the NS, standard&

The synta. of the ,N"06 follows:

INEQ ! Kcolumn*name) Kcharacter*string %

,t is common to use the ,N"06 function in the 2=0R0 clause as well as in the S0L0CT list&This pro+ides the aility to return data ased on the presence or asence of a character string within the data&

0.ample of using the ,N"06 function:

FG alphaet is a 8E*yte character column that contains *Z GF

S0L0CT INEQ(alpha!etJ KAK) S -indW

  JINEQ(alpha!etJ KMK) S -indW$

  JINEQ(alpha!etJ KmK) S -indWm

  JINEQ(alpha!etJ KQYK) S -indW6Z

FG returns the location of the 6 when the string has all ) 6Z GF

-R3$ lphaWTale

2=0R0 INEQ(alpha!etJ KCK) 4 6 =

1 Row Returned !in Teradata $ode%

Page 181: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 181/401

Page 182: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 182/401

Concatenation is the process of taking two or more columns and comining them into asingle column& This is also a character operation& $ath is used to comine numers) notconcatenation& =owe+er) if numer columns are concatenated) they must first e con+ertedto a character string&

The is used in SQL to concatenate columns& The following uses literals to demonstrate itsuse:

S0L0CT KABCK KQYK S 3neWcolumn H

1 Row Returned

$ne7column

 #C6Z

Since they are comined into a single column) they need only one alias name&

The "epartment tale is used with the 0mployee tale to show more capailities of concatenation&

%igure H1@ 

The ne.t S0L0CT uses the 0mployee tale to incorporate the concatenation:

S0L0CT %irst7name K K Last7name as ;Name;

  )"epartmentWname S "epartment

-R3$ 0mployeeWtale S 0 ,NN0R @3,N "epartmentWtale S "

  3N 0&deptWno M "&deptWno

2=0R0 43S,T,3N!; ,N "epartmentWname% 9

FG "epartment Name defined as a <RC=R column otherwise TR,$

  must e used to eliminate TR,L,NI spaces GF

3R"0R # 8)1 H

Rows Returned

Name epartment

Cletus

Strickling

Customer 

Support=erert=arrison

Customer Support

2illiamReilly

Customer Support

#illyCoffing

Researchand"e+elopment

Page 183: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 183/401

Name epartment

@ohnSmith

Researchand"e+elopment

0ach of the rows ao+e is selected ecause the name of the department has more than oneword in it) ased on a space in the department name found y the 2=0R0 clause& The43S,T,3N function found them& Then) the ,NN0R @3,N matched the department to theemployees working there&

Now) let's say that it has een determined that the entire name is too long& To make mattersworse) the name should e sorted y the last name) not the first& So the S0L0CT has eencon+erted elow to incorporate these changes:

S0L0CT -irstWname ' ' LastWname as ;Name;

  J&'B&T"IN8(epartment7name %"$M 0 %$"

  P$&ITI$N(V IN epartment7name) 10 )

  S "epartmentFG "epartment Name defined as a <RC=R column otherwise TR,$

  must e used to eliminate TR,L,NI spaces GF

-R3$ 0mployeeWtale S 0 ,NN0R @3,N "epartmentWtale S "

  3N 0&deptWno M "&deptWno

2=0R0 43S,T,3N!; ,N "epartmentWname% 9

3R"0R # 8) LastWname

H

Rows Returned

Name epartment

=erert=arrison

Customer 

2illiamReilly

Customer 

CletusStrickling

Customer 

#illyCoffing

Research

@ohnSmith

Research

,t has een determined the answer set is etter& The 43S,T,3N function found the space inthe name of the department and sutracted 1 from it& This pro+ides the length of the firstword and is used in the -3R portion of the S5#STR,NI& Thus) only the first word of thedepartment name is returned&

 t the same time) it is not e.actly what is needed& The last name should come efore thefirst name and e separated y a comma:

Page 184: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 184/401

Page 185: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 185/401

Rows Returned

epartment7name &econd7epartment7:ord

Research and"e+elopment

and "e+elopment

=uman Resources Resources

Customer Support Support

Returning the second word with S5#STR,NI is really nothing more than using the43S,T,3N function in the -R3$ instead of the -3R& =owe+er) what if only the third word isneeded

The ne.t S0L0CT shows how to return the third word:

S0L0CT "epartmentWname

  J&'B&T"IN8(epartment7name %"$M

  P$&ITI$N(V IN epartment7name) U 9 U

  P$&ITI$N(V IN &'B&T"IN8(epartment7name  %"$M P$&ITI$N(V IN epartment7name ))) U 9 )

  S ThirdW"epartmentW2ord

-R3$ "epartmentWtale

  2=0R0 43S,T,3N!; ,N

  T"IM(&'B&T"IN8(epartment7name %"$M

  P$&ITI$N(V IN epartment7name) U0 ))) 46=

1 Row Returned

epartment7name Third7epartment7:ord

Research and"e+elopment

"e+elopment

,n order to accomplish this processing) e+erything from the second word to the end must epresented to the 43S,T,3N function in the 2=0R0 clause to +erify a third word& 3nce a rowwith a third word is found) the S5#STR,NI in the S0L0CT uses the 43S,T,3N of the firstspace and the 43S,T,3N of the second space as a starting point and returns all charactersto the end&

Chapter 19: $LAP %unctions

$n1Line Analytical Processing ($LAP) %unctions

Page 186: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 186/401

Page 187: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 187/401

%igure 061@ 

$LAP %unctions

The 3L4 functions are uilt into the Teradata dataase to pro+ide data mining capailitiesand trend analysis& These functions pro+ide processing not a+ailale using the standardaggregation& s mentioned earlier) an aggregate eliminates the detail data from a row& These3L4 functions pro+ide the result of their operation and display the detail data +alues usedin the function&

This techni/ue produces output that is somewhat like the Teradata e.tensions of 2,T= and2,T= #& The similarity is in the fact that the detail row data is also displayed as part of theanswer set& =owe+er) since the output is in row format and not in a report format like 2,T=)

the 3L4 functions may e performed on all tales or +iews and may e used to populatetales in con(unction with ,NS0RTFS0L0CT& The iggest difference is that these can e usedin Queryman) unlike 2,T=&

Cumulati<e &um 'sing the C&'M %unction

Compatiility: Teradata 0.tension

Page 188: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 188/401

Page 189: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 189/401

Product7I &ale7ate aily7&ales C&um

8999 8999*9A*8A

7B999&99 1BDA&8B

1999 8999*9A*

8A

799&88 1A8A&9

1999 8999*9A*9

E999&9D 88A8A&D

8999 8999*9A*9

7AB9&9 8DA9BA&E9

1999 8999*19*91

79899&7 1A8A9&9

8999 8999*19*91

7B9&8A D7179&8

1999 8999*19*

98

8B99&9 79EA79&B8

8999 8999*19*98

E981&A 778AE8&D

1999 8999*19*9

E799&99 9D8E8&D

8999 8999*19*9

7899&1B 97E8&A

1999 8999*19*97

7&19 E991E&9

8999 8999*19*97

8B99&9 @FG0D@

-rom the ao+e output) it is easy to see that the report is in se/uence y the Sale datecolumn& Since 3L4 functions are capale of sorting on more than a single column) it mighte ad+isale to se/uence y the product ," too& dding an 3R"0R # is most e+eryone'sfirst thought to pro+ide a sort for the product ,"& lthough it is syntactically correct) it is notthe correct approach&

ou can also see the true purpose of the CS5$ command& The first data row contains71)BBB&BB and is added to 9 y CS5$ to otain 71)BBB&BB& The second row returned a dailysale of 7B)B9&79 that is added to 71)BBB&BB for a CS5$ of A9)DA&8B& This continuesadding each consecuti+e +alue until the last row is processed with a final total of ED)B1E&&The following demonstrates the INC$""ECT  way to add the product ," y using an3R"0R #:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )CS5$!"ailyWSales) SaleW"ate% S ;CSum;

-R3$ SalesWtale

2=0R0 4roductW," #0T200N 1999 and 8999

$"E" BY Product7I #5 ne<er do this 5#

Page 190: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 190/401

Page 191: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 191/401

Page 192: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 192/401

Page 193: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 193/401

Page 194: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 194/401

Page 195: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 195/401

a new row in another tale& See chapters 1 and 1B for creating tales and the use of the,NS0RTFS0L0CT&

Mo<ing &um 'sing the M&'M %unction

Compatiility: Teradata 0.tension

  mo+ing sum incorporates the same addition as seen in the CS5$ function& =owe+er) theaspect of mo+ing in+ol+es estalishing a window ased on a numer of rows to e used inthe addition&

The $o+ing Sum !$S5$% function pro+ides the mo+ing sum or total on a column's +alue)ased on a defined numer of rows& The numer of rows is referred to as the /uery width&Like the CS5$) the $S5$ defaults to sorting the results in ascending order&

The synta. for $S5$ is:

S0L0CT M&'M( 3column1name4J 3idth4J 3sort1+ey4 OA&C E&C

  OJ 3sort1+ey4 OA&C E&C )-R3$ Ktale*name

IR354 # Kcolumn*name )Kcolumn*numerO O

H

The $S5$ uses the first parameter as the column containing a numeric +alue to sum&

The second parameter of the $S5$ is the width numer& ,t represents the numer of rowsincluded in the summation& <alid +alues are from 1 to 79AE& ,f the numer of rows is lessthan the width defined then the calculation will e ased on the rows present and it will actlike the CS5$& lthough a +alue of 1 is allowed) it makes no sense to sum e+ery row&

The third parameter is entered as one or more sort keys that se/uence the spooled rows&The sort will determine the se/uence of the detail row data for the $S5$ operation& #ydefault) the sort se/uence is ascending !SC%& The "0SC can e specified to re/uest adescending !highest to lowest% se/uence& 3ptionally) additional sort keys can e entered tore/uest one or more minor sort se/uences& gain) this sort is performed inside the $S5$and not y the 3R"0R # statement at the end of the /uery&

The ne.t S0L0CT shows a *row !day% mo+ing sum for all products from the Sales taleusing $S5$&

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )M&'M(aily7&alesJ @J &ale7ate) S $o+Sum-R3$ SalesWtale

2=0R0 06TRCT!$3NT= -R3$ SaleW"ate% M A H

A Rows Returned

Product7I &ale7ate aily7&ales Mo<&um

999 8999*9A* E191&DD E191&DD

Page 196: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 196/401

Page 197: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 197/401

Product7I &ale7ate aily7&ales 7 M&um

8A

1999 8999*9A*9

E999&9D 1A9&EA

1999 8999*19*91

79899&7 1DA1&18

1999 8999*19*98

8B99&9 909@D09

1999 8999*19*9

E799&99 99FG6099

1999 8999*19*97

7&19 88DB7&19

8999 8999*9A*8B

71BBB&BB 8D78&A1

8999 8999*9A*8A

7B999&99 87178&7B

8999 8999*9A*9

7AB9&9 8BA8&91

8999 8999*19*91

7B9&8A 87A178&9

8999 8999*19*98

E981&A 89E11&1

8999 8999*19*9

7899&1B 81A88&7

8999 8999*19*97 8B99&9

90F99H@

Now) rows go into the accumulation and the +alue fluctuates for product 1999 on 3ctoer as the si.th row come into the operation and the first row drops out& This continues for eachfi+e rows until arri+ing at the 81E)D88&A for the last fi+e rows for product 8999& This allowsus to see trends during certain time frames of our choosing& 2hen we see a ig or smallnumer (ump out at us in the accumulation we can in+estigate why& "id we run an adcampaign or ha+e a sale 2as it a holiday

Mo<ing &um ith "eset Capa!ilities

The mo+ing sum operation can also e written to pro+ide the e/ui+alence of a sutotal&

2hen the IR354 # designation is added to the /uery it indicates which column or columns to monitor for a change to occur& ,t also indicates the order of the sort to perform&2hen the data +alue in the column changes) the IR354 # causes the accumulation +alueto e reset ack to ero& =ence a sutotal is pro+ided within a mo+ing window&

'sing M&'M and 8"$'P BY

  mo+ing sum may e reset to ero at a specified reakpoint& Like the CS5$) this isaccomplished y merely adding a IR354 # clause to the /uery using the $S5$&

Page 198: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 198/401

 lthough) it is important to rememer that this is an additional reset ecause the reset alsooccurs when the width has een e.ceeded y new rows eing read and used in the mo+ingwindow&

The ne.t S0L0CT produces a report like the ao+e using the $S5$) howe+er) it is sortingand reaking on the 4roduct ," instead of the sale date and limits the scope of the productsto1999 and 8999:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales !-ormat '[[[)[[[&AA'%

  )$S5$!"ailyWSales) ) 4roductW,") SaleW"ate% !-ormat '[[[[)[[[&AA'%

  S SalesW#yW4roduct

-R3$ SalesWtale

2=0R0 4roductW," ,N !1999) 8999%

8"$'P BY Product7I H

17 Rows Returned

Product7I &ale7ate aily7&ales &ales ByProduct

1999 8999*9A*8B

[7B)B9&79 [7B)B9&79

1999 8999*9A*8A

[7)99&88 [19)9&E8

1999 8999*9A*9

[E)999&9D \0@HJ@D6H

1999 8999*19*

91

[79)899&7 \0@6JF66F9

1999 8999*19*98

[8)B99&9 [19A)991&99

1999 8999*19*9

[E7)99&99 [1D)99&A

1999 8999*19*97

[7)&19 \0D0JD@6

8999 8999*9A*8B

\0JGGGGG  \0JGGGGG 

8999 8999*9A*8A

[7B)999&99 [BA)BBB&BB

8999 8999*9A*9

[7A)B9&9 \0@HJF@GH0

8999 8999*19*91

[7)B9&8A \0D9JF66@9

8999 8999*19*98

[E)981&A [179)D88&8

8999 8999*19* [7)899&1B [17)9D8&79

Page 199: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 199/401

Product7I &ale7ate aily7&ales &ales ByProduct

9

8999 8999*19*

97

[8)B99&9 \009J6990

Now the report demonstrates a *day mo+ing a+erage y product instead of for all products&This is a more meaningful report& The sales +olume continues to mo+e with the ne.t threedays !rows%) ut the reset occurs when the first occurrence of product 8999 is encountered&

 t that time) the counter returns to ero and increases for rows as determined y Kwidthand then fluctuates ased on the new +alue from the ne.t row and the remo+al of the +aluefrom the row that was read Kwidth rows ago& ,n simple terms you can almost pick any rowand e.amine the $S5$ column& ou will notice that the calculation was made using thecurrent row plus the two pre+ious rows only& This is the purpose of the width&

Now we can look for trends to see where the data seems to (ump high or low and then we

can utilie our SQL to proe deeper to find why& 3nce we see that in one *day period wesold doule the amount we usually do we might find that we had ran an ad+ertisingcampaign that day or pro+ided coupons&

The ne.t S0L0CT produces a report like the ao+e using the $S5$) howe+er) it is sortingand reaking on oth the 4roduct ," and on the sale date and limits the scope of theprocessing to products 1999 and 8999:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales !-ormat '[[[)[[[&AA'%

  )$S5$!"ailyWSales) ) 4roductW,") SaleW"ate% !-ormat '[[[[)[[[&AA'%

  S SalesW#yW4roduct

-R3$ SalesWtale

2=0R0 4roductW," ,N !1999) 8999%

IR354 # 4roductW," H

17 Rows Returned

Product7I &ale7ate aily7&ales &ales ByProduct

1999 8999*9A*8B

[7B)B9&79 [7B)B9&79

1999 8999*9A*8A

[7)99&88 [19)9&E8

1999 8999*9A*9

[E)999&9D [1A)9&EA

1999 8999*19*91

[79)899&7 [19)D99&D8

1999 8999*19*98

[8)B99&9 [19A)991&99

Page 200: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 200/401

Product7I &ale7ate aily7&ales &ales ByProduct

1999 8999*19*9

[E7)99&99 [1D)99&A

1999 8999*19*97

[7)&19 [11)E&E9

8999 8999*9A*8B

[71)BBB&BB [71)BBB&BB

8999 8999*9A*8A

[7B)999&99 [BA)BBB&BB

8999 8999*9A*9

[7A)B9&9 [1A)DB&A1

8999 8999*19*91

[7)B9&8A [18)D99&8

8999 8999*19*98 [E)981&A [179)D88&8

8999 8999*19*9

[7)899&1B [17)9D8&79

8999 8999*19*97

[8)B99&9 [118)988&E1

Mo<ing A<erage 'sing the MA8 %unction

Compatiility: Teradata 0.tension

  mo+ing a+erage incorporates the same window of rows and addition as seen in the$S5$& =owe+er) the aspect of the a+erage incorporates a count of all the +alues in+ol+edand then di+ides the sum y the count to otain the a+erage&

The $o+ing +erage !$<I% function pro+ides a mo+ing a+erage on a column's +alue)ased on a defined numer of rows also known as the /uery width& Like the $S5$) the$<I defaults to ascending order for the sort& So) once you learn the $S5$) the $<I iseasier to learn ecause of the similarities&

,f the numer of rows is less than the width defined then the calculation will e ased on therows present&

The synta. for $<I is:

S0L0CT MA8( 3column1name4J 3idth4J 3sort1+ey4 OA&C E&C)  OJ 3sort1+ey4 OA&C E&C )

-R3$ Ktale*name

IR354 # Kcolumn*name )Kcolumn*numer O O

H

The $<I command uses the first parameter as the column containing a numeric +alue toa+erage&

Page 201: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 201/401

The second parameter used y the $<I is the width numer& ,t represents the numer of rows included in the summation& <alid +alues are from 1 to 79AE& ,f the numer of rows isless than the width defined then the calculation will e ased on the rows present& lthough1 is an acceptale +alue) it does not make sense to use it& This would mean that e+erya+erage was the +alue for that one row&

The third parameter is entered as a ma(or sort key that se/uences the output rows& Thiscolumn will e sorted to determine the se/uence of the detail row data along with the $<I&#y default) the sort se/uence is ascending !SC%& The "0SC can e specified to re/uest adescending !highest to lowest% se/uence& 3ptionally) additional sort keys can e entered tore/uest one or more minor sort se/uences&

The following S0L0CT shows a *row !day% mo+ing a+erage for product 1999 from the Salestale using $<I:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )MA8(aily7&alesJ DJ &ale7ate) A& VMA<gV

-R3$ SalesWtale

2=0R0 4roductW," M 1999H

D Rows Returned

Product7I &ale7ate aily7&ales 7 MA<g

1999 8999*9A*8B

7BB9&79 7BB9&79

1999 8999*9A*8A

799&88 1ED&1

1999 8999*9A*9

E999&9D 7E79&8

1999 8999*19*91

79899&7 77BBD&DB

1999 8999*19*98

8B99&9 9F6@9

1999 8999*19*9

E799&99 7E9&87

1999 8999*19*97

7&19 DDF6G9

The ao+e output a+erages rows ! days% all the way through the end of the returned rows& s the si.th row comes into the a+erage operation) the first row drops out& This continuesthrough the end of the rows&

To make the se/uence more refined) the ne.t S0L0CT uses an additional sort column asedon the product numer:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

Page 202: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 202/401

Page 203: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 203/401

D Rows Returned

Product7I &ale7ate aily7&ales D1ayMo<ingA<g

1999 8999*9A*8B [7B)B9&79 [7B)B9&79

1999 8999*9A*8A

[7)99&88 [1)ED&1

1999 8999*9A*9

[E)999&9D [7E)79&8

8999 8999*9A*8B

[71)BBB&BB [7)9A&BA

8999 8999*9A*8A

[7B)999&99 \DJGFH0

8999 966616H1

@6 

\HJGD66@  \J6FG

1999 8999*19*91

\6J966@  \6J966@

1999 8999*19*98

[8)B99&9 [E)99&7E

1999 8999*19*9

[E7)99&99 [7)DEE&AB

1999 8999*19*97

[7)&19 [7D)AE&1

8999 8999*19*91

[7)B9&8A \HJ@6G

8999 8999*19*98

[E)981&A [7B)9&1E

8999 8999*19*9

[7)899&1B [9)B&19

8999 8999*19*97

[8)B99&9 \J9GD96

,n the ao+e output) the iggest change occurs on 3ctoer 1) for product 1999& There) thea+erage is the same as the sales for that day when the reset occurred as a result of finishingall rows for Septemer&

Mo<ing i,,erence 'sing the MI%% %unction

Compatiility: Teradata 0.tension

The $o+ing "ifference !$",--% function pro+ides a mo+ing difference on a column's +alue)ased on a defined numer of rows known as the /uery width& Since the $",-- functiondoes sutraction) it works differently than all the other 3L4 functions& This difference is

Page 204: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 204/401

ased on the fact that addition allows more than two numers to e added at a time& 2hereas) sutraction operations can only e performed on two numers at a time&

The synta. for $",-- is:

S0L0CT MI%%(3column1name4J 3idth4J 3sort1+ey4 OA&C E&C )

  OJ 3sort1+ey4 OA&C E&C )

-R3$ Ktale*name

IR354 # Kcolumn*name )Kcolumn*numerO O

H

The $",-- command uses the first parameter as the column containing a numeric +alue tosutract&

The second parameter used y the $",-- is the width numer& The width determines howmany rows ack to count for the sutrahend& <alid +alues are from 1 to 79AE& ,f width isgreater than the numer of rows in the tale) all preceding rows will display a N5LL for $",--& Therefore) the first rows displayed less than the width will always e represented ya N5LL& nother distinction of the $",-- is that a width of 1 might e a good +alue&

The third parameter is entered as a sort key that se/uences the output rows& This columnwill e sorted to determine the se/uence of the detail row data along with the $",--& #ydefault) the sort se/uence is ascending !SC%& The "0SC can e specified to re/uest adescending !highest to lowest% se/uence& 3ptionally) additional sort keys can e entered tore/uest one or more minor sort se/uences&

The following S0L0CT shows a 8*day mo+ing difference for product 1999:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )MI%%(aily7&alesJ 9J &ale7ate) A& VMi,,V

-R3$ SalesWtale

2=0R0 4roductW," M 1999 H

D Rows Returned

Product7I &ale7ate aily7&ales 7 Mi,,  

1999 8999*9A*8B

7BB9&79

1999 8999*9A*8A

799&88

1999 8999*9A*9

E999&9D   −18B9&

1999 8999*19*91

79899&7   −178AA&DA

1999 8999*19*98

8B99&9   −1AA&D

1999 8999*19* E799&99 879AA&D

Page 205: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 205/401

Product7I &ale7ate aily7&ales 7 Mi,,  

9

1999 8999*19*97

7&19 81D8&E9

,n the ao+e output) the $",-- represents the difference etween the sales on any twodays& Notice the $",-- for the last row ha+ing "ailyWSales of 7&19& The $",-- had awidth of two so the last rows "ailyWSales is calculated with the row two rows up& Thus)7)&19 sutracting 8B99&9 gi+es a difference of 81D8)E9& Now) comes a different/uestion& 2hy are there nulls in the first two rows

Since the $",-- needs to use a column +alue Kwidth rows ago) the first Kwidth rows willcontain a N5LL& This is due to the fact that until one more row eyond Kwidth has eenread) there is no +alue for the sutrahend& Therefore) a missing +alue is N5LL and the firstKwidth row will always e N5LL ecause the result) of any math operation using a N5LL) isa N5LL&

The ne.t S0L0CT is performing a D*day mo+ing difference for a weekly comparison etweenthe products 1999 and 8999 ased on all sales stored in the tale:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )$",--!"ailyWSales) D) 4roductW,") SaleW"ate% S ;$"iff;

-R3$ SalesWtale

2=0R0 4roductW," ,N !1999) 8999%H

17 Rows Returned

Product7I &ale7ate aily7&ales Mi,,  

1999 8999*9A*8B

7BB9&79

1999 8999*9A*8A

799&88

1999 8999*9A*9

E999&9D

1999 8999*19*91

79899&7

1999 8999*19*98

8B99&9

1999 8999*19*9

E799&99

1999 8999*19*97

7&19

8999 8999*9A*8B

71BBB&BB   −EAE1&8

Page 206: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 206/401

Page 207: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 207/401

  )SaleW"ate

  )"ailyWSales

  )$",--!"ailyWSales) 8) 4roductW,"% S ;$"iff;

-R3$ SalesWtale

2=0R0 SaleW"ate etween 1991991 and '8999*19*97'

IR354 # 4roductW,"

H

18 Rows Returned

Product7I &ale7ate aily7&ales Mi,,  

1999 8999*19*98

8B99&9

1999 8999*19*91

79899&7

1999 8999*19*9

E799&99 17AA&9

1999 8999*19*97

7&19 178&ED

8999 8999*19*9

7899&1B

8999 8999*19*97

8B99&9

8999 8999*19*98

E981&A   −D1DB&8

8999 8999*19*91 7B9&8A 8897A&DA

999 8999*19*9

81&DA

999 8999*19*97

1ED&

999 8999*19*98

1AEDB&A7   −1BD7&B

999 8999*19*91

8B999&99 1887&ED

=owe+er) as shown in the following S0L0CT) care should e taken in attempts to show a 7*day mo+ing difference for all products with only 7 days of data:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )$",--!"ailyWSales) 7) 4roductW,"% S ;$"iff;

-R3$ SalesWtale

2=0R0 SaleW"ate etween 1991991 and '8999*19*97'

Page 208: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 208/401

IR354 # 4roductW,"H

18 Rows Returned

Product7I &ale7ate aily7&ales 7  Mi,, 

1999 8999*19*98

8B99&9

1999 8999*19*91

79899&7

1999 8999*19*9

E799&99

1999 8999*19*97

7&19

8999 8999*19*9

7899&1B

8999 8999*19*97

8B99&9

8999 8999*19*98

E981&A

8999 8999*19*91

7B9&8A

999 8999*19*9

81&DA

999 8999*19*97

1ED&

999 8999*19*98 1AEDB&A7

999 8999*19*91

8B999&99

"on't get too detailed so that nothing is seen) as in the ao+e output& Jnow what the datalooks like to pick the est representation in the output& ou cannot see 7 days worth of datedifference when the data contains only 7 rows&

 lso) notice that the ao+e SQL uses two different +ersions of a date in the 2=0R0 clause&The first is the numeric Teradata nati+e format and the second is the NS, +ersion& The firstcould ha+e een written as 1991991!date%& =owe+er) since it is longer) the only ad+antage indoing so is the ease of understanding y another person&

Cumulati<e and Mo<ing &'M 'sing &'M # $E"

Compatiility: NS,

 n accumulati+e sum can now e otained using NS, standard synta.& This process isre/uested using the S5$ and y re/uesting an 3<0R option& This option causes theaggregate to act like an 3L4 function& ,t pro+ides a running or cumulati+e total for a

Page 209: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 209/401

column's numeric +alue& This allows users to see what is happening with certain columntotals o+er an ongoing progression& The results will e sorted in ascending or descendingorder and the sort list can consist of a single or multiple columns as sort keys&

The following NS, synta. is used with S5$ to pro+ide CS5$ 3L4 functionality:

S0L0CT &'M(3column1name4) $E" ($"E" BY 3column1name4 OA&C E&C

  OJ3column1name4 OA&C E&C

  O "$:& OBET:EEN 'NB$'NE P"ECEIN8

  O AN 'NB$'NE . * %$LL$:IN8 )

-R3$ Ktale*name

H

5nlike the S5$ used as an aggregate) the ma(or difference is the 3<0R specification&2ithin the 3<0R is the 3R"0R # re/uest& ,t may specify a single column or multiplecolumns in a comma*separated list& ,t is not optional and it is part of the S5$ F 3<0R& Thedefault se/uence is ascending !SC%&

 dding a second and final 3R"0R # would e as incorrect here as it was with the CS5$&The 3R"0R # must e specified in the 3<0R& 2hereas) the CS5$ function simply usesone or more columns in the sort list&

The optional R32S 5N#35N"0" portion indicates the width or numer of rows to use& The5N#35N"0" specification allows all rows to participate in the addition&

#elow) the S0L0CT shows the cumulati+e sales using the S5$ F 3<0R:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )&'M(aily7&ales) $E" ( $"E" BY &ale7ate

  "$:& 'NB$'NE P"ECEIN8)

  S LikeWCSum

-R3$ SalesWtale

2=0R0 4roductW," #0T200N 1999 and 8999 H

17 Rows Returned

Product7I &ale7ate aily7&ales Li+e7C&um

8999 8999*9A*8B

71BBB&BB 71BBB&BB

1999 8999*9A*8B 7BB9&79 A9DA&8B

8999 8999*9A*8A

7B999&99 1BDA&8B

1999 8999*9A*8A

799&88 1A8A&9

1999 8999*9A*9

E999&9D 88A8A&D

Page 210: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 210/401

Product7I &ale7ate aily7&ales Li+e7C&um

8999 8999*9A*9

7AB9&9 8DA9BA&E9

1999 8999*19*

91

79899&7 1A8A9&9

8999 8999*19*91

7B9&8A D7179&8

1999 8999*19*98

8B99&9 79EA79&B8

8999 8999*19*98

E981&A 778AE8&D

1999 8999*19*9

E799&99 9D8E8&D

8999 8999*19*

9

7899&1B 97E8&A

1999 8999*19*97

7&19 E991E&9

8999 8999*19*97

8B99&9 EDB1E&

To make the output a it more organied) it might help to ha+e all of the sales for a particular product together& To accomplish this se/uencing) the product ," column must also e usedin the sort& The ne.t S0L0CT adds the product ," to the 3R"0R #:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales  )S5$!"ailyWSales% 3<0R ! $"E" BY Product7IJ &ale7ate

  R32S 5N#35N"0" 4R0C0",NI%

  S LikeWCSum

-R3$ SalesWtale

2=0R0 4roductW," #0T200N 1999 and 8999 H

17 Rows Returned

Product7I &ale7ate aily7&ales Li+e7C&um

1999 8999*9A*8B

7BB9&79 7BB9&79

1999 8999*9A*8A

799&88 199&E8

1999 8999*9A*9

E999&9D 1A9&EA

1999 8999*19*91

79899&7 1DA1&18

Page 211: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 211/401

Product7I &ale7ate aily7&ales Li+e7C&um

1999 8999*19*98

8B99&9 8181&E8

1999 8999*19*

9

E799&99 8DEE1&E8

1999 8999*19*97

7&19 1897&D8

8999 8999*9A*8B

71BBB&BB D9A&E9

8999 8999*9A*8A

7B999&99 7819A&E9

8999 8999*9A*9

7AB9&9 7D9A7&E

8999 8999*19*

91

7B9&8A 8DA&A8

8999 8999*19*98

E981&A E1B1&B

8999 8999*19*9

7899&1B E991E&9

8999 8999*19*97

8B99&9 EDB1E&

Like the CS5$) had a second 3R"0R # een used) the output would e wrong and looklike the S5$ had een reset& Now) with that eing said) there are times when it is eneficialto ha+e the accumulation process reset& -or instance) maye product sutotals are neededinstead of the total for all products& The ne.t section demonstrates the techni/ues !Teradataand NS,% to make this processing happen&

To make the output a mo+ing sum) the range of the rows to use must e estalished& Thene.t S0L0CT adds R32S 8 !like width of % and the product ," to the 3R"0R #:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )&'M(aily7&ales) $E" ( $"E" BY Product7IJ &ale7ate

  "$:& 9 P"ECEIN8) S LikeW$Sum

-R3$ SalesWtale

2=0R0 4roductW," #0T200N 1999 and 8999 H

17 Rows Returned

Product7I &ale7ate aily7&ales Li+e7M&um

1999 8999*9A*8B

7BB9&79 7BB9&79

1999 8999*9A*8A

799&88 199&E8

Page 212: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 212/401

Product7I &ale7ate aily7&ales Li+e7M&um

1999 8999*9A*9

E999&9D 1A9&EA

1999 8999*19*

91

79899&7 19D99&D8

1999 8999*19*98

8B99&9 19A991&99

1999 8999*19*9

E799&99 1D99&A

1999 8999*19*97

7&19 11E&E9

8999 8999*9A*8B

71BBB&BB 1E9D71&AB

8999 8999*9A*

8A

7B999&99 177771&AB

8999 8999*9A*9

7AB9&9 1ADB&A1

8999 8999*19*91

7B9&8A 18D99&8

8999 8999*19*98

E981&A 179D88&8

8999 8999*19*9

7899&1B 179D8&79

8999 8999*19*97

8B99&9 118988&E1

This output is the same as a $S5$ with a width of & =owe+er) here it is re/uired to specifythe use of the 8 preceding rows&

Cumulati<e &um ith "eset Capa!ilities

 s mentioned with the CS5$) this +ersion of the cumulati+e sum can e reset a to pro+idethe e/ui+alent of a sutotal& This method uses the NS, Standard S5$ with 3<0R and4RT,T,3N # designators to specify a data +alue that) when it changes) causes theaccumulation +alue to e reset ack to ero&

&'M 'sing &'M and $E" # PA"TITI$N BY

Normally aggregate functions and 3L4 functions are incompatile& This is ecauseaggregates pro+ide only the final single row answer and eliminate row detail data&Con+ersely) the 3L4 functions pro+ide the row detail data and the answer& 5sing this NS,synta.) the S5$ aggregate can e made to act more as an 3L4 function to pro+ide oththe answer and the row detail&

 s seen ao+e) CS5$ is a Teradata 0.tension& ,t may use the IR354 # designation toreset the accumulation process for the e/ui+alent of a sutotal& The AN&I method does not

Page 213: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 213/401

Page 214: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 214/401

Product7I &ale7ate aily7&ales Li+e7C&um

999 8999*19*9

81&DA [18A)9&AD

The 4RT,T,3N has the same effect here as the IR354 # does in the proprietaryTeradata e.tension 3L4 functions&

There are two ad+antages to using this synta.& -irst) it is the NS, standard& Second) andthe iggest ad+antage) is that it is compatile with other 3L4 functions ecause the detaildata is retained as well as the use of aggregate functions within the formulas for deri+eddata&

Now that the daily total has een seen ao+e) it might e useful to see totals y product& Toaccomplish this) the product ," needs to e part of the 3R"0R # and the 4RT,T,3N muste ased on the product ,":

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )S5$!"ailyWSales% 3<0R ! 4RT,T,3N # 4roductW,"

  $"E" BY Product7IJ &ale7ate E&C

  R32S 5N#35N"0" 4R0C0",NI%

  !format '[[[[)[[[&AA'% S LikeWCSum

-R3$ SalesWtale

2=0R0 SaleW"ate etween 1991991 and 199199 H

A Rows Returned

Product7I &ale7ate aily7&ales Li+e7C&um

1999 8999*19*9

E799&99 [E7)99&99

1999 8999*19*98

8B99&9 [AD)199&9

1999 8999*19*91

79899&7 [1D)99&A

8999 8999*19*9

7899&1B [7)899&1B

8999 8999*19*

98

E981&A [DA)888&11

8999 8999*19*91

7B9&8A [17)9D8&79

999 8999*19*9

81&DA [81)&DA

999 8999*19*98

1AEDB&A7 [71)88&D

999 8999*19* 8B999&99 [EA)88&D

Page 215: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 215/401

Product7I &ale7ate aily7&ales Li+e7C&um

91Now that the S5$ 3<0R has een shown) to this point) there has not een demonstrated acompelling reason to use it instead of the $S5$ or CS5$ e.tensions& Since this ook is

called Teradata SQL – Unleash the Power ) lets e.plore the power&

The following shows the true enefit of these new 3L4 functions for mi.ing them with theoriginal 3L4 functions:

S0L0CT 4roductWid

  )"ailyWSales

  )Rank!dailyWsales%

  )S5$!dailyWsales% 3<0R !4RT,T,3N # productWid

  R32S #0T200N 5N#35N"0" 4R0C0",NI

  N" 5N#35N"0" -3LL32,NI %

  )aily7&ales 5 066 # &'M(daily7sales) $E" (PA"TITI$N BY product7id

  "$:& BET:EEN 'NB$'NE P"ECEIN8

  AN 'NB$'NE %$LL$:IN8 )

  S Contriution

-R3$ salesWtale

Q5L,- RNJ!dailyWsales% KM 8

3R"0R # Contriution "0SCH

8 Rows Returned

Product7I aily7&ales "an+(daily7sales) 8roup&um(daily7sales)

Contri!

999 E191&DD 8 887BD&B8 8D&9

1999 E799&99

Mo<ing A<erage 'sing A8 # $E"

Compatiility: NS,

  mo+ing a+erage can now e otained using NS, synta.& This process is re/uested usingthe <I y using the 3<0R option& This option causes the aggregate to act like an 3L4function& ,t pro+ides a running a+erage for a column's numeric +alue& This allows users tosee what is happening with certain column a+erages o+er an ongoing progression& Theresults will e sorted in ascending or descending order and the sort list can consist of singleor multiple columns as sort keys&

The following NS, synta. is used with <I to pro+ide $<I 3L4 functionality:

S0L0CT A8(3column1name4) $E" ( $"E" BY 3column1list4

  O"$:& OBET:EEN 'NB$'NE . * P"ECEIN8

  O AN 'NB$'NE . * %$LL$:IN8 )

Page 216: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 216/401

Page 217: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 217/401

To see product a+erages for the same period) the S0L0CT can e modified to add theproduct ," to the sort:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales !-ormat '[[[)[[[&AA'%

  ) <I!"ailyWSales% 3<0R ! 3R"0R # productW,") saleWdate

  R32S 8 4R0C0",NI%

  !-ormat '[[[[)[[[&AA'% S LikeW$+g

-R3$ SalesWtale

2=0R0 06TRCT!$3NT= -R3$ SaleW"ate% M A H

A Rows Returned

Product7I &ale7ate aily7&ales Li+e7MA<g

1999 8999*9A*

8B

[7B)B9&79 [7B)B9&79

999 8999*9A*8B

[E1)91&DD [1)ED&1

8999 8999*9A*8B

[71)BBB&BB [7E)79&8

1999 8999*9A*8A

[7)99&88 [77)18A&D8

8999 8999*9A*8A

[7B)999&99 [71)AE8&AB

999 8999*9A*8A

[7)9A&1 [7E)DA&E7

1999 8999*9A*9

[E)999&9D [)99&E9

999 8999*9A*9

[7)BEB&BE [7B)&E7

8999 8999*9A*9

[7A)B9&9 [7E)A&A8

Mo<ing A<erage ith "eset Capa!ilities

Like the other 3L4 functions) there is a method to reset a mo+ing a+erage to pro+ide areak or reset to occur&

'sing A8 and $E" # "$:& and PA"TITI$N BY

  reset on a mo+ing a+erage can now e otained using NS, synta.& This process isre/uested using the <I y re/uesting the 3<0R option& The 4RT,T,3N # identifies thecolumn used to initiate a reset when its +alue changes&

The following NS, synta. is used with <I to pro+ide $<I 3L4 functionality:

S0L0CT A8(3column1name4) $E" ( PA"TITI$N 3column1name4

Page 218: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 218/401

Page 219: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 219/401

Page 220: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 220/401

Page 221: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 221/401

Page 222: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 222/401

Product7I &ale7ate aily7&ales -uantile

97

1999 8999*19*98

8B99&9 18

8999 8999*19*98

E981&A 8

1999 8999*19*91

79899&7 D

8999 8999*19*9

7899&1B 9

1999 8999*19*97

7&19 E8

8999 8999*19*91

7B9&8A D

1999 8999*19*9

E799&99 BD

Notice that the only difference) etween these two e.ample outputs is in the first two rows of the second e.ample& This is ecause the Sale date "0SC) impacts the first two rows& 2hy

Since these rows ha+e the same +alue) it uses the SaleW"ate column as a tiereaker for these/uencing and makes them different from each other& =ence) they are assigned to different+alues in different partitions&

-'ALI%Y to %ind Products in the top Partitions

Like the aggregate functions) 3L4 functions must read all re/uired rows efore performingtheir operation& Therefore) the 2=0R0 clause cannot e used& 2here the aggregates use=<,NI) the 3L4 functions uses Q5L,-& The Q5L,- e+aluates the result todetermine which ones to return&

The following S0L0CT uses a Q5L,- to show only the products that sell in the top E94ercentile:

S0L0CT 4roductW,"

  )SaleW"ate )"ailyWSales

  )-'ANTILE (066J aily7&alesJ &ale7ate ) as VPercentileV

-R3$ SalesWtale

-'ALI%Y VPercentileV 4? 6 H

B Rows Returned

Product7I &ale7ate aily7&ales Percentile

8999 8999*9A*8A

7B999&99 E1

1999 8999*9A*8B

7BB9&79 EE

Page 223: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 223/401

Product7I &ale7ate aily7&ales Percentile

8999 8999*9A*9

7AB9&9 D1

1999 8999*9A*

8A

799&88 DE

1999 8999*19*97

7&19 B9

8999 8999*19*91

7B9&8A B

999 8999*9A*8B

E191&DD A9

1999 8999*19*9

E799&99 A

 lthough ascending is the default se/uence for oth the Q5NT,L0 and data +alue) many

people think of the percentile with the highest numer eing est and therefore wish to see itlisted first&

The following modifies the pre+ious S0L0CT to incorporate the 3R"0R # to otain adifferent se/uence in the answer set:

S0L0CT 4roductW,"

  )SaleW"ate )"ailyWSales

  )Q5NT,L0 !199) "ailyWSales) SaleW"ate % as ;4ercentile;

-R3$ SalesWtale

Q5L,- ;4ercentile; M E9

$"E" BY VpercentileV E&C

H

B Rows Returned

Product7I &ale7ate aily7&ales Percentile

1999 8999*19*9

E799&99 A

999 8999*9A*8B

E191&DD A9

8999 8999*19*91

7B9&8A B

1999 8999*19*97

7&19 B9

1999 8999*9A*8A

799&88 DE

8999 8999*9A*9

7AB9&9 D1

1999 8999*9A* 7BB9&79 EE

Page 224: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 224/401

Product7I &ale7ate aily7&ales Percentile

8B

8999 8999*9A*8A

7B999&99 E1

The 3R"0R # changes the se/uence of the rows eing listed) not the meaning of thepercentile& The ao+e functions oth determined that the highest numer in the column isthe highest percentile& The data +alue se/uence ascends as the percentile ascends or descends as the percentile descends&

2hen the sort in the Q5NT,L0 function is changed to SC the data +alue se/uencechanges to ascend as the percentile descends& ,n other words) the se/uence of thepercentile does not change) ut the data +alue se/uence is changed to ascend !SC%instead of the default) which is to descend !"0SC%&

The following S0L0CT uses the SC to cause the data +alues to go contradictory to thepercentile:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )-'ANTILE (066J aily7&ales A&CJ &ale7ate )

  as ;4ercentile;

-R3$ SalesWtale

Q5L,- ;4ercentile; ME9 H

B Rows Returned

Product7I &ale7ate aily7&ales Percentile

1999 8999*9A*9

E999&9D E1

999 8999*9A*8A

79A&1 EE

1999 8999*19*98

8B99&9 D1

8999 8999*19*97

8B99&9 DE

999 8999*19*91

8B999&99 B9

999 8999*19*9

81&DA B

999 8999*19*98

1AEDB&A7 A9

999 8999*19*97

1ED& A

Page 225: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 225/401

The ne.t S0L0CT modifies the ao+e /uery to incorporate the 4roduct ," as a tiereaker for the two rows with sales of [8)B99&9:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )-'ANTILE (066J aily7&ales A&CJ &ale7ate E&C)

  as ;4ercentile;

-R3$ SalesWtale

Q5L,- ;4ercentile; M E9 H

B Rows Returned

Product7I &ale7ate aily7&ales Percentile

1999 8999*9A*9

E999&9D E1

999 8999*9A*8A 79A&1 EE

1999 8999*19*98

8B99&9 D1

8999 8999*19*97

8B99&9 DE

999 8999*19*91

8B999&99 B9

999 8999*19*9

81&DA B

999 8999*19*

98

1AEDB&A7 A9

999 8999*19*97

1ED& A

 lthough the pre+ious /ueries were all ased on percentiles !199% other +alues can e usedwith interesting results&

The following S0L0CT uses a /uartile !Q5NT,L0 ased on 7 partitions%:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )Q5NT,L0 !7) "ailyWSales ) SaleW"ate % S ;"ecile;-R3$ SalesWtale

H

81 Rows Returned

Product7I &ale7ate aily7&ales ecile

999 8999*19* 1ED& 9

Page 226: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 226/401

Product7I &ale7ate aily7&ales ecile

97

999 8999*19*98

1AEDB&A7 9

999 8999*19*9

81&DA 9

999 8999*19*91

8B999&99 9

1999 8999*19*98

8B99&9 9

8999 8999*19*97

8B99&9 9

999 8999*9A*8A

79A&1 1

1999 8999*9A*9

E999&9D 1

8999 8999*19*98

E981&A 1

1999 8999*19*91

79899&7 1

8999 8999*9A*8B

71BBB&BB 1

8999 8999*19*9

7899&1B 8

999 8999*9A*9 7BEB&BE 8

8999 8999*9A*8A

7B999&99 8

1999 8999*9A*8B

7BB9&79 8

8999 8999*9A*9

7AB9&9 8

1999 8999*9A*8A

799&88

1999 8999*19*

97

7&19

8999 8999*19*91

7B9&8A

999 8999*9A*8B

E191&DD

1999 8999*19*9

E799&99

Page 227: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 227/401

 ssigning a different +alue to the Kpartitions indicator of the Q5NT,L0 function changesthe numer of partitions estalished& 0ach Quantile partition is assigned a numer starting at9 increasing to a +alue that is one less than the partition numer specified& So) with a/uantile of 7 the partitions are 9 through and for 19) the partitions are assigned 9 throughA& Then) all the rows are distriuted as e+enly as possile into each partition from highest tolowest +alues& Normally) e.tra rows with the lowest +alue egin ack in the lowest numeredpartitions&

"an+ing ata using "AN2

Compatiility: Teradata 0.tension and NS,

The Ranking function !RNJ% permits a column to e e+aluated and compared) either asedon high or low order) against all other rows to create the output set& The order will e sortedy default in descending se/uence of the ranking column) which correlates to descendingrank&

This style of selecting the est and the worst has een a+ailale using SQL in the past&

=owe+er) it was +ery in+ol+ed and re/uired e.tensi+e coding and logic in order to make itwork& The new RNJ function replaces all the elaorate SQL pre+iously re/uired to createthis type of output&

The output of the RNJ function is the highest or the lowest data +alues in the column)depending on the sort re/uested& /uery can return a specified numer of the ;est; rows!highest +alues% or the ;worst; rows !lowest +alues%& These capailities and output optionswill e demonstrated elow&

=ere is the synta. for RNJ:

S0L0CT "AN2( 3column1name4 OE&C A&C )

-R3$ Ktale*name

IR354 # Kcolumn*name )Kcolumn*numer O O P SC "0SC OQ5L,- RNJ!Kcolumn*name% PK KM Knumer*of*rows O

H

The ne.t S0L0CT ranks all columns of the Sales tale y the daily sales for all a+ailaledays:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )RNJ!"ailyWSales%

-R3$ SalesWtale

H

81 Rows Returned

Product7I 7  &ale7ate

aily7&ales "an+

1999 8999*19*9

E799&99 1

Page 228: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 228/401

Product7I 7  &ale7ate

aily7&ales "an+

999 8999*9A*8B

E191&DD 8

8999 8999*19*91

7B9&8A

1999 8999*19*97

7&19 7

1999 8999*9A*8A

799&88

8999 8999*9A*9

7AB9&9 E

1999 8999*9A*8B

7BB9&79 D

8999 8999*9A*8A 7B999&99 B

999 8999*9A*9

7BEB&BE A

8999 8999*19*9

7899&1B 19

8999 8999*9A*8B

71BBB&BB 11

1999 8999*19*91

79899&7 18

8999 8999*19*

98

E981&A 1

1999 8999*9A*9

E999&9D 17

999 8999*9A*8A

79A&1 1

0666  9666106169 

@9G66D6  0 

9666  966610616 

@9G66D6  0 

999 8999*19*91

8B999&99 1B

999 8999*19*9

81&DA 1A

999 8999*19*98

1AEDB&A7 89

999 8999*19*97

1ED& 81

Page 229: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 229/401

Page 230: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 230/401

Product7I &ale7ate aily7&ales "an+

999 8999*19*97

1ED& 81

999 8999*19*

98

1AEDB&A7 89

999 8999*19*9

81&DA 1A

The twist here is that the Q5L,- was not changed& ,t still checks for ;K7; in this form of the/uery& So) it acts more like a row counter instead of a +alue comparison&

"AN2 ith "eset Capa!ilities

There is a method a+ailale to reset a RNJ function to pro+ide the est or worst rank of agroup of rows that contain a common +alue in another column& ,t uses the IR354 #designation to specify a data +alue that) when it changes) causes the accumulation +alue to

e reset ack to ero&

 s indicated ao+e) the reset process takes place using either techni/ue& The onlydifference is the synta. used to re/uest and define the +alues&

'sing "AN2 ith 8"$'P BY

Compatiility: Teradata 0.tension

 s pre+iously seen) the RNJ function permits a column to e ranked) either ased on highor low order) against other rows& The IR354 # can e used in con(unction with a RNJfunction to change the ranking function's scope& This allows a check on which items were inthe top sales racket for each store&

The following S0L0CT ranks the daily sales for each product using the IR354 # andcreates an alias for the RNJ column to use in the Q5L,- to find the est 8 days:

S0L0CT 4roductW,"

  )SaleW"ate

  )"ailyWSales

  )RNJ!"ailyWSales% S Ranked

-R3$ SalesWtale

8"$'P BY Product7I

Q5L,- Ranked KM 8

H

E Rows Returned

Product7I &ale7ate aily7&ales "an+ed

1999 8999*19*9

E799&99 1

1999 8999*19* 7&19 8

Page 231: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 231/401

Product7I &ale7ate aily7&ales "an+ed

97

8999 8999*19*91

7B9&8A 1

8999 8999*9A*9

7AB9&9 8

999 8999*9A*8B

E191&DD 1

999 8999*9A*9

7BEB&BE 8

 ll of the e.amples of the RNJ function seen so far are ased on daily sales& 2hat if theRNJ was re/uested for monthly sales instead

The ne.t S0L0CT gets data from a monthly +iew of the sales tale for monthly acti+ity:

S0L0CT 4roductW,"  )rW$onth !format 'AAAA*AA'%

  )$onthlyWSales !format '[[[[)[[[&AA'%

  )RNJ!Monthly7&ales% S Ranked

-R3$ $onthlyWSalesW<

H

E Rows Returned

Product7I Yr7Month Monthly7&ales "an+ed

1999 8999*19 [1A1)B7&9 18999 8999*19 [1EE)BD8&A9 8

8999 8999*9A [1A)DB&A1

999 8999*9A [1A)EDA&DE 7

1999 8999*9A [1A)9&EA

999 8999*

Internal "AN2 operations

,n the initial releases of RNJ) Teradata read all participating rows +ia the 2=0R0 clauseinto spool and then performed the ranking processing& 3n millions of rows) this techni/ue isnot terrily effecti+e regarding C45 and space utiliation&

,n release <8R7) NCR has implemented -irst N 3ptimiation for RNJ processing& Thismeans that the Q5L,- clause is used to determine the numer of rows !N% on each $4&Therefore) each $4 returns only that many /ualifying rows instead of all participating rows&Then) the $4s aggregate the selected rows to determine the final ranking of the rows for return to the client& This can dramatically reduce the o+erall numer of rows eing read andcompared&

Page 232: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 232/401

The current way to determine whether or not this processing is eing used is through the064L,N& The phrases ;all*$4 STT -5NCT,3N; and ;redistriuted y hash code; aresigns that it is working& The ca+eat is that either phrase can change in future releases& Themain telltale sign of its use should e the impro+ed performance characteristic&

Now) with that eing said) there might e occasions when the client wishes for Teradata todisale the -irst N 3ptimiation processing and e.amine all participating rows& To force thistype of processing a dummy condition like !1M1% may e added to the Q5L,-&

The following demonstrates the synta. for using this techni/ue:

Q5L,- RNJ!Kcolumn*name% KM Kliteral*+alue N" !1M1%

&ampling "os using the &AMPLE %unction

Compatiility: Teradata 0.tension

The Sampling function !S$4L0% permits a S0L0CT to randomly return rows from aTeradata dataase tale& ,t allows the re/uest to specify either an asolute numer of rows

or a percentage of rows to return& dditionally) it pro+ides an aility to return rows frommultiple samples&

The synta. for the S$4L0 function:

S0L0CT P Kcolumn*name G

  )Kcolumn*name O

  )S$4L0," O

-R3$ Ktale*name

&AMPLE 3num!er1o,1ros4 3percentage4 *

O J3num!er1o,1ros4 3percentage4

H

The ne.t S0L0CT uses the S$4L0 to get a random sample of the sales tale:

S0L0CT G

-R3$ studentWcourseWtale

&AMPLE D=

Rows Returned

&tudent7I Course7I

8B998 819

8E9999 799

18E7 199

18E7 889

79 99

This ne.t S0L0CT uses the S$4L0 function to re/uest multiple samples to create aderi+ed tale !co+er later%& Then) the uni/ue rows will e counted to show the random /ualityof the S$4L0 function:

Page 233: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 233/401

S0L0CT count!distinct!courseWid%%

-R3$ !S0L courseWid -R3$ studentWcourseWtale &AMPLE D% "T H

1 Row Returned

count(distinct(course7id)

7

,n the ao+e e.ecution) all fi+e rows contained a different data +alue in the course ,"& second run of the same S0L0CT might +ery well yield these results:

1 Row Returned

count(distinct(course7id)

Sometimes) a single sampling of the data is not sufficient& The S$4L0 function can eused to re/uest more than one sample y listing either the numer of rows or the percentageof the rows to e returned&

The ne.t S0L0CT uses the S$4L0 function to re/uest multiple samples:

S0L0CT G

-R3$ studentWcourseWtale

&AMPLE 9DJ 9D

3R"0R # 1)8 H

B Rows Returned

&tudent7I Course7I

1889 199

18E7 199

18E7 889

81888 889

8E9999 799

8B998 819

881 99

79 99

 lthough multiple samples were taken) the rows came ack as a single answer setconsisting of 9U !&8 X &8% of the data& 2hen it is necessary to determine which rowscame from which sample) the S$4L0," column name can e used to distinguish etweeneach sample&

This S0L0CT uses the S$4L0 function with the S$4L0," to re/uest multiple samplesand denote which sample each row came from:

S0L0CT StudentW,"

Page 234: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 234/401

Page 235: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 235/401

&tudent7I Course7I &ampleId

8E9999 799 1

79 99 1

18E7 199 181888 889 8

1889 199 8

18E7 889 8

881 99 8

81888 819

87181 199

881 889

18E7 899

79 799 7

87E8 899 7

Since S$4L0," is a column) it can e used as the sort key&

The 3L4 functions pro+ide some +ery interesting and powerful functionality for e.aminingand e+aluating data& They pro+ide an insight into the data that was not easily otained prior to these functions&

 lthough they look like ggregates) they are not normally compatile with them in the sameS0L0CT list& s demonstrated here) aggregation can e performed) howe+er) they must ecalculated in a temporary or deri+ed tale&

"AN$M Num!er 8enerator %unction

Compatiility: Teradata 0.tension

The RN"3$ function generates a random numer that is inclusi+e for the numersspecified in the SQL that is greater than or e/ual to the first argument and less than or e/ualto the second argument&

The RN"3$ function may e used in the S0L0CT list) in a CS0) in a 2=0R0 clause) ina Q5L,-) in a =<,NI and in an 3R"0R #&

The synta. for RN"3$ is:"AN$M!Klow*literal*+alue) Khigh*literal*+alue%

 lthough RN"3$ can e used in many parts of an SQL statement) some constructs wouldnot make sense when used together& -or instance) the following is meaningless:

S0L RN"3$!1)89% =<,NI RN"3$!1)89% H

 t the same time) used creati+ely it can pro+ide some powerful functionality within SQL&

Page 236: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 236/401

The ne.t S0L0CT uses the RN"3$ function to return a random numer etween 1 and89:

S0L0CT "AN$M(0J 96)H

1 Row Returned

"AN$M(0J96)

17

The ne.t S0L0CT uses RN"3$ to randomly select 1U of the rows from the tale:

S0L0CT G

-R3$ SalesWtale

:;E"E "AN$M(0J 066) ? 0=

8 Row Returned

Product7I sale7date daily7sales

999 8999*9A*8A

79A&1

1999 8999*9A*9

E999&9D

There is roughly a 1U !1 out of 199% chance that a row will e returned using RN"3$ inthe 2=0R0 clause) completely at random& Since S$4L0 randomly selects rows out of spool) currently RN"3$ will e faster than S$4L0& =owe+er) S$4L0 will e moreaccurate regarding the numer of rows eing returned with oth the percent and row count&There is discussion that NCR is changing S$4L0 to randomly select from the $4sinstead of from spool& 2hen this occurs) their performance characteristics should e moresimilar&

The ne.t e.ample uses RN"3$ to randomly set the +alue in the column to a randomnumer etween 1999 and 999 for a random 19U of the rows:

54"T0 SalesWtale

S0T "ailyWSales M "AN$M(0666J @666)

2=0R0 "AN$M(0J 066) BET:EEN 0 and 06H

This last e.ample uses RN"3$ to randomly generate a numer that will determine whichrows from the aggregation will e returned:

S0L0CT 4roductW,") C35NT!dailyWsales%

-R3$ SalesWtale

IR354 # 1

=<,NI C35NT!dailyWsales% 4 "AN$M(0J 06) H

8 Rows Returned

Product7I Count(daily7sales)

8999 D

Page 237: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 237/401

Product7I Count(daily7sales)

999 D

Then) on the +ery ne.t e.ecution of the same S0L0CT) the following might e returned:

No Rows Returned

2hene+er a random numer is needed within the SQL) RN"3$ is a great tool&

Chapter 11: &ET $perators

&et $perators

The Teradata dataase pro+ides the NS, standard S0T operators: ,NT0RS0CT) 5N,3N)and 06C04T) as well as the Teradata $,N5S e.tension& They are /uite simply named for 

the way they work& ,t is said that SQL is set oriented with each S0L0CT returning a set of rows& The S0T operators are used to comine answer sets from multiple S0L0CTstatements into a single answer set& The enefit to these operators is that the separateS0L0CT operations can run in parallel) prior to eing comined& dditionally) they all run asa single transaction&

Considerations ,or 'sing &et $perators

The following considerations are guidelines for writing each S0L0CT when using S0Toperators:

1& $ust specify the same numer of columns in the list& 0ach column must eof the same domain !data type and +alue range%

8& ,f using aggregation) each S0L0CT must ha+e an indi+idual IR354 #& $ust ha+e a -R3$7& -irst S0L0CT

a& 5sed to specify -3R$T& 5sed to specify T,TL0c& 5sed to specify alias names

& Last S0L0CTa& 5sed to specify 3R"0R #) only one shared y all sets& Contains the single semi*colon which ends the statement

E& 2hen using comined 3peratorsa& ll ,NT0RS0CT operators performed first& ll 5N,3N operators performed secondc& ll 06C04T and $,N5S operators performed last

d& 4arentheses can e used to change the ao+e order of e+aluationD& "uplicate rows

a& 0liminated from the answer sets& LL specification can e added to S0T operator to return duplicate

rowsB& Can e used in most SQL operationsA& 2,T= and 2,T= # not supported) treated as data) not a report

The following tales are used in the e.amples of S0T operators:

Page 238: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 238/401

Page 239: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 239/401

INTE"&ECT

S0L0CT $grWno

-R3$ "epartmentWtale

3R"0R # 1H

7 Rows ReturnedManager 

199987

11817

18E7A

177

 s o+ious as this might appear) it contains some sutle traps& There are four rows output)ut fi+e different departments& ,n +iewing this output) it appears that no manager isresponsile for more than one department and one department does not ha+e a manager&

=owe+er) this could e a misconception&

0arlier) the considerations section indicated that S0T operators eliminate duplicate rows&Therefore) if a manager's employee numer were selected more than once) the S0Toperator throws away all duplicates and returns only one row&

,n order to see the duplicates) the process of eliminating them must e turned off& This iseasily accomplished y coding the ao+e statement as an ,NT0RS0CT LL& s a matter of fact the keyword LL actually speeds up the set operator /ueries ecause Teradata does notha+e to look for and eliminate duplicates&

 nytime you are using S0T operators and you know the information has no duplicates youshould use the LL keyword to speed up the re/uest processing& #ecause we did not usethe LL keyword in our last e.ample) the output contains the manager's employee numer 

only once&

Therefore) the following is another way to determine all departmental managers using the,NT0RS0CT LL to pre+ent the identical employee numers from eing eliminated:

S0L0CT 0mployeeWno S $anager 

-R3$ 0mployeeWtale

INTE"&ECT ALL

S0L0CT $grWno

-R3$ "epartmentWtale

3R"0R # 1H

Rows Returned

Manager 

199987

1181709D@H 09D@H 

Page 240: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 240/401

Manager 

177

Now) it is known that one employee manages two departments& s useful as this might e)this re/uest might e a etter way to determine departmental managers y also including thedepartment numer they manage:

S0L0CT 0mployeeWno S $anager 

  )"eptWno !T,TL0 '"epartment Numer' %

-R3$ 0mployeeWtale

INTE"&ECT ALL

S0L0CT $grWno

  )"eptWno

-R3$ "epartmentWtale

3R"0R # 8)1H

1 Row Returned

epartmentNum!er 

Manager 

799 18E7A

Now) there is only one row returned& Since there are two columns from each tale) othcolumns are used in the (oin& Therefore) employee 18E7A works in department 799) sooth matched and it was returned& This person also manages department 199) ut since 799is not e/ual to 199) that row is not returned& There are limitations that need to e consideredwhen using ,NT0RS0CT&

 s this illustrates) the ,NT0RS0CT is a it limited in its fle.iility to return columns that areoutside the domain of oth tales& Therefore) one of the est techni/ues for using the,NT0RS0CT is for populating a deri+ed tale or in a +iew&

3nce the tale has een deri+ed) in parallel using the S0T operator) it can then e used toperform either an ,NN0R or 35T0R (oin to otain the additional columns from one or moreother tales&

The ne.t ,NT0RS0CT populates a deri+ed tale !see Temporary Tales chapter% and then (oins it to the 0mployee tale to find out the students taking ,ntroduction to SQL:

S0L0CT 0mployeeWno S $anager 

  )TR,$!LastWname%') '-irstWname S ;Name;

-R3$ ! S0L0CT 0mployeeWno -R3$ 0mployeeWtale  INTE"&ECT

  S0L0CT $grWno -R3$ "epartmentWtale %

"T !empno% ,NN0R @3,N 0mployeeWtale

3N empno M 0mployeeWno

3R"0R # ;Name; H

Page 241: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 241/401

Page 242: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 242/401

epartment7name ept7no

Customer Support 799

=uman Resources 99

$arketing 199Research and"e+elopment

899

Sales 99

Now) the LL is added to allow duplicates:

S0L0CT "epartmentWname) "eptWno -R3$ "epartmentWtale

'NI$N ALL

S0L0CT "epartmentWname) "eptWno -R3$ "epartmentWtale

3R"0R # 1H

19 Rows Returned

epartment7name ept7no

Customer Support 799

Customer Support 799

=uman Resources 99

=uman Resources 99

$arketing 199

$arketing 199

Research and"e+elopment

899

Research and"e+elopment

899

Sales 99

Sales 99

 s mentioned pre+iously) the second +ersion using LL runs faster& 2hen there is nopossiility of duplicates) always use LL& =owe+er) if duplicates will cause a prolem in theoutput) y all means) don't use the LL&

The 5N,3N is commonly used to create reports that comine data from slightly differentdomains& -or instance) managers are responsile for departments and employees work indepartments) for a manager&

The ne.t 5N,3N will return the departmental information and comine it with the employeeinformation:

S0L0CT "eptWno !T,TL0 '"epartment' %

  )'0mployee' !T,TL0 ' ' %

Page 243: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 243/401

  )-irstWnameLastWname S ;Name;

-R3$ 0mployeeWtale

'NI$N ALL

S0L0CT "eptWno

  )'"epartment'

  )"epartmentWname

-R3$ "epartmentWtale

3R"0R # 1)8H

19 Rows Returned

epartment 

Name

199 "epartment $arketing

199 0mployee $andeeChamers

899 "epartment Researchand"e+elopment

899 0mployee @ohn Smith

99 "epartment Sales

99 0mployee LoraineLarkins

799 "epartment Customer  Support

799 0mployee =erert

=arrison

799 0mployee 2illiam Reilly

799 0mployee CletusStrickling

Like the other S0T operators) 5N,3N will eliminate duplicates and the LL can e used topre+ent this from happening& lthough there would ne+er e any duplicates on this output)the LL should e used to pro+ide peak performance& Since there are no duplicates) do notforce Teradata to attempt to eliminate them and the /uery will run faster&

EQCEPTCompatiility: NS,

The 06C04T set operator is used to eliminate common domain +alues from the answer sety throwing away the matching +alues& This is the primary S0T operator that pro+ides acapaility not a+ailale using either an ,NN0R or 35T0R @3,N& lthough the 35T0R @3,Ndoes return missing row data) it also includes the matching or intersecting rows& The06C04T will only return the missing domain rows and therefore pro+ides a uni/ue capaility&

Page 244: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 244/401

The synta. of the 06C04T:

S0L0CT Kcolumn*name !T,TL0 'Column Title') -3R$T '***' % O

  )Kcolumn*name &&& O S Kalias*name O

-R3$ Ktale*name

EQCEPT O ALL

S0L0CT Kcolumn*name

  )Kcolumn*name &&& O

-R3$ Ktale*name

3R"0R # Kdisplayed*columns O

H

The following e.ample will return all departments without employees) therefore) the"epartment tale is in the first S0L0CT:

S0L0CT "eptWno S "epartmentWNumer -R3$ "epartmentWTale

EQCEPT

S0L0CT "eptWno -R3$ 0mployeeWTale H

1 Row Returned

epartment7Num!er 

99

 s mentioned earlier in this chapter) the restriction regarding the use of only domaincolumns) makes the output a it cryptic and it might e nice to see the department name&

The ne.t S0L0CT uses a deri+ed tale to otain the department for a (oin with thedepartment data to return the name of the department without employees working in it:

S0L0CT "epartmentWname S "epartmentsWwithoutW0mployees

-R3$ !S0L0CT deptWno -R3$ "epartmentWtale

  EQCEPT

  S0L0CT deptWno -R3$ 0mployeeWtale %

"T !depno% ,NN0R @3,N "epartmentWtale

3N depno M deptWno

3R"0R # 1

H

1 Row Returned

epartments7ithout7Employees

=uman Resources

MIN'&

Page 245: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 245/401

Compatiility: Teradata 0.tension

The $,N5S set operator is e.actly the same as the 06C04T& ,t was the original S0Toperator in Teradata efore 06C04T ecame the standard& ,ts name is actually moredescripti+e than the 06C04T& #oth of these S0T operators select the first answer set andeliminate or minus all rows that match& =owe+er) 06C04T should proaly e used for compatiility&

The synta. of the $,N5S:

S0L0CT Kcolumn*name !T,TL0 'Column Title') -3R$T '***' % O

  )Kcolumn*name &&& O S Kalias*name O

-R3$ Ktale*name

MIN'& O ALL

S0L0CT Kcolumn*name

  )Kcolumn*name &&& O

-R3$ Ktale*name

3R"0R # Kdisplayed*columns O

H

$,N5S makes more sense when thinking aout the way it works& 3nce oth answer sets arein spool) the rows from the second are sutracted from the first !minus%& =owe+er) since the$,N5S and the 06C04T perform the e.act same function) it is recommended to use06C04T for compatiility reasons& Therefore) for e.amples of its use see those ao+e using06C04T&

'sing Multiple &et $perators in a &ingle "e>uest

 s mentioned earlier) all of the Set operators may e comined into a single re/uest& The listof considerations indicated that the order of processing is: ,NT0RS0CT) 5N,3N and06C04TF$,N5S& ,f there is more than one of any of these S0T operators) they will eperformed in the order coded) from top to ottom& =owe+er) the se/uence may e changedat any time y enclosing any operator and its associated S0L0CT re/uests in parentheses&

The following comines one of each operator without changing the natural se/uence:

S0L0CT "eptWno !T,TL0 '"epartment' % )0mployeeWno !T,TL0 ' ' %

-R3$ 0mployeeWtale

'NI$N ALL

S0L0CT "eptWno )employeeWno

-R3$ 0mployeeWtaleINTE"&ECT ALL

S0L0CT "eptWno )mgrWno

-R3$ "epartmentWtale

MIN'&

S0L0CT "eptWno )mgrWno

-R3$ "epartmentWtale

Page 246: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 246/401

Page 247: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 247/401

epartment 

99 81888

799 11817

799 18E7A

799 18E7A

799 87181B

 s mentioned earlier) it takes some planning to comine them& lso e sure to notice thate+ery S0L0CT must ha+e the same numer of columns and they must e of the samedomain& ,t ecomes apparent that it is not necessarily an easy re/uest to write and it is a itlimited in its fle.iility& That is why we tend to use them indi+idually to populate deri+ed talesor in +iews for (oining against other tales or to eliminate rows from multiple answer sets&

Chapter 18: ata Manipulationata Maintenance

,n a data*warehousing en+ironment) the trend is to spend A9 to AEU of the time selectingdata& The rows of the tale are there to pro+ide insight into the operation of the usiness&0+eryone is looking for the golden /uery) the one that sa+es the corporation)[19)999)999&99&

 nother 8 to U of the time using the data warehouse is spent loading new data& $ost of this data is pulled from the operational on*line systems or the operations of the usiness& 3f the remaining time) 1 to 8U will e spent deleting old rows& -or the most part) a datawarehouse might ne+er update or modify e.isting dataH since to a large degree) it is historicdata&

Regardless of how the Teradata R"#$S data warehouse is used) there will come a point intime when you need to use the functionality of the other "ata $anipulation Language !"$L%commands esides S0L0CT& This chapter is dedicated to those other "$L statements&

Considerations ,or ata Maintenance

2hene+er data maintenance is eing performed attention needs to e paid to the result of the operation& ll changes made y one of these "$L commands should e +erified in a testdataase efore eing e.ecuted on a production dataase& 5nless the efore data image of rows is stored in the 4ermanent @ournal) once changes are made and committed to the

dataase) they are permanent& So) make sure the SQL is making the changes that wereintended&

&a,eguards

,n order to use the commands in this chapter) the appropriate pri+ileges are re/uired to makechanges to a gi+en tale within a dataase& These pri+ileges are named the same as the"$L operation: ,NS0RT) 54"T0) and "0L0T0&

Page 248: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 248/401

 ll three of these "$L statements need to otain a write lock on a tale or row& Therefore) arow cannot e changed y one "$L statement while another "$L statement is reading or modifying the row& This is ecause a lock is placed on the o(ect during an update& nyconflicting SQL commands are /ueued until the pre+ious lock is released& Likewise) a rowcannot otain a read lock on a row while it is eing updated&

  row cannot e changed or inserted if a new data +alue reaks the rules estalished in theconstraint& Constraints are sometimes placed on one or more columns in a tale& Theconstraint defines rules regarding the characteristics of and the types of data +alues thatmay e stored within the column!s% of a row&

Constraints are of these types: Check) a specific or range of +alues Referential ,ntegrity) 4rimary key e.ists for a -oreign key 5ni/ue) there is one and only one row per legal +alue N3T N5LL) there must e a +alue and N5LL is not allowed

There is additional information on constraints in the "ata "efinition Language !""L% chapter in this ook&

IN&E"T Command

The ,NS0RT statement is used to put a new row into a tale& status is the only returned+alue from the dataaseH no rows are returned to the user& ,t must account for all thecolumns in a tale using either a data +alue or a N5LL& 2hen e.ecuted) the ,NS0RT placesa single new row into a tale& lthough it can run as a single row insert) primarily it is used inutilities like #T0Q) -astLoad) $ultiLoad) T4ump or some other application that reads a datarecord and uses the data to uild a new row in a tale&

The following synta. of the ,NS0RT does not use the column names as part of thecommand& Therefore) it re/uires that the <L50S portion of the ,NS0RT match each ande+ery column in the tale with a data +alue or a N5LL&

IN&OE"T O INT$  Ktale*name

AL'E& ! Kliteral*data*+alue1 )

Kliteral*data*+alue8 &&& ) Kliteral*data*+alueN O O H

Note 5sing ,NS instead of ,NS0RT is not NS, compliant&

Since the column names are not used the ,NS0RT se/uences the data +alues column ycolumn& Therefore) the ,NS0RT must e.actly match the se/uence of the columns as definedy the CR0T0 T#L0& This includes a correct match on the data types as well&

This chapter uses the following tale called $yWtale) defined as:

%igure 0910 

 n e.ample of an ,NS0RT statement might appear like this:

Page 249: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 249/401

 ,NS0RT ,NT3

$yWtale <L50S ! '$y character data') 187&E) 198BD) ) N5LL) '8999*18*1' % H

 fter the e.ecution of the ao+e ,NS0RT) there is a new row with the first character data

+alue of ]$y character data^ going into Column1) the decimal +alue of 187&E into Column8)the integer 198BD into Column) N5LL +alues into Column7 and Column) and a date intoColumnE&

The N5LL e.pressed in the <L50S list is the literal representation for no data& =owe+er)the two commas !))% that follow the positional +alue for Column also represent missing data&The commas are placeholders or delimiters for the data +alues& 2hen no data +alue iscoded) the end result is a N5LL&

5nlike many of the columns in $yWtale) Column7 and Column are defined to allow aN5LL& ny attempt to place a N5LL into a column defined as N3T N5LL) will cause an error and the row is not inserted& ,n Teradata) the default in a CR0T0 T#L0 is to allow N5LL&=owe+er) a N3T N5LL can e used in the ""L to alter this default functionality&

There is another form of the ,NS0RT statement that can e used when some of the data isnot a+ailale& ,t allows for the missing +alues !N5LL% to e eliminated from the list in the<L50S clause& ,t is also the est format when the data is arranged in a different se/uencethan the CR0T0 T#L0) or when there are more nulls !unknown +alues% than a+ailaledata +alues&

The synta. of the second type of ,NS0RT follows:

 ,NS0RTO ,NT3 O

Ktale*name ! Kcolumn*name1 )Kcolumn*name8

)Kcolumn*nameN O O <L50S ! Kliteral*data*+alue1

)Kliteral*data*+alue8 )Kliteral*data*+alueN O O H

This form of the ,NS0RT statement could e used to insert the same row as the pre+ious,NS0RT e.ample& =owe+er) it might look like this:

 ,NS0RT ,NT3 $yWtale ! Column8)

Column1) Column) ColumnE % <L50S ! 187&E) '$y character data')18BD)

'8999*18*1'% H

The ao+e statement incorporates oth of the reasons to use this synta.& -irst) notice thatthe column names Column8 and Column1 ha+e een switched) to match the data +alues&

 lso) notice that Column7 and Column do not appear in the column list) therefore they areassumed to e N5LL& This is a good format to use when the data is coming from a file anddoes not match the order of the tale columns&

The third form of the ,NS0RT statement can e used to insert the same row as the pre+ious,NS0RT& ,t might look like this:

 ,NS0RT ,NT3 $yWtale

!Column8M187&E) Column1M'$y character data') ColumnM18BD)

ColumnEM'8999*18*1' % H

Page 250: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 250/401

'sing Null ,or E%A'LT AL'E&

Teradata now has the NS, "0-5LT <L50S functionality& lthough an ,NS0RT statementcould easily put a null +alue into a tale column) it re/uires it to use the N5LL reser+ed wordor y omitting a +alue for that column!s% etween commas&

The either of the ne.t two ,NS0RT statements may e used to uild a row with no data+alues in $yWtale:

 ,NS0RT ,NT3 $yWtale <L50S !) ) )

  ) ) % H ,NS0RT ,NT3 $yWtale <L50S!N5LL)N5LL)N5LL)N5LL)N5LL)N5LL% H

 

Since the Teradata release of <8R) it is now easier to insert null +alues into all columns&The following ,NS0RT can now e used:

 ,NS0RT ,NT3 $yWtale "0-5LT

  <L50SH

 lthough all of these ,NS0RT options uild a row with all N5LL +alues) it is proaly not anoption that is needed +ery often& -or instance) if a tale uses a 54, !5ni/ue 4rimary ,nde.%column) any of these ao+e commands could only e e.ecuted one time& 3nce a N5LL isthe +alue stored in the 4, column) it can e the only row !uni/ue% with that +alue&Therefore) to get the most enefit from any of these ,NS0RT options) the tale should ha+ea N54, !Non*5ni/ue 4rimary ,nde.%& dditionally) the tale should ha+e "0-5LT +aluesdefined using the CR0T0 T#L0 !see ""L chapter %& That way) the N5LL +alues arereplaced y the "0-5LT& 0+en then) all N5LL or "0-5LT +alues in the column!s% of the4, all go to the same $4& This pro+ides an aility to insert many nulls) it also creates a +eryhigh potential for skewed data rows with all the nulls going to the same $4& ,ts use is a itlimited&

IN&E"T # &ELECT Command

 lthough the ,NS0RT is great for adding a single row not currently present in the system) an,NS0RTFS0L0CT is e+en etter when the data already e.ists within Teradata& ,n this case)the ,NS0RT is comined with a S0L0CT& =owe+er) no rows are returned to the user&,nstead) they go into the tale as new rows&

The S0L0CT reads the data +alues from the one or more columns in one or more tales anduses them as the +alues to ,NS0RT into another tale& Simply put) the S0L0CT takes theplace of the <L50S portion of the ,NS0RT&

This is a common techni/ue for uilding data marts) interim tales and temporary tales& ,t isnormally a etter and much faster alternati+e than e.tracting the rows to a data file) thenreading the data file and inserting the rows using a utility&

,f the data needed is already in the data warehouse) why reload it ,nstead select it andinsert it&

The synta. of the ,NS0RT F S0L0CT follows:

IN&OE"T  ,NT3 O Ktale*name1

&ELECT Kcolumn*name1

Page 251: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 251/401

)Kcolumn*name8 )Kcolumn*nameN O O -R3$ Ktale*name8 H

2hen all columns are desired to make an e.act copy of the second tale and oth talesha+e the e.act same numer of columns in the e.act same order with the e.act same datatypesH an G may e used in the S0L0CT to read all columns without a 2=0R0 clause) as in

the ne.t e.ample: ,NS0RT ,NT3 $yWtale S0L0CT G -R3$

$yWoriginalWtaleH

Like all S0L0CT operations without a 2=0R0 clause) a full tale scan occurs and all therows of the second tale are inserted into $yWtale) using only the data +alues from thecolumns listed&

2hen fewer than all the columns are desired) either of the following ,NS0RT F S0L0CTstatements will do the (o:

 ,NS0RT ,NT3 $yWtale S0L0CT !

Column1) Column8) Column ) ) ) '8919*91*91' % -R3$

$yWoriginalWtale H

or 

 ,NS0RT ,NT3 $yWtale ! Column8)

Column1) Column) ColumnE% S0L0CT Column8) Column1) Column )C5RR0NTW"T0 -R3$

$yWoriginalWtale H

,n oth of the ao+e e.amples) only the first three and the last columns are recei+ing data& ,nthe first ,NS0RT) the data is a literal date& The second ,NS0RT uses the C5RR0NTW"T0&#oth are acceptale) depending on what is needed&

2orking with the same concept of a normal ,NS0RT) when using the column names the onlydata +alues needed are for these columns and they must e in the same se/uence as thecolumn list) not the CR0T0 T#L0& Therefore) omitted data +alues or column namesecome a N5LL data +alue&

Since the second part of this ,NS0RT is a S0L0CT) it can contain any of the functions of aS0L0CT& ,t might e an inner or outer (oin) su/uery or correlated su/uery& The S0L0CTalso may contain aggregates) literals) sustrings or deri+ed data&

Regardless) it is still +ery important to list the selected data +alues to match the se/uence of the columns in the CR0T0 T#L0& The columns to e inserted must e listed in ase/uence that matches the columns in the S0L0CT from the original tale&

 s an e.ample of a data mart) it might e desirale to uild a summary tale usingsomething like the following:

 ,NS0RT ,NT3 $yWtale S0L0CT !

Column1) S5$!Column8%) <I!Column%) C35NT!Column7%) <I!C=R!Column%%)

 <I!C=R!ColumnE%% % -R3$ $yWoriginalWtale IR354 # 1 H

=owe+er used) the ,NS0RT F S0L0CT is a powerful tool for creating rows from the rowsalready contained in one or more other tales&

Page 252: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 252/401

%ast Path IN&E"T # &ELECT

2hen the tale eing loaded is empty) the ,NS0RT F S0L0CT is +ery fast& This is especiallytrue when all columns and all rows are eing copied& Rememer) the tale eing loadedmust e empty to attain the speed& ,f there is e+en one row already in the tale) it negatesthe aility to take the -ast 4ath&

There are two reasons ehind this speed& -irst) there is no need to Transient @ournal anidentifier for each inserted row& Reco+ery) if needed) is to empty the tale& No other type of reco+ery can e easier or faster&

Second) when all columns and all rows are re/uested from the e.isting tale and theye.actly match the columns in the new tale) there is no need to use spool& The rows gostraight into the tale eing loaded& dditionally) when all rows are eing selected Teradatadoes not other to read the indi+idual rows& ,nstead) each $4 literally copies the locks of the original tale to locks for the new tale&

These reasons are why it is called the -ast 4ath& To use this techni/ue) the order of thecolumns in oth tales must match e.actly and so must the data types) otherwise spool muste used to rearrange the data +alues or translate from one data type to the other&

2hat if it is necessary to retrie+e the rows from multiple tales for the ,NS0RT

$ultiple ,NS0RT F S0L0CT operations could e performed as follows:

 ,NS0RT ,NT3 $yWtale S0L0CT G -R3$

  $yWoriginalWtaleW1 H ,NS0RT ,NT3 $yWtale S0L0CT G -R3$$yWoriginalWtaleW8 H

  ,NS0RT ,NT3 $yWtale S0L0CT G -R3$ $yWoriginalWtaleW H

The first ,NS0RTFS0L0CT into $yWtale loads the empty tale e.tremely fast) e+en withmillions of rows& =owe+er) the tale is no longer empty and the suse/uent ,NS0RT is muchslower ecause it cannot use the fast path& ll inserted rows must e identified in the

Transient @ournal& ,t can more than doule the processing time&

The real /uestion is: =ow to make all of the indi+idual S0L0CT operations act as one so thatthe tale stays empty until all rows are a+ailale for the ,NS0RT

3ne way to do this uses the 5N,3N command to perform all S0L0CT operations in parallelefore the first row is inserted into the new tale& Therefore all rows are read from the+arious tales) comined into a single answer set in spool and then loaded into the emptytale& ll of this is done at high speed&

-or instance) if all the rows from three different tales are needed to populate the new tale)the applicale statement might look like the following:

 ,NS0RT ,NT3 $yWtale S0L0CT G -R3$

  $yWoriginalWtaleW1 5N,3N S0L0CT G -R3$ $yWoriginalWtaleW85N,3N S0L0CT G -R3$

  $yWoriginalWtaleW H

 gain) the ao+e statement assumes that all four tales ha+e e.actly the same columns&2hether or not that would e+er e the case in real life) this is used as an e.ample& =owe+er)at this point we know the columns in the S0L0CT must match the columns in the tale to eloaded) no matter how that is accomplished&

Page 253: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 253/401

  second alternati+e method is a+ailale using #T0Q& The key here is that #T0Q can domultiple SQL statements as a single transaction for the S0L0CT and the ,NS0RToperations& The only way to do that is to delay the actual ,NS0RT) until all of the rows fromall the select operations ha+e completed& Then the ,NS0RT is performed as a part of thesame transaction into the empty tale&

The #T0Q trick mentioned ao+e is achie+ed in this manner:

 ,NS0RT ,NT3 $yWtale S0L0CT G -R3$

  $yWoriginalWtaleW1 H ,NS0RT ,NT3 $yWtale S0L0CT G -R3$$yWoriginalWtaleW8 H

  ,NS0RT ,NT3 $yWtale S0L0CT G -R3$ $yWoriginalWtaleW H#y ha+ing another SQL command on the same line as the semi*colon !H%) in #T0Q) they allecome part of the same multi*statement transaction& Therefore) all are inserting into anempty tale and it is much faster than doing each ,NS0RT indi+idually& Now you know thesecret too&

This does not work as fast in Queryman) ecause it considers each ,NS0RT as a singletransaction& Therefore) the tale is no longer empty for the second and third transactionsafter the first ,NS0RT transaction completes& Since it is not an empty tale after the firstinsert) the transient (ournal is used for all suse/uent inserts and they are all much slower due to rollack considerations and use of the Transient @ournal&

'PATE Command

The 54"T0 statement is used to modify data +alues in one or more columns of one or more e.isting rows& status is the only returned +alue from the dataaseH no rows arereturned to the user& ,n a data warehouse en+ironment) it is not normally a hea+ily used SQLcommand& That is ecause it changes data stored within a row and much of that data ishistoric in nature& Therefore) history is not normally changed&

=owe+er) when usiness re/uirements call for a change to e made in the e.isting data)then the 54"T0 is the SQL statement to use& ,n order for the 54"T0 to work) it mustknow a few things aout the data row!s% in+ol+ed& Like all SQL) it must know which tale touse for making the change) which column or columns to change and the change to makewithin the data&

-or pri+ileges) the user issuing the 54"T0 command needs 54"T0 pri+ilege against thetale or dataase in order for it to work& dditionally) the 54"T0 pri+ilege can e set at thecolumn le+el& Therefore) the aility to modify data can e controlled at that le+el&

The asic synta. for the 54"T0 statement follows:

'POATE Ktale*name S

Kalias*name O -R3$ Ktale*name8 S Kalias*name8 O O

&ET Kcolumn*name M

Ke.pression*or*data*+alue ) Kcolumn*name M

Ke.pression*or*data*+alue &&& O 2=0R0 Kcondition*test O N"

Kcondition*test &&& O 3R Kcondition*test &&& O LLO H

Note 5sing 54" instead of 54"T0 is not NS, compliant

Page 254: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 254/401

Page 255: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 255/401

Page 256: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 256/401

Page 257: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 257/401

 "0L0T0 -R3$ Ktale*name LL

O H

Since the -R3$ and the LL are optional) and the "0L0T0 can e are+iated) the ne.tcommand still remo+es all rows from a tale and e.ecutes e.actly the same as the ao+estatement:

 "0L Ktale*name H

,n the earlier releases of Teradata) the LL was re/uired to delete all rows& Now) NS, rulessay that LL is the default for all rows& The LL is optional and with or without it) all rows aredeleted& $ake sure that the intent really is to delete all rows? Teradata can delete one illionrows in a hearteat&

Normally) remo+ing all rows from a tale is not the intent& Therefore) it is a common practicefor a 2=0R0 clause to limit the scope of the "0L0T0 operation to specific rows& 5sually) itis the oldest data that is remo+ed&

 s seen pre+iously) the following command deletes all of the rows from $yWtale&

 "0L0T0 -R3$ $yWtaleH

2hereas) the ne.t "0L0T0 command only remo+es the rows that contained a date +alueless than 199181 !"ecemer 1) 8999% in ColumnE !"T0) data type% and lea+es all rowsnewer than or e/ual to the date:

 "0L0T0 -R3$ $yWtale 2=0R0 ColumnE

K 199181 H

$any times in a data warehouse the pre+ious format of the "0L0T0 statement canaccomplish most of the processing to remo+e old rows& ,t is also commonplace to use theao+e statement in $ultiLoad&

Sometimes it is desirale to delete rows from one tale ased on their e.istence in or ymatching a +alue stored in another tale& -or e.ample) you may e asked to gi+e a raise toall people in the wards Tale& To access these rows from another tale for comparison) asu/uery or a (oin operation can e used) as seen in either of these two formats:

The su/uery synta. for the "0L0T0 statement follows:

ELOETE Ktale*name S

Kalias*name O :;E"E Kcolumn*name

) Kcolumn*name8 )Kcolumn*nameN O O ,N ! S0L0CT

Kcolumn*name )Kcolumn*name8 )Kcolumn*nameN O O -R3$

Ktale*name S Kalias*name O 2=0R0 condition &&& O % LL O

H

The (oin synta. for "0L0T0 statement follows:

ELOETE Ktale*name1 -R3$

Ktale*name8 S Kalias*name O O :;E"E

Ktale*name1&Kcolumn*nameMKtale*name1&Kcolumn*name

Page 258: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 258/401

Page 259: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 259/401

 "0L0T0 -R3$ $yWtale 2=0R0 ColumnE

  K 199181 H

There are three different methods for using -ast 4ath 4rocessing in #T0Q for a "0L0T0&The first method uses an ,NS0RTFS0L0CT& ,t will e fast) ut it does re/uire pri+ileges for using the appropriate ""L& ,t also re/uires that additional 40R$ space e a+ailale for 

temporarily holding oth the rows to e kept and all of the original rows at the same time& ,NS0RT ,NT3 $yWtaleWcopy S0L0CT G

  -R3$ $yWtale 2=0R0 ColumnE 199189 H "R34 T#L0$yWtale H R0N$0

  $yWtaleWcopy to $yWtale H

This ne.t method also uses an ,NS0RTFS0L0CT and will e fast& ,t does not re/uirepri+ileges for using any ""L& ,t proaly will not e faster than the first method) since therows must all e put ack into the original tale& =owe+er) the tale is empty and the -ast4ath will e used:

 ,NS0RT ,NT3 $yWtaleWcopy S0L0CT G

  -R3$ $yWtale 2=0R0 ColumnE M 199189 H "0L0T0 $yWtale H,NS0RT ,NT3

  $yWtale S0L0CT G -R3$ $yWtaleWcopy H

#oth of these re/uire additional 40R$ space for temporarily holding the rows to e kept andall of the original rows at the same time& dditionally) it is essential that all statementscomplete successfully) or none of them complete& This is the definition of a transaction onlywhen using #T0Q& "on't forget that the reason this is one transaction is ecause the semi*colon is on the same line as the ne.t "$L statement& So) don't place the semi*colon at theend of the line ecause this ends the transaction prematurely&

This last ,NS0RTFS0L0CT co+ered here uses a Iloal Temporary Tale) which wasintroduced in Teradata with <8R and co+ered in the Temporary Tales chapter& ,t is also fast

and does not re/uire pri+ileges for using any ""L& =owe+er) there is some "ata "ictionaryin+ol+ement to otain the definition for the Iloal Temporary Tale) ut it does not need ""Land its space comes from T0$4 space) not from 40R$&

The ne.t ,NS0RTFS0L0CT uses a Iloal temporary tale to prepare for the singletransaction to copy $yWtale in #T0Q:

 ,NS0RT ,NT3 $yWIloalWtaleWcopy

  S0L0CT G -R3$ $yWtale 2=0R0 ColumnE M 199189 H "0L0T0$yWtale H ,NS0RT

  ,NT3 $yWtale S0L0CT G -R3$ $yWIloalWtaleWcopy H

,t re/uires that T0$43RR space e a+ailale for temporarily holding the rows to e keptand all of the original rows at the same time& <olatile Temporary tale could also e used&,ts space comes from spool& =owe+er) it re/uires a CR0T0 statement to uild the tale)unlike Iloal Temporary tales& $ore information on Temporary tales is a+ailale in thisook&

,f you are not using #T0Q) these statements can e used in a macro& This works ecausemacros always e.ecute as a transaction&

There are many operational considerations to take into account when deciding whether or not to use a -ast 4ath operation and which one to use& lways consider reco+ery and data

Page 260: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 260/401

integrity when performing any type of data maintenance& lso consider how large the tale isthat is eing manipulated& The larger the tale the more ad+antageous it might e to use the-ast 4ath& #ut rememer) to test it on non*production data& 4lease e careful of the riskswhen using production data&

'P&E"T

Compatiility: Teradata 0.tension

,n <8R7&1) NCR is incorporating a new synta. for an atomic 54S0RT command intoTeradata& ,t is targeted for use with a CL,+8) program) like #T0Q or other SQL interfaces!3"#C) Queryman) @"#C) etc%:

 n 54S0RT is the comination of an 54"T0 and an ,NS0RT& ,t works y monitoring the54"T0& ,f it fails ecause the row it is supposed to change is missing) the systemautomatically does an ,NS0RT of the row&

The synta. for the new 54S0RT command:

'PATE Ktale*name S0T

Kcolumn*name M Ke.pression )Kcolumn*name M

Ke.pression &&& O 2=0R0 Ktale*name1&OKcolumn*name M

Ktale*name1&OKcolumn*name N" Kcondition*test O 3RKcondition*test O

EL&E IN&E"T INT$ Ktale*name <L50S !

K+alue*list % H

The primary reason for this functionality is to support T4ump& T4ump takes ad+antage of thisnew command to more efficiently implement its 54S0RT capaility& #oth T4ump and$ultiLoad ha+e an internal 54S0RT capaility& =owe+er) an 54S0RT re/uires the 54"T0

statement to fail in order for the ,NS0RT to e performed& ,n $ultiLoad) e+ery part of the54S0RT processing is e.ecuted within the Teradata dataase while working with entirelocks of data rows& Con+ersely) T4ump does its work at the row le+el) not the lock le+el&

This means) using T4ump for an 54S0RT to a Teradata dataase prior to <8R7&1) thatwhen the 54"T0 statement fails the dataase sends a status ack to T4ump on theoriginating host !mainframe or other computer% where it is e.ecuting& Then) T4ump mustpackage up the data for the ,NS0RT and send it ack to Teradata& This is rather slow andre/uires additional processing on the host computer& 2ith <8R7&1) T4ump sumits a singlecommand to perform the re/uested 54S0RT&

The 54S0RT synta. for T4ump and $ultiload will not e changed& Therefore) it iscompatile with e.isting scripts and follows this format:

ML LABEL 3la!el1name4$ IN&E"T %$" MI&&IN8 'PATE "$:&=

'PATE Ktale*name S0T

Kcolumn*name M Ke.pression )Kcolumn*name M

Ke.pression &&& O 2=0R0 Ktale*name1&OKcolumn*name M

Ktale*name1&OKcolumn*name N" Kcondition*test O 3R

Kcondition*test O H ,NS0RT ,NT3 Ktale*name <L50S !

Page 261: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 261/401

K+alue*list % H

Considerations for using 54S0RT:1& S$0 T#L0: The 54"T0 and ,NS0RT specify the same tale&8& S$0 R32: The 54"T0 and ,NS0RT specify the ;same; row Y the

primary inde. +alue in the inserted row matches the one in the targetedupdate row&

& =S=0" R32 CC0SS: The 54"T0 fully specifies the primary inde. sothat the targeted row can e accessed with a one*$4 hashed operation&

AN&I s Teradata Transactions

Rememer that the Teradata R"#$S has the aility to e.ecute all SQL in either Teradatamode or in NS, mode& This makes a slight difference in what code is re/uired to guaranteethat all changes made to the rows are permanently kept&

,n Teradata mode) all SQL commands are implicitly a complete transaction& Therefore) oncea change is made) it is committed and ecomes permanent& ,t contains an implied C3$$,T

or an e.plicit 0N" TRNSCT,3N !0T%&

,n NS, mode) (ust the opposite is true& ll SQL commands are considered to e part of thesame logical transaction& transaction is not complete until an e.plicit C3$$,T is e.ecuted&

Therefore) each of the "$L commands in NS, mode needs to perform the followingcommand to permanently store the data) and more importantly) release the write locks thatare currently held:

 C3$$,T 23RJH

 s an e.ample) to remo+e all rows) oth statements elow can e needed in NS, mode&

 "0L0T0 -R3$ $yWtaleH C3$$,T 23RJH

2ithout a C3$$,T 23RJ) it is likely that the "0L0T0 will aort and all the rows will e putack& The ma(or downside to this techni/ue is that the -ast 4ath "0L0T0 is no longer allowed ecause there is potential that the rows might need to e put ack into the tale if something fails& Therefore) they must e logged&

Since a macro is always a transaction) it could still e used to impro+e performance&There is more transactional information in the ne.t chapter  of this ook&

Per,ormance Issues :ith ata Maintenance

The +ery mention of changing data on disk implies that space must e managed y the $4!s% owning the row!s% to modify& "ata cannot e changed unless it is read from the disk&

-or ,NS0RT operations) a new lock might e written or an e.isting lock might e modifiedto contain the new data row& The choice of which to use depends on whether or not there issufficient space on the disk to contain the original lock plus the numer of ytes in the newrow&

Page 262: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 262/401

,f the new row causes the lock to increase eyond the current numer of sectors) the $4must locate an empty slot with enough contiguous sectors to hold the larger lock& Then) itcan allocate this new area for the larger lock&

  "0L0T0 is going to make one or more locks shorter& Therefore) it should ne+er ha+e tofind a larger slot in which to write the lock ack to disk& =owe+er) it still has to read thee.isting lock) remo+e the appropriate rows and re*write the smaller lock&

The 54"T0 is more unpredictale than either the "0L0T0 or the ,NS0RT& This is ecausean 54"T0 might increase the sie of the lock like the ,NS0RT) decrease the sie like the"0L0T0 or not change the sie at all&

  larger lock might occur ecause one of the following conditions:  N5LL +alue was compressed and now must e e.panded to contain a +alue&

This is the most likely situation&  longer character literal is stored into a <RC=R column&

  smaller lock might occur ecause one of these conditions:  data +alue is changed to a N5LL +alue with compression& This is the most likely

situation&

  smaller character literal is stored into a <RC=R column&

  lock sie does not change:The column is a fi.ed length C=R) regardless of the length of the actual

character data +alue) the length stays at the ma.imum defined& ll numeric columns are stored in their ma.imum numer of ytes&

There are many reasons for performance gains or losses& nother consideration) which waspre+iously mentioned) is the (ournal entries for the Transient @ournal for reco+ery androllack processing& The Transient @ournal is mandatory and cannot e disaled& 2ithout it)data integrity cannot e guaranteed&

Impact o, %ALLBAC2 on "o Modi,ication2hen using -LL#CJ on tales) it negati+ely impacts the processing time when changingrows within a tale& This is due to the fact that the same change must also e made on the

 $4 storing the -LL#CJ copy of the row!s% in+ol+ed& These changes in+ol+e additionaldisk ,F3 operations and the use of two $4s instead of one for each row ,NS0RT) 54"T0)or "0L0T0& That e/uates to twice as much ,F3 acti+ity&

Impact o, PE"MANENT S$'"NAL Logging on "o Modi,ication

2hen using 40R$N0NT @35RNL logging on tales) it will negati+ely impact theprocessing time when changing rows within a tale& This is due to the fact that the 54"T0processing also inserts a copy of the row into the (ournal tale& ,f #0-3R0 (ournals are

used) a copy of the row as it e.isted efore a change is placed into the log tale& 2hen -T0R images are re/uested) a copy of the row is inserted into the (ournal tale that lookse.actly like the changed row&

There is another issue to consider for (ournaling) ased on S,NIL0 or "5L (ournaling&"5L asks for a second !mirror% copy to e inserted& ,t is the (ournals way to pro+ide-LL#CJ copies without the tale eing re/uired to use -LL#CJ& The caution here isthat if the T#L0 is -LL#CJ protected) so are the (ournals& This will further impact theperformance of the row modification&

Page 263: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 263/401

Impact o, Primary Inde. on "o Modi,ication

,n Teradata) all tales must ha+e a 4rimary ,nde. !4,%& ,t is a normal and +ery important partof the storage and retrie+al of rows for all tales& Therefore) there is no additional o+erheadprocessing in+ol+ed in an ,NS0RT or "0L0T0 operation for 4rimary ,ndices&

=owe+er) when using an 54"T0 and the data +alue of a 4, is changed) there is moreprocessing re/uired than when changing the content of any other column& This is due to thefact that the original row must e read) literally deleted from the current $4 and rehashed)redistriuted and inserted on another $4 ased on the new data +alue&

Rememer that 4rimary Jeys do not allow changes) ut 4rimary ,nde.es do& Since the 4,may e a column that is not the 4rimary Jey) this rule does not apply& =owe+er) e awarethat it will take more processing and therefore) more time to successfully complete theoperation when a 4, is the column eing modified&

Impact o, &econdary Indices on "o Modi,ication

,n Teradata) a Secondary ,nde. is optional& Currently) a tale may ha+e 8 secondary

indices& 0ach inde. may e a comination of up 1E columns within a tale& 0+ery uni/uedata +alue in a defined inde. has a row in the sutale and potentially one on each $4 for a N5S, !Non 5ni/ue Secondary ,nde.%& dditionally) e+ery inde. has its own sutale&

2hen using secondary indices on tales) it may also negati+ely impact the processing timewhen changing rows within a tale& This is due to the fact that when a column is part of aninde. and its data +alue is changed in the ase tale) the inde. +alue must also e changedin the sutale&

This normally re/uires that a row e read) deleted and inserted into a sutale when thecolumn is in+ol+ed in a 5S, !5ni/ue Secondary ,nde.%& Rememer that the delete and insertare proaly e on different $4 processors&

-or a N5S,) the processing all takes place on the same $4& This is referred to as $4Local& t first glance this sounds like a good thing& =owe+er) the processing re/uires a readof the old N5S,) a modification) and a rewrite& Then) most likely it will e necessary to insertan inde. row into the sutale& =owe+er) if the N5S, already e.ists) Teradata needs to readthe e.isting N5S,) append the new data +alue to it and re*write it ack into the sutale& Thisis why it is important not to create a 4rimary ,nde. or a Secondary ,nde. on data that oftenchanges&

The point of this discussion is simple& ,f secondary indices are used) additional processing isin+ol+ed when the data +alue of the inde. is changed& This is true on an ,NS0RT) a "0L0T0and an 54"T0& So) if a secondary inde. is defined) make sure that the SQL is using it torecei+e the potential access speed enefit& n 064L,N can pro+ide this information& ,f it isnot eing used) drop the inde.&

 s an added note to consider) when using composite secondary indices) the same columncan e included in multiple indices& 2hen this is the case) any data +alue change re/uiresmultiple sutales changes& The result is that the numer of indices in which it is definedmultiplies the pre+ious $4 and sutale*processing o+erhead& Therefore) it ecomes moreimportant to choose columns with a low proaility of change&

Page 264: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 264/401

Chapter 1: ata Interrogation

ata Interrogation

4re+iously in this ook) we e.plored the functionality of the 2=0R0 clause and its aility to

test for a column data +alue was addressed regarding its aility to determine whether or notto return a row& s functional as this is) sometimes it is not powerful enough& 2hen that isthe case) we now ha+e N5LL,-) C3L0SC0 and CS0 !no pun intended% tests&

2hen relational dataases first started appearing e+eryone was impressed with their ailityto use SQL instead of writing a program to get at the desired data& =owe+er) as re/uestsecame more sophisticated and new re/uirements emerged) there came a point in timewhen people thought) ;,f , only had an ,- statement&;

Now SQL contains functions to test the data +alues after a row passes the 2=0R0 test andis read from the disk& These functions not only allow the data to e tested) ut also allow for additional logic to e incorporated into the SQL& This logic pro+ides many options regardingthe processing of data efore it is returned to the client& These options are e.plored in thischapter&

$any of the data interrogation functions may e used in either the column name list as wellas the 2=0R0 clause& 4rimarily) these functions are used after the 2=0R0 clause testsdetermine that the row is needed for the processing of one or more columns&

The Student tale elow is used to demonstrate the functionality of these functions:

%igure 0@10 

N'LLI%E"$

Compatiility: Teradata 0.tension

The Teradata dataase software) for many years) has pro+ided the user the aility to test for ero using the original N5LL,-Z0R3 function& The purpose of this function was to compare

the data +alue in a column for a ero and when found) con+ert the ero) for the life of theSQL statement) to a N5LL +alue&

The following synta. shows two different uses of the N5LL,-Z0R3 function) first on acolumn and then within an aggregate:

S0L0CT N5LL,-Z0R3! Kcolumn*name %

  )Kggregate ! N5LL,-Z0R3!Kcolumn*name % %

-R3$ Ktale*name

Page 265: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 265/401

IR354 # 1H

The ne.t S0L0CT uses literal +alues to demonstrate the functionality of the N5LL,-Z0R3:

S0L0CT N5LL,-Z0R3!9% S Col1

  )N5LL,-Z0R3!N5LL% S Col8

  )N5LL,-Z0R3!% S ColH

1 Row Returned

Col0 Col9 Col@

,n the ao+e SQL and its output:Col1 the +alue 9 is e/ual to 9) so a N5LL is returned&

Col8) the N5LL is not e/ual to 9) so the N5LL is returned&Col) the is not e/ual to 9) so the is returned&

The ne.t S0L0CT shows what happens when a ero ends up in the denominator of adi+ision re/uest and then) how to a+oid it using the N5LL,-Z0R3 in di+ision:

S0L0CT ClassWcode

  )IradeWpt F !IradeWpt G 8 %

-R3$ StudentWtale

3R"0R # 1)8 H

GGG 8E1A "i+ision y Zero 0rror 

To fi. the 8E1A error) this ne.t techni/ue might e used:

S0L0CT ClassWcode  )IradeWpt F ! N5LL,-Z0R3!IradeWpt% G 8 %

-R3$ StudentWtale

3R"0R # 1)8 H

19 Rows Returned

Class7code (8rade7Pt#(NullI,ero(8rade7Pt)59))

-R

-R &9-R &9

@R &9

@R &9

S3 &9

S3 &9

Page 266: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 266/401

Class7code (8rade7Pt#(NullI,ero(8rade7Pt)59))

SR &9

SR &9

This can e a lifesa+er when a ero will cause an incorrect result or cause the SQLstatement to terminate in an error such as di+iding y ero& Therefore) it is common to useN5LL,-Z0R3 for the di+isor when doing a di+ision operation&

 lthough di+iding y N5LL returns a N5LL) the SQL continues to e.ecute and returns all the+alues for rows containing good data& t the same time) it also helps to identify the row or rows that need to e fi.ed&

The ne.t two e.amples show a different answer when the N5LL,-Z0R3 function is usedinside an aggregate function to eliminate the Z0R3:

-irst without N5LL,-Z0R3:

S0L0CT ClassWcode

  ) <I!IradeWpt%

-R3$ StudentWtale

IR354 # 1

3R"0R # 8H

Rows Returned

Class7code A<erage(8rade7Pt)

&99

-R 8&8A

S3 8&A9

@R 8&A8

SR &1B

Then with N5LL,-Z0R3:

S0L0CT ClassWcode

  )<I!N5LL,-Z0R3!IradeWpt% %

-R3$ StudentWtale

IR354 # 1

3R"0R # 8 H

Rows Returned

Class7code A<erage(NullI,ero(8rade7Pt))

S3 8&A9

@R 8&A8

Page 267: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 267/401

Class7code A<erage(NullI,ero(8rade7Pt))

SR &1B

-R &77

 s seen in the ao+e answer sets) the ero I4 +alue came out as is in the first one& Then)the N5LL,-Z0R3 con+erts it to a N5LL in the second with -R eing higher&

N'LLI%

Compatiility: NS,

 s handy as N5LL,-Z0R3 is) it only con+erts a ero to a N5LL& Like its predecessor) thenewer NS, standard N5LL,- function also can con+ert a ero to a N5LL& =owe+er) it cancon+ert anything to a N5LL& To use the N5LL,-) the SQL must pass the name of the columnto compare and the +alue to compare for e/ual&

The following is the synta. for using the N5LL,- function&

S0L0CT N5LL,-!Kcolumn*name) K+alue %

  )Kggregate!N5LL,-!Kcolumn*name) K+alue % %

-R3$ Ktale*name

IR354 # 1

H

To show the operation of the N5LL,-) literal +alues are shown in the ne.t e.ample:

S0L0CT N5LL,-!9) 9% S Col1

  )N5LL,-!9) % S Col8

  )N5LL,-!) 9% S Col

  )N5LL,-!) % S Col7

  )N5LL,-!N5LL) % S Col H

1 Row Returned

Col0 Col9 Col@ Col ColD

9

,n the ao+e SQL and its output:Col1 the +alue 9 was e/ual to 9) so a N5LL is returned&

Col8) the 9 is not e/ual to a ) so the 9 is returned&Col) the is not e/ual to 9) so the is returned&Col7) the is e/ual to ) so a N5LL is returned&Col) the N5LL is not e/ual to 9) so the N5LL is returned&

Like the N5LL,-Z0R3 the N5LL,- is great for situations when the SQL is doing di+ision andaggregation& ,f a need arises to eliminate a ero or any specific +alue from the aggregation)the N5LL,- can con+ert that +alue to a N5LL& 0arlier we discussed aggregates and the factthat they do ignore a N5LL +alue&

Page 268: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 268/401

 n e.ample of using the N5LL,- in di+ision and aggregation follows:

S0L0CT IradeWpt F !IradeWpt G 8 %

  ) <I!N5LL,-!IradeWpt)9% %

-R3$ StudentWtale

IR354 # 1 H

GGG 8E1A "i+ision y Zero 0rror 

2ithout the N5LL,-) we get an error& 2hy

The reason is that the grade point +alue is multiplied y 8 with the result eing ero& Theprolem occurs when the grade point is di+ided y 9 and the SQL aorts with a 8E1A error condition&

,n the ne.t e.ample) the N5LL,- is added to the denominator of the first column to fi. thedi+ision error:

S0L0CT IradeWpt F !! N5LL,-!IradeWpt) 9%% G 8 %

  ) <I!N5LL,-!IradeWpt) 9% %

-R3$ StudentWtale

IR354 # 1H

8 Rows Returned

(8rade7Pt#(3CA&Ee.pression459))

A<erage(3CA&Ee.pression4)

&9 &11

There are two items to notice from this answer set& -irst) the 9 in IradeWpt is con+erted to aN5LL and the 8E1A error disappears& Ne.t) the N5LL +alue is multiplied y 8 with a result of N5LL& Then) the +alue stored in IradeWpt is di+ided y a N5LL and of course) the result is aN5LL& nytime a +alue is di+ided y itself times 8) & is the result& Therefore) all +alid data+alues are comined in the output& The only other row!s% are those with a ero in the gradepoint column&

The second thing aout the output is the heading& Notice that oth headings contain theword CS0& Later in this chapter CS0 is shown as a techni/ue to test +alues& Now it isseen that the N5LL,- and C3L0SC0 oth use CS0 for their tests& Now that this isknown) it also means that using alias or T,TL0 is proaly a good idea to dress up theoutput&

The good news is that the N5LL,- allows the SQL to complete and show +alues for all rows

that do not contain a ero in the column used for di+ision& These ero +alues proaly needto e fi.ed in the long term&

-or the second column in this S0L0CT) whene+er IradeWpt contains a ero) it is con+ertedto a N5LL& The resulting N5LL is passed to the <I function and promptly ignored&Therefore) the resulting a+erage will e a higher numer than if the ero is allowed toecome part of the o+erall a+erage&

Page 269: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 269/401

E"$I%N'LL

Compatiility: Teradata 0.tension

The original Teradata dataase software also allowed the user to compare for a N5LL +alue&0arlier in this ook we saw ,S N5LL and ,S N3T N5LL used within the 2=0R0 clause& n

additional test is a+ailale with the Z0R3,-N5LL function&

The purpose of this function is to compare the data +alue in a column and when it contains aN5LL) transform it) for the life of the SQL statement) to a ero&

The synta. for the Z0R3,-N5LL follows:

S0L0CT Z0R3,-N5LL!Kcolumn*name %

  )Kggregate ! Z0R3,-N5LL!Kcolumn*name % %

-R3$ Ktale*name

IR354 # 1

H

=ere) literals are used to demonstrate the operation of the Z0R3,-N5LL function:

S0L0CT Z0R3,-N5LL!9% S Col1

  )Z0R3,-N5LL!N5LL% S Col8

  )Z0R3,-N5LL!% S Col H

1 Row Returned

Col0 Col9 Col@

9 9

,n the ao+e SQL and its output:Col1 the +alue 9 is not a N5LL) so the 9 is returned&Col8) the N5LL is a N5LL) so a 9 is returned&Col) the is not a N5LL) so the is returned&

The est use of the Z0R3,-N5LL is in a mathematics formula& ,n an earlier chapter it wasseen that anytime a N5LL is used in math) the answer is a N5LL& Therefore) theZ0R3,-N5LL can con+ert a N5LL to a ero so that an answer is returned&

The ne.t S0L0CT shows what happens when a ero ends up in the calculation and then)how to a+oid it using the Z0R3,-N5LL:

S0L0CT ClassWcode

  )IradeWpt G 8

-R3$ StudentWtale

2=0R0 ClassWcode N3T L,J0 'SU'

3R"0R # 1)8 H

Rows Returned

Page 270: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 270/401

Class7code (8rade7Pt59)

-R &99

-R &DE

-R B&99@R &B9

@R D&A9

To fi. the prolem of the N5LL appearing:

S0L0CT ClassWcode

  )Z0R3,-N5LL!IradeWpt% G 8 S <II4

-R3$ StudentWtale

3R"0R # 8 H

19 Rows Returned

Class7code A88PA

9&99

-R 9&99

@R &B9

S3 7&99

-R &DE

SR E&99

SR E&D9

S3 D&E9

@R D&A9

-R B&99

The following are the same e.amples seen earlier in this chapter for N5LL,-Z0R3& They areused here to show the contrast:

S0L0CT ClassWcode

  ) <I(E"$I%N'LL(8rade7pt) )

-R3$ StudentWtale

IR354 # 1

3R"0R # 1H

Rows Returned

Class7code A<erage(eroI,Null(8rade7Pt))

9&99

-R 8&8A

Page 271: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 271/401

Class7code A<erage(eroI,Null(8rade7Pt))

@R 8&A8

S3 8&A9

SR &1B

Then again with an alias on the Z0R3,-N5LL:

S0L0CT ClassWcode

  ) <I!Z0R3,-N5LL!IradeWpt% % S <II4

-R3$ StudentWtale

IR354 # 1

3R"0R # 1H

Rows Returned

Class7code A88PA

&99

-R 8&8A

@R 8&A8

S3 8&A9

SR &1B

C$ALE&CE

Compatiility: NS,

 s helpful as the Z0R3,-N5LL is) it only con+erts a N5LL into a ero& The newer NS,standard C3L0SC0 can also con+ert a N5LL to a ero& =owe+er) it can con+ert a N5LL+alue to any data +alue as well& The C3L0SC0 searches a +alue list) ranging from one tomany +alues) and returns the first Non*N5LL +alue it finds& t the same time) it returns aN5LL if all +alues in the list are N5LL&

To use the C3L0SC0) the SQL must pass the name of a column to the function& The datain the column is then compared for a N5LL& lthough one column name is all that isre/uired) normally more than one column is normally passed to it& dditionally) a literal +alue)which is ne+er N5LL) can e returned to pro+ide a default +alue if all of the pre+ious column+alues are N5LL&

2hereas N5LL,- works with two parameters and compares a column with a +alue passed toit) the C3L0SC0 can e.amine many +alues and continues to check each data +alue until itfinds one that is not a N5LL and that +alue is returned&

=owe+er) if all the +alues passed to the function are N5LL) it has no choice and can onlyreturn a N5LL& The +alues passed to the C3L0SC0 function can e +ia column names or a literal +alue&

The synta. for the C3L0SC0 follows:

Page 272: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 272/401

S0L0CT C3L0SC0 !Kcolumn*list )Kliteral O %

  )Kggregate! C3L0SC0!Kcolumn*list)KliteralO % %

-R3$ Ktale*name

IR354 # 1 H

,n the ao+e synta. the Kcolumn*list is a list of columns& ,t is written as a series of columnnames separated y commas&

S0L0CT C3L0SC0!N5LL)9% S Col1

  )C3L0SC0!N5LL)N5LL)N5LL% S Col8

  )C3L0SC0!% S Col

  )C3L0SC0!'')% S Col7 H

1 Row Returned

Col0 Col9 Col@ Col

9

,n the ao+e SQL and its output:Col1 the first +alue is a N5LL) so the 9 is checked& Since it is not a N5LL) 9 is

returned&Col8) the first +alue is a N5LL) the second and third +alues are also N5LL& Since

all +alues are N5LL) there is no alternati+e) a N5LL is returned&Col) the is not a N5LL) so the is returned& ,t will ne+er make sense to use a

single column ecause the result is e.actly the same as selecting the column& lways use a minimum of two +alues with the C3L0SC0&

Col7) is an interesting case& Since oth ha+e a +alue) the first +alue ]^ is returnedand the is ne+er displayed& This means that when coding a C3L0SC0)ne+er place the literal first) it should always e last if used& 3therwise) the datain suse/uent column names will ne+er e checked& The columns should

always precede a literal&

Like the Z0R3,-N5LL) one of the est uses for the C3L0SC0 is in a mathematicsformula& ,n an earlier chapter it was seen that anytime a N5LL is used in math) the answer isa N5LL& Therefore) the C3L0SC0 can con+ert a N5LL to a ero so that an answer isreturned&

The ne.t S0L0CT displays the student's last name and I4& =owe+er) if there is no I4) itincludes the phrase ;$issing I4; in the output using the C3L0SC0 to search Iradepoints for a N5LL:

S0L0CT LastWname

  )C3L0SC0!ClassWcode) '$issing Class'% S ClassWcode

-R3$ StudentWtale3R"0R # 8) LastWnameH

19 Rows Returned

Last7Name Class7code

=anson -R

Page 273: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 273/401

Last7Name Class7code

Larkins -R

Thomas -R

#ond @R$cRoerts @R

@ohnson $,SS,NICLSS

Smith S3

2ilson S3

"elaney SR

4hillips SR

The ne.t e.ample uses asically the same S0L0CT as ao+e) ut adds a second column to

the column list of the C3L0SC0&S0L0CT LastWname

  )C$ALE&CE(Class7codeJ %irst7nameJ KBoth MissingK)

  S ClasscodeWorW-irstnameW,fN5LL

-R3$ StudentWtale

2=0R0 ClassWcode M 'SR' or ClassWcode ,S N5LL

3R"0R # LastWname H

Rows Returned

Last7Name Classcode7or7%irstname7I,N'LL

"elaney SR

@ohnson Stanley

4hillips SR

,n this e.ample) 8 columns and a literal are used in the C3L0SC0& Since @ohnson had afirst name) the literal is not displayed& ,t is there as an insurance policy in case oth columnscontained N5LL& C$ALE&CE is a great tool any time there is a need to display a singlecolumn and insure that missing data is replaced ith a su!stitute <alue

CA&E

Compatiility: NS,

The CS0 function pro+ides an additional le+el of data testing after a row is accepted y the2=0R0 clause& The additional test allows for multiple comparisons on multiple columns withmultiple outcomes& ,t also incorporates logic to handle a situation in which none of the +aluescompares e/ual&

Page 274: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 274/401

2hen using CS0) each row retrie+ed is e+aluated once y e+ery CS0 function&Therefore) if two CS0 operations are in the same SQL statement) each row has a columnchecked twice) or two different +alues each checked one time&

The asic synta. of the CS0 follows:

CS0 Kcolumn*name

  2=0N K+alue1 T=0N Ktrue*result1

  2=0N K+alue8 T=0N Ktrue*result8

  2=0N K+alueN T=0N Ktrue*resultN

  0LS0 Kfalse*result O

0N"

The ao+e synta. shows that multiple 2=0N tests can e made within each CS0& Thedata +alue test continues from the first 2=0N to the last 2=0N or until it finds an e/ualcondition& t that point) it does the T=0N and e.its the CS0 logic y going directly to the0N"& ,f the CS0 checks all +alues and does not find an e/ual condition in any of the2=0N tests) it does the optional 0LS0 logic and then proceeds to the 0N"&

The 0LS0 portion of the CS0 statement is the only component that is optional& ,f there isno 0LS0 and no e/ual conditions in the 2=0N tests) it falls through to the 0N" withoutdoing anything&

,t is a common practice to use the 0LS0 for the aility to pro+ide an alternate +alue when thecondition does not e.ist in any of the 2=0N comparisons& +ariation of this asic format isto use a literal +alue following the CS0 and use column names in the 2=0N&

%igure 0@19 

This S0L0CT uses the Course tale to show the asic CS0 operation:

S0L0CT CourseWName

  )CA&E Credits

  :;EN 0 T;EN K0 CreditK

  :;EN 9 T;EN K9 CreditsK

  :;EN @ T;EN K@ CreditsK

  EL&E KMore than @ CreditsK

  EN ;Numer of Credits;

-R3$ CourseWtale

3R"0R # credits) 1H

D Rows Returned

Page 275: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 275/401

Course7name Num!er  o, Credits

Logical

"ataase"esign

8 Credits

<8R SQL-eatures

8 Credits

 d+anced SQL Credits

,ntroduction toSQL

Credits

TeradataConcepts

Credits

"ataase dministration

$orethan

Credits

4hysical"ataase"esign

$orethan Credits

The ao+e answer set demonstrates three things& -irst) the CS0 does a comparison on anumeric data +alue called Credits with a numeric literal and returns a character string& TheS0L0CT may return numers or character strings) regardless of their source&

Second) the output is sorted on the credits column and not the KCS0 e.pression displaycolumn& Therefore) the se/uence will not change e+en if the words in the literal change inthe SQL statement&

Lastly) the heading is not the phrase KCS0 e.pression ecause of the alias ;Numer of Credits;& ,t is ad+isale to either alias or T,TL0 on columns with CS0 e.pressions&

The ao+e synta. is great for comparing e/ual conditions& =owe+er) we do not li+e in aperfect world and sometimes it is necessary to compare for une/ual conditions&

%le.i!le Comparisons ithin CA&E

2hen it is necessary to compare more than (ust e/ual conditions within the CS0) theformat is modified slightly to handle the comparison& $any people prefer to use the followingformat ecause it is more fle.ile and can compare ine/ualities as well as e/ualities&

This is a more fle.ile form of the CS0 synta. and allows for ine/uality tests:

CS0

  2=0N Kcondition*test1 T=0N Ktrue*result1

  2=0N Kcondition*test8 T=0N Ktrue*result8

  2=0N Kcondition*testN T=0N Ktrue*resultN

  0LS0 Kfalse*result O

0N"

Page 276: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 276/401

The ao+e synta. shows that multiple tests can e made within each CS0& The +aluestored in the column continues to e tested until it finds a true condition& t that point) it doesthe T=0N portion and e.its the CS0 logic y going directly to the 0N"&

,f the CS0 tests the +alue and does not find a true condition in any of the 2=0N checks) itcan do the 0LS0 portion of the logic and then proceed to the 0N"& ,f there is no 0LS0) itfalls to the 0N" without doing anything to the data& s a result) if this is a selected column) anull is returned& 2orse yet) if this is in the S0T portion of an 54"T0 statement) the columnis set to a null&

Rememer that the 0LS0 portion of the CS0 statement is optional& ,t can work without it)howe+er) it is common to use that aility to ha+e an alternate +alue if the condition does note.ist in any 2=0N comparisons&

The ne.t S0L0CT is similar to the pre+ious e.ample and also demonstrates that you couldcompare for a numeric data +alue with a numeric literal and then return a character literal&The primary difference is that it uses the comparisons inside the 2=0N and an 0LS0 for thedefault literal:

S0L0CT CourseWName

  ) CS0  2=0N credits M 1 T=0N '1 Credit'

  2=0N credits M 8 T=0N '8 Credits'

  2=0N credits M T=0N ' Credits'

  0LS0 '$ore than Credits'

  0N" S NumerWofWCredits

-R3$ CourseWtale

3R"0R # credits) 1H

D Rows Returned

Course7name Num!er7o,7Credits

Logical"ataase"esign

8 Credits

<8R SQL-eatures

8 Credits

 d+anced SQL Credits

,ntroduction toSQL

Credits

TeradataConcepts

Credits

"ataase dministration

$ore than Credits

4hysical"ataase"esign

$ore than Credits

Page 277: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 277/401

#oth of the pre+ious CS0 statements used an e/ual comparison& ,n reality) when e/ualconditions are desired) the first form of the CS0 is shorter to write) ut not as fle.ile& Thesecond format could easily e modified to check for ine/ualities and allows multiple columnsto e tested in the same CS0&

Comparison $perators ithin CA&E

,n this section) we will in+estigate adding more power to the CS0 statement& ,n the ao+ee.amples) a literal +alue was returned& ,n most cases) it is necessary to return data& Thereturned +alue can come from a column name (ust like any selected column or amathematical operation&

 dditionally) the ao+e e.amples used a literal ]M^ as the comparison operator& The CS0comparisons also allow the use of ,N) #0T200N) N5LL,- and C3L0SC0& ,n reality) the#0T200N is a compound comparison& ,t checks for +alues that are greater than or e/ual tothe first numer and less than or e/ual to the second numer&

The ne.t e.ample uses oth formats of the CS0 in a single S0L0CT with each oneproducing a column display& ,t also uses S to estalish an alias after the 0N":

S0L0CT CA&E :;EN 8rade7pt I& N'LL T;EN K8rade Point 'n+nonK

  :;EN 8rade7pt IN (0J9J@) T;EN KInteger 8PAK

  :;EN 8rade7pt BET:EEN 0 AN 9 T;EN KLo ecimal <alueK

  :;EN 8rade7pt 3 @HH T;EN K;igh ecimal <alueK

  EL&E K6 8PAK

  EN S IradeW4ointW+erage

  )CA&E Class7code

  :;EN K%"K T;EN K%reshmanK

  :;EN K&$K T;EN K&ophomoreK

  :;EN KS"K T;EN KSuniorK  :;EN K&"K T;EN K&eniorK

  EL&E K'n+non ClassK

  EN S ClassW"escription

-R3$ StudentWtale

3R"0R # ClassWcode H

19 Rows Returned

8rade7Point7A<erage Class7escription

Irade 4oint 5nknown 5nknown Class

7&9 I4 -reshman

=igh "ecimal +alue -reshman

=igh "ecimal +alue -reshman

Low "ecimal +alue @unior  

=igh "ecimal +alue @unior  

=igh "ecimal +alue Sophomore

Page 278: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 278/401

8rade7Point7A<erage Class7escription

,nteger I4 Sophomore

,nteger I4 Senior  

=igh "ecimal +alue Senior  

  word of caution is warranted here& Since the CS0 stops comparing when it finds a truecondition and ine/ualities are eing used) it is important to se/uence the comparisonscarefully& The ao+e CS0 tests for IradeWpt ,N !1)8)% first& ,f the data is e.actly one of these +alues) the T=0N portion is used and the CS0 is finished& Therefore) only decimal+alues and the 7&9 gets through all the suse/uent 2=0N tests&

3nce all the decimal +alue possiilities ha+e een eliminated in the two other 2=0N tests)the only +alue left is 7&9& That is where the 0LS0 comes in automatically without re/uiring anadditional test&

2hen , first saw an ,N comparison with the CS0 statement) , got +ery e.cited ecause an,N comparison is often seen with a su/uery& =owe+er) , soon realied that su/ueries are

only located in the 2=0R0 clause& Currently) su/ueries cannot e used in a CS0statement&

CA&E ,or ;oriXontal "eporting

 nother interesting usage for the CS0 is to perform horiontal reporting& Normally) SQLdoes +ertical reporting& This means that e+ery row returned is shown on the ne.t output lineof the report as a separate line& =oriontal reporting shows the output of all informationre/uested on one line as columns instead of +ertically as rows&

4re+iously) we discussed aggregation& ,t eliminates detail data and outputs only one line or one line per uni/ue +alue in the non*aggregate column!s% when utiliing the IR354 #&That is how +ertical reporting works) one output line elow the pre+ious& =oriontal reportingshows the ne.t +alue on the same line as the ne.t column) instead of the ne.t line&

5sing the normal S0L0CT structure we return one row per uni/ue +alue in the +erticalformat for the column named in the IR354 #) the report appears as:

Class7code A<erage78PA

-R &77

S3 8&A9

@R 8&A8

SR &1B

5sing the ne.t S0L0CT statement) we achie+e the same information in a horiontalreporting format y making each +alue a column:

S0L0CT <I!CA&E Class7code

  :;EN K%"K T;EN 8rade7pt

  EL&E N'LL EN% !format 'Z&ZZ'% S -reshmanWI4

  )<I!CA&E Class7code

  :;EN K&$K T;EN 8rade7pt

Page 279: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 279/401

  EL&E N'LL EN% !format 'Z&ZZ'% S SophomoreWI4

  )<I!CA&E Class7code

  :;EN KS"K T;EN 8rade7pt

  EL&E N'LL EN% !format 'Z&ZZ'% S @uniorWI4

  )<I!CA&E Class7code

  :;EN K&"K T;EN 8rade7pt

  EL&E N'LL EN% !format 'Z&ZZ'% S SeniorWI4

-R3$ StudentWTale

2=0R0 ClassWcode ,S N3T N5LL H

1 Row Returned

%reshman78PA &ophomore78PA Sunior78PA &enior78PA

8&8A 8&A9 8&A8 &1B

2hen using horiontal reporting) it is important that the column heading in the report indicatewhat the data represents& Normally) one of the selected columns identifies the origin of thedata eing reported in the +ertical format& To accomplish this type of reporting) the numer of the columns and the desired +alues must e known ahead of time& Therefore) it is not asfle.ile as the normal SQL statement&

The 2=0R0 clause in the pre+ious e.ample is not re/uired since the CS0 will eliminatethe N5LL for missing class codes& lso) y using the 2=0R0) the N5LL is not compared 7times with each test producing an unknown result& s it is) e+ery ]-R^ row is compared 1time) e+ery ]S3^ row is compared 8 times) e+ery ]@R^ row is compared times and e+ery ]SR^row is compared 7 times& 0+ery comparison takes time&

Therefore) it is est to eliminate as many comparisons as possile y eliminating the row inthe 2=0R0 clause& Likewise) if there are more seniors than freshmen) it is faster to

compare the ]SR^ first& This way) instead of testing each senior 7 times) they are onlycompared once& s a result) the CS0 checks fewer +alues and the entire S0L0CT wille.ecute much faster&

 lways think aout the impact on performance when using special SQL features and look for opportunities to reduce comparisons& Rememer) the tests are performed from the first2=0N through the last 2=0N or until a true result is found&

Nested CA&E E.pressions

 fter ecoming comfortale with the pre+ious e.amples of the CS0) it may ecomeapparent that a single check on a column is not sufficient for more complicated re/uests&2hen that is the situation) one CS0 can e imedded within another& This is called nestedCS0 statements&

The CS0 may e nested to check data in a second column in a second CS0 eforedetermining what +alue to return& ,t is common to ha+e more than one CS0 in a single SQLstatement& =owe+er) it is powerful enough to ha+e a CS0 statement within a CS0statement&

So that the system can tell where each CS0 starts and ends) the nested CS0 statementsmust e imedded in parentheses and each CS0 must ha+e its own 0N"& The sie of the

Page 280: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 280/401

SQL statement is more of the limiting factor than is the numer of CS0 statements in aS0L0CT&

4rior to <8R) the CS0 could only check one column& lthough it is permissile to usedifferent +alues) only one column per CS0 comparison was allowed& To check multiple+alues) multiple CS0 statements were imedded within each other&

The first CS0 tests the first +alue of one column and the nested CS0 normally tests for another +alue of a different column& This is getting into an ad+anced techni/ue and it willproaly re/uire some practice to get it working e.actly as desired&

The ne.t e.ample of nested CS0 statements pro+ides a sample to egin coding your own:

S0L0CT LastWname

  )CA&E ClassWcode 2=0N '@R'

  T=0N '@unior ' !CA&E :;EN 8rade7pt 3 9 T;EN K%ailingK

  :;EN 8rade7pt 3 @D T;EN KPassingK

  EL&E KE.ceedingK EN%

  0LS0 'Senior ' !CA&E :;EN 8rade7pt 3 9 T;EN K%ailingK  :;EN 8rade7pt 3 @D T;EN KPassingK

  EL&E KE.ceedingK EN%

  EN S CurrentWStatus

-R3$ StudentWTale

2=0R0 ClassWcode ,N !'@R')'SR'%

3R"0R # classWcode) lastWnameH

7 Rows Returned

Last7name Current7&tatus 7 

#ond @unior  0.ceeding

$cRoerts @unior -ailing

"elaney Senior 4assing

4hillips Senior 4assing

The ao+e nested CS0 first compares the class code using the e/uality*checking format&Then) when the class code is e/ual to ]@R^) it starts the literal with ]@unior ]& Then it egins thenested CS0 to test the grade point a+erage& ,f the row is not for a (unior it knows it must ea senior ecause the 2=0R0 clause selects only (uniors and seniors& ,t immediately tests

the seniors I4 to finish the output literal&

-or oth (uniors and seniors) the nested CS0 tests the I4 compared to the literal +alue of 8) meaning that they are not doing well in school& ,f it is greater than 8) the +alue is thencompared against && 2hen it is less than &) this means it is also greater than or e/ual to8 since these rows failed the first test& These are passing grades& The only rows left are theones containing a I4 greater than & that represent students doing +ery well in school&

Page 281: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 281/401

There are two reasons why the 2=0R0 clause is +ery important here& -irst) it speeds up theS0L0CT y eliminating all rows e.cept (uniors and seniors& Second and more importantly)without the 2=0R0) all students who are not (uniors are assumed to e seniors&

Since there are freshman and sophomores) this is a ad thing and the CS0 re/uireschanges to make it correct& Since oth the CS0 and the 2=0R0 pro+ide testing) they cane written to work together and compliment each other& 2ith the ad+ent of <8R) the need toimed nested CS0 statements has een reduced) ut not eliminated&

The ne.t CS0 is e/ui+alent to the one ao+e without using nesting:

S0L0CT LastWname

  )CA&E :;EN class7code ? KS"K AN grade7pt 3 9

  T;EN KSunior %ailingK

  :;EN class7code ? KS"K AN grade7pt 3 @D

  T;EN KSunior PassingK

  :;EN class7code ? KS"K

  T;EN KSunior E.ceedingK

  :;EN class7code ? K&"K AN grade7pt 3 9

  T;EN K&enior %ailingK

  :;EN class7code ? K&"K AN grade7pt 3 @D

  T;EN K&enior PassingK

  EL&E K&enior E.ceedingK

  EN S CurrentWStatus

-R3$ StudentWTale H

2hen comparing the two CS0 statements) these statements are true:

1& ,t takes longer to code without nesting8& ,t takes comparisons to separate (uniors and seniors instead of 8&

Therefore) less efficient than nesting&

$any third*party tools generate this form of CS0) ecause they can create each 2=0Nwithout e+aluating the totality of the processing eing performed&

2hen additional data +alue comparisons are needed after the row has een read) there isnow a powerful tool& The CS0 statement adds ,- functionality to the S0L0CT&

CA&E used ith the other ML

All o, the e.amples ha<e !een using the &ELECT The good nes is that it can !e

used ith all ,our ML statements (&ELECTJ IN&E"TJ 'PATEJ and ELETE) Thismight !e especially help,ul hen using the CA&E ithin an 'PATE &-L statement&

$any times in this chapter) the answer set was sorted y the class code& lthough thisgrouped them +ery well) it also put (uniors ahead of sophomores& So) it has een determinedthat the easiest way to put sophomores first is to add a #T0,NT column to the Studenttale called classWno and store the +alues 1 through 7 to represent the class& This +alue isused y the sort) ut most likely ne+er displayed&

Page 282: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 282/401

Now that the column e.ists within the tale !see "ata "efinition Language Chapter for details%) it needs data& Rememer) when a tale is altered with a new column) it contains aN5LL +alue for all e.isting rows and needs to e populated&

The following 54"T0 statements could e used to accomplish this:

54"T0 StudentWtale set classWno M 1

2=0R0 classWcode M '-R'H

54"T0 StudentWtale set classWno M 8

2=0R0 classWcode M 'S3'H

54"T0 StudentWtale set classWno M

2=0R0 classWcode M '@R'H

54"T0 StudentWtale set classWno M 7

2=0R0 classWcode M 'SR'H

 lthough this techni/ue satisfies the re/uirements) four different 54"T0 statements areneeded& 0ach one locks the tale for 2R,T0& "ue to the 2R,T0 lock) they cannot ee.ecuted concurrently and each one takes time to complete& Therefore) more time is takenaway from the users) or it must e done at night and may interfere with normal atchprocessing&

 s a result) it is est to accomplish this as fast as possile and in a single run if possile&5sing the CS0) it is possile& The ne.t 54"T0 does the same processing as the 7statements ao+e:

54"T0 StudentWtale set classWno M

  CA&E

  :;EN class7code ? K%"K T;EN 0

  :;EN class7code ? K&$K T;EN 9

  :;EN class7code ? KS"K T;EN @

  :;EN class7code ? K&"K T;EN EN =

This approach is faster ecause it only re/uires a single pass through all the rows instead of 7 separate passes& =owe+er) there are always two sides to e+ery story& Since all rows areeing updated at once) the Transient @ournal must ha+e enough space in "#C to store all of the efore images& 2ith the four different statements) the Transient @ournal should re/uireless space for each of the indi+idual statements& The total space used is the same) ut it isused at different times& ,f space is an issue on a system) the choice may not e ased solelyon efficiency& This is proaly an indicator that more disk space needs to e added to thesystem&

'sing CA&E to a<oid a Roin

 nother trick associated with the CS0 is the aility to a+oid a costly (oin for a small numer of +alues& -or instance) the CS0 could e used to test the department numer and returnthe department name instead of doing a (oin&

Page 283: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 283/401

Chapter 17: ie Processing

ies

Compatiility: NS,

  <iew is a S0L0CT statement that is stored in the "ata "ictionary !""%& ,t is sometimesreferred to as a +irtual tale ecause a +iew is used e.actly like a tale with columns androws& <iews are used to pro+ide customied access to data tales for the purpose of restricting the numer of columns) to deri+e columns) to comine columns from multiple datatales !(oin%) to restrict the numer of rows returned from one or more data tales) to simplifySQL creation or isolate the actual tale from the user&

Restricting access to columns from one or more data tales is normally done for reasons of security& ,f the +iew does not select a column) it is not a+ailale to the user& #y creating a+iew to e.plicitly re/uest the desired column names from the data tale!s% and omitting therestricted columns) it looks as though the columns do not e.ist& Therefore) they are securefrom the users' restricted access to columns through the +iew&

To restrict rows from user access) the +iew can e written to disallow access to rows yusing a 2=0R0 clause in the stored S0L0CT& The 2=0R0 clause limits the rows returnedto the user y re(ecting all rows that do not meet the stated criteria&

"easons to 'se ies

,f SQL were the only tool a+ailale for a site) +iews would e strongly recommended& Then)any user can e taught to code a simple ;S0L0CT G -R3$ <iewname; without ha+ing topossess more in depth SQL e.pertise& ll the sophisticated SQL would e stored in a +arietyof +iews&

 nother factor is that some 7IL languages are not written to perform all the newer more

sophisticated functions a+ailale in SQL& +iew can pro+ide these functions and the 7ILcan simply access the +iew as a +irtual tale&

Another poer,ul ,unctionality ithin <ies is the use o, aggregates & Since data martsoften in+ol+e summary tales) +iews can e used to uild a logical data mart& 2hen this isdone within Teradata) no data mo+ement or e.tra storage space is re/uired on a separatesystem& ,nstead) all summary ;+irtual tales; are created dynamically using +iews when theyare needed&

<iews also pro+ide insulation etween the users and the actual data tales& #ecause <iewsare stored in the "") they re/uire no 4ermanent space in a user's dataase&

Therefore) they can e tailored to the needs of specific users or organiations withoutdirectly impacting the actual data tale&

Considerations ,or Creating ies

2hen creating a +iew) there are certain considerations that must e taken into account& ,nTeradata) a +iew may not contain:

 n 3R"0R # Y rows are not ordered in a tale) nor in a +iew

,ndices Y howe+er) any inde. on underlying tales may e used Column names must use +alid characters

Page 284: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 284/401

o  ggregates must e assigned an alias due to ! %o "eri+ed data with mathematics symols must ha+e an alias

Creating and 'sing IE:&

<iews are created using a special form of "ata "efinition Language !""L%& The CR0T0re/uests a new <,02) pro+ides the name and the S0L0CT for the +iew& ,t is suggested thatthe name of the +iew either start with ;+W; or end with ;W+; to identify it as a +iew name!check your site standards%& That way) it is +isily o+ious to people that this is a +iew andnot a tale& The name of the +iew must e uni/ue from the names of other o(ects in thedataase& The CR0T0 <,02 +erifies that the name does not already e.ist and return anerror if it does&

The rest of the statement is the S0L0CT statement re/uired to return the desired columnsand rows& The synta. for creating a +iew follows:

C"EATE IE: K+iew*name ! Kalias*name) Kalias*name) &&& % O S

  S0L0CT Kcolumn*name S Kalias*name O

  ) Kcolumn*name S Kalias*name O O

  ) Kcolumn*name S Kalias*name O O

  -R3$ Ktale*name

  2=0R0 Kconditional*tests O

2,T= C=0CJ 34T,3N O

H

3r 

** CR0T0 <,02 may e are+iated as C<

C K+iew*name ! Kalias*name) Kalias*name) &&& % O A&

  S0L0CT Kcolumn*name S Kalias*name O

  ) Kcolumn*name S Kalias*name O O

  ) Kcolumn*name S Kalias*name O O

  -R3$ Ktale*name

  2=0R0 Kconditional*tests O

2,T= C=0CJ 34T,3N O

H

  +iew) if created with ;S0L0CT G -R3$ Ktale*name; reflects the column definitions at thetime the CR0T0 <,02 is e.ecuted& ,f the data tale is altered afterwards) it will not e seenwhen using the +iew definition& Therefore) using this techni/ue is discouraged&

The 0mployee tale is used to demonstrate the use of +iews:

Page 285: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 285/401

%igure 010 

The following creates a +iew to return the employees !ao+e tale% in department 899& ,tlimits the +iew to an employee's numer) last name) and salary& This +iew restricts othcolumns !i&e& firstWname% and rows not for department numer 899:

C"EATE IE: emplW899W+

  S S0L0CT employeeWno S Emp7No  )lastWname S Last

  )salaryF18 !format '[[[[)[[A&AA'%

  S Monthly7&alary

  -R3$ employeeWtale

  2=0R0 deptWno M 899 H

The ne.t S0L0CT can e used to return all the columns and rows from this <,02:

S0L0CT G

-R3$ emplW899W+ H

Emp7No Last 7 Monthly7&alary

187ED Coffing [)7A9&D7

177 Smith [7)999&99

This ao+e +iew contains alias names for all the columns using the S to define the alias inthe S0L0CT& The +iew was created using them and they ecome the column names of the+iew& =owe+er) if the original S0L0CT does not contain alias names and they are needed inthe +iew) alias names may e assigned as part of the CR0T0 <,02&

The following creates the same +iew as ao+e) howe+er) it estalishes the alias using thisother techni/ue:

C"EATE IE: emplW899W+ !Emp7N!rJ LastJ Monthly7&alary%

  S S0L0CT employeeWnr 

  )lastWname

  )salary !format '[[[[)[[A&AA'%

  -R3$ employeeWtale

  2=0R0 departmentWnr M 899 H

Page 286: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 286/401

5sing this second techni/ue) if one alias is estalished in the parentheses) all columns muste represented with an alias column name& The order of the name needs to respecti+elymatch the se/uence of the columns in the S0L0CT list& ,f the S0L0CT contains an alias) thistechni/ue o+er*rides it using the name in parentheses&

,t is a common practice to use +iews for the purpose of accomplishing a (oin& The lengthyand sometimes complicated (oin code and conditions are made easier and automatic whenthey are stored in a +iew& #y simply selecting from the +iew name) the (oin is automaticallyperformed and the appropriate columns and rows are returned& +iew does not store thedata separatelyH only the S0L0CT is stored&

These two tales are used in the following e.amples:

%igure 019 

%igure 01@ 

The following +iew performs the (oin as part of its processing whene+er a user does aS0L0CT from the +iew:

CR0T0 <,02 CustomerW3rderW+ S

S0L0CT CustomerWname S Customer   )3rderWnumer 

  )3rderWtotal !-3R$T '[[[)[[A&AA' % S TotalWmount

-R3$ CustomerWtale S cust

  )3rderWtale S ord

2=0R0 cust&customerWnumer M ord&customerWnumer H

The ne.t S0L0CT references the +iew to perform the (oin:

S0L0CT G

-R3$ CustomerW3rderW+

3R"0R # 1H

Rows Returned

Customer7 $rder7num!er $rder7total

 C0Consulting

188 [)111&7D

#illy's #est 187E [18)7D&

Page 287: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 287/401

Customer7 $rder7num!er $rder7total

Choice

#illy's #estChoice

1818 [B)99&A1

"ataasesN*5

18B [1)81&E8

6Z4luming

18DDD [8)77&B7

Notice that all alias names and formatting defined in the +iew ecome the default for the+irtual tale& Now that there is a +iew) it can e in+ol+ed in another (oin as a tale& s aresult) there may e a *tale (oin e.ecuted as two 8*tale (oins using the +iew& <irtually) a+iew is a tale&

 nother common use for +iews is to summarie data& ,nstead of creating an actual tale andstoring the data twice) many times Teradata is powerful enough to do all the aggregation

within a +iew&

The following creates a +iew to perform the aggregation of all orders placed y e+erycustomer for each month:

CR0T0 <,02 ggregW3rderW+ S

S0L0CT CustomerWNumer 

  )3rderW"ateF199X1A9999 !format 'AAAA*AA'% S rW$thW3rders

  )C35NT!3rderWtotal% S 3rderWCnt

  )S5$!orderWtotal% S 3rderWSum

  )<I!orderWtotal% S 3rderW+g

-R3$ 3rderWTale

2=0R0 3rderW"ate #0T200N AB9191 and AA181

IR354 # CustomerWNumer) rW$thW3rders H

The +iew can then e used to aggregate the columns that are created as a result of anaggregate) as seen ne.t:

S0L0CT S5$!3rderWSum%

-R3$ ggregW3rderW+ H

1 Row Returned

&'M($rder7&um)

E711&D

3r as a +irtual tale in a (oin:

S0L0CT CustomerWName

  )rW$thW3rders

  )3rderWSum

Page 288: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 288/401

-R3$ CustomerWtale S cust ,NN0R @3,N CustomerW3rderW+ S +

3N cust&customerWnumer M +&customerWnumer 

2=0R0 customerWname L,J0 '#illU' H

8 Rows Returned

Customer7Name Yr7Mth7$rders $rder7&um

#illy's #est Choice 1AAB*9 [18)7D&

#illy's #est Choice 1AAA*19 [B)99&A1

Notice that the +iew contains a 2=0R0 and so does the S0L0CT from the +iew& llconditions within the +iew and the user S0L0CT must e satisfied for the rows to ereturned& Together) the conditions are compared using the N" logical operation& This cane seen using an 064L,N on the S0L0CT from the +iew& lso seen in the 064L,N is theuse of actual tale names) ne+er the +iew name& Therefore) there is no additional processingo+erhead compared to selecting the rows directly out of the tale& t the same time) thisallows companies the option of additional security y not re+ealing to users if the rows are

retrie+ed directly from a tale or through a +iew&

eleting ies

2hen a +iew is no longer needed) it can e deleted& The following synta. may e used:

"R34 <,02 Kdataase*nameK&OK+iew*name

H

,t remo+es the +iew name) column names and S0L0CT from the ""&

Modi,ying ies

  +iew cannot e altered like a tale& ,nstead) the entire +iew !S0L0CT% is replaced usingthe R04LC0 <,02 format of ""L& 5nlike the CR0T0 <,02) the R04LC0 <,02 doesnot +erify that the name is uni/ue& ,nstsead) it anticipates that the +iew e.ists and replaces itwith the new S0L0CT statement& Therefore) it is ad+isale to manually +erify that the correct<,02 is eing replaced&

,t is ad+isale to do a S=32 <,02 to otain the latest +ersion of the +iew& Then) copy andmodify it to replace the current +iew& #esides making it easier than rewriting the ""L) theS=32 <,02 makes it safer and guarantees that nothing is inad+ertently missed from apre+ious R04LC0 <,02 operation&

2hen using the R04LC0 <,02) if the +iew name does not e.ist) an error does not occur&,nstead) the R04LC0 uilds a new +iew the same as using CR0T0 <,02&

The synta. of the R04LC0 <,02 follows:

"EPLACE IE: Kdataase*name&OK+iew*name

  S S0L0CT Kcolumn*name

  )Kcolumn*name O

Page 289: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 289/401

  -R3$ Ktale*name

  2=0R0 Kconditional*tests O

2,T= C=0CJ 34T,3N O

H

The ne.t e.ample changes the ggregW3rderW+ +iew to process only orders for the year 8991:

"EPLACE IE: ggregW3rderW+ S

  S0L0CT CustomerWNumer 

  )3rderW"ateF199X1A9999 !-3R$T 'AAAA*AA'%

  S rW$thW3rders

  )C35NT!3rderWtotal% S 3rderWCnt

  )S5$!orderWtotal% S 3rderWSum

  )<I!orderWtotal% S 3rderW+g

-R3$ 3rderWTale

:;E"E $rder7ate BET:EEN 0606060 and 06009@0

IR354 # CustomerWNumer) rW$thW3rders

H

Notice that the keyword R04LC0 appears instead of the original CR0T0 and the 2=0R0clause is changed from the original CR0T0 <,02 statement&

Modi,ying "os 'sing ies

 lthough +iews are primarily used for retrie+ing rows from one or more tales) they can alsoe used for modifying the rows in a data tale& That's right +iews can 54"T0 tales? Since+iews are ;+irtual tales); users can do anything with a +iew that their pri+ileges allow)including updates& 4ri+ileges work the same on +iews as they do on tales& =ence) theypossess the same aility for row modification) with a few additional rules&

 ll "ata $anipulation Language !"$L% commands !,NS0RT) ,NS0RTFS0L0CT) 54"T0)and "0L0T0% may e used& The only difference is that the name of the +iew and its columnsare used instead of the underlying tale and column names&

ML "estrictions hen using ies

There are a few restrictions that disallow maintenance acti+ity on a +iew with an ,NS0RT)54"T0 or "0L0T0 re/uest& +iew cannot e used for maintenance if it:

4erforms a (oin operation Y more than one tale Selects the same column twice Y wouldn't know which one to use

"eri+es data Y does not undo the math or calculation 4erforms aggregation Y eliminates detail data 5ses 3L4 functions Y data does not e.ist in a column 5ses a ",ST,NCT or IR354 # Y eliminate duplicate rows

Page 290: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 290/401

IN&E"T using ies

  +iew may e used to create new rows within a data tale& Like the update process) an,NS0RT cannot enter data into a column that is not listed in the +iew& lthough this is also aform of security) it can cause operational errors& 2hen a +iew does not reference a column)that column cannot recei+e data using that +iew& Therefore) a N5LL will e stored in all

columns not named in the +iew& ,f one of these columns is declared as N3T N5LL in thedata tale) the ,NS0RT fails&

'PATE or ELETE using ies

  +iew may e used to modify !54"T0% the columns of an e.isting row or remo+e rows!"0L0T0% in a data tale& =owe+er) the 54"T0 cannot change the +alues in columns notspecified in the +iew& Therefore) it is impossile for users to accidentally update data thatthey do not ha+e access to within the +iew) hence increasing security and data integrity&

:IT; C;EC2 $PTI$N

-or a long time) Teradata has allowed +iews to modify data rows& ,n doing this) only the rowsthat the +iew returned were eligile to e updated& Since the incorporation of NS,functionality into Teradata) this is no longer true& NS, indicates that when an 54"T0 or "0L0T0 reference a +iew to modify or delete rows of a tale) all the rows of the tale shoulde eligile& This means that y default) the 2=0R0 clause is ignored&

 lthough this can e a good thing) it may not always e the desired outcome& -or instance) if a user updates a row using its 4,) only the row!s% with that specific +alue is changed&=owe+er) when a non*inde.ed column is used) there is far more likelihood that more thanone row to e updated&

=ere is why: Let's say that it is time to gi+e a raise to an employee& -urthermore) it isdecided to reference the employee's name for the comparison ecause e+ery S0L0CTperformed on the +iew returns only one employee with that name& Rememer) when a

S0L0CT uses a +iew) the internal 2=0R0 clause compares and eliminates rows notmeeting the conditional comparison&

=owe+er) NS, indicates that when the +iew is used for the maintenance) the 2=0R0clause is ignored& The system looks at all rows for potential modifications& ,f there are two or more people with the same last name anywhere in the tale) all of them get the raise&Therefore) a 2=0R0 should e used to constrain the 54"T0) or the 2,T= C=0CJ34T,3N should e specified in the +iew at creation time&

,t is worth mentioning that the 2,T= C=0CJ 34T,3N did not e.ist in pre+ious releases of Teradata& ,n those releases prior to <8R8&9) the 2=0R0 clause conditions were alwaysapplied when an 54"T0 or "0L0T0 was performed through a +iew& ,n all releases since<8R8&9) any 54"T0 or "0L0T0 acti+ity using a +iew) that does not ha+e a 2,T= C=0CJ

34T,3N e.plicitly defined) allows an authoried user to manipulate all rows of a tale) not (ust those seen in a S0L0CT& NCR pro+ided a migration script that added the check optionphrase to e.isting +iews when upgrading to the later releases&

,n Teradata) the additional key phase: 2,T= C=0CJ 34T,3N) indicates that the 2=0R0clause conditions should e applied during the e.ecution of an 54"T0 or "0L0T0 againstthe +iew& This is not a concern if +iews are not used for maintenance acti+ity due to restrictedpri+ileges&

Page 291: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 291/401

2ith that eing stated: in the later <8R releases) the 2=0R0 is always eing appliedagainst the data) incorrectly) when performing an 54"T0 or "0L0T0 against a +iew& NCRhas een notified and is looking at a fi.& Currently) when maintenance is performed in NS,mode) the 2,T= C=0CJ 34T,3N applies the 2=0R0 clause two times !this can e seen inthe output of the 064L,N on the following page%&

show +iew customerH

GGG Te.t of ""L statement returned&

GGG Total elapsed time was 1 second&

replace +iew customer as

sel customerWnumer as custno) customerWname as custname

  ) phoneWnumer as phone

from customerWtale

where customerWnameM'myname'

with check optionH

e.plain update customer set custname M 'a' where phone M 1H

A Rows Returned0.planation W

1& -irst) we lock a distinct $,J0L&;pseudo tale; for write on a Row=ash topre+ent gloal deadlock for $,J0L&customerWtale&

8& Ne.t) we lock $,J0L&customerWtale for write&& 2e do an all*$4s 54"T0 from $,J0L&customerWtale y way of an all*

rows scan with a condition of ! V(MI2ELcustomer7ta!leCustomer7name ? KmynameK) AND ((MI2ELcustomer7ta!leCustomer7name ? KmynameK) ANE& !$,J0L&customerWtale&phoneWnumer M 1 %%;%&

− No rows are returned to the user as the result of statement 1&

Loc+ing and ies

Now that +iews ha+e een demonstrated there is another consideration to understand& ,n anacti+e data warehouse) there e.ists the potential for rows to e locked for a change !2R,T0%while other users are attempting to read them& 2hen users need immediate access to rows)the L3CJ,NI modifier is often used in +iews to re/uest an CC0SS lock to pre+ent a /ueryfrom suspending when other users are modifying the underlying tale& 2R,T0 lock doesnot lock an CC0SS lock& That's the good news&

3n the other side of the coin) it means that one or more returned rows might e efore or after a pending change& ,n other words) running the same re/uest twice might returndifferent results due to the timing of the modifications& That is why the CC0SS lock isreferred to as a ;dirty read&; There is more information on L3CJ,NI in the transactionchapter in this ook&

The following CR0T0 <,02 uses the L3CJ,NI modifier to downgrade the normal R0"lock of the S0L0CT to an CC0SS lock:

C< ggregW3rderW+ S

L$C2IN8 $rder7ta!le ,or ACCE&&

Page 292: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 292/401

Page 293: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 293/401

Chapter 0D/ Macro Processing

Macros

Compatiility: Teradata 0.tension

$acros are SQL statements stored as an o(ect in the "ata "ictionary !""%& 5nlikea +iew) a macro can store one or multiple SQL statements& dditionally) the SQL isnot restricted to only S0L0CT operations& ,NS0RT) 54"T0) and "0L0T0commands are +alid within a macro& 2hen using #T0Q) conditional logic and#T0Q commands may also e incorporated into the macro&

The use of macros pro+ide the enefits) listed elow:Stored in the ""

o Can e shared y multiple userso SQL is stored in Teradata and not sent across the network

or channel Can e secured to keep users from accessing them

4ro+ide the access security to tales ll updates within a macro are considered a transaction

o ,f all steps work) all work is committed

o ,f a single step fails) all the updated rows are automaticallyrolled ack !undone% to their original +alues prior to themacro e.ecuting

4arameters can e dynamically passed to them for added fle.iility

"ata "efinition Language !""L% is used to create) delete or modify a macro& Themain restriction is that all o(ects in a dataase must ha+e uni/ue names&

 dditionally) since Teradata is case lind) names like $ymacro and mymacro areidentical&

Although a macro can ha<e multiple &-L statements ithin itJ i, a macrocontains LJ it must !e the last statement in the macro The reason for this isased on the transactional nature of a macro& Since ""L locks one or more rowswithin the "" and this could pre+ent user access to the "") it is desirale torelease these locks as soon as possile& Therefore) a macro's ""L transactionneeds to finish /uickly& ;enceJ you can only ha<e one L statement ithin amacro&

C"EATE MAC"$

The CR0T0 $CR3 or C$ statement initially uilds a new macro& ,t names the macro andoptionally the dataase where it is to e created& dditionally) it must specify the SQL

statement!s% that comprise the e.ecution of the macro&

0ach SQL statement within a macro must ha+e its own semi*colon to help the optimier delineate one SQL statement from another& ll the SQL statements must e enclosed inparentheses to e created and treated as a single transaction&

The following two synta. formats are oth +alid for a CR0T0 $CR3:

C"EATE MAC"$ Kmacro*name A&

 ! ,NS0RT &&& H O

Page 294: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 294/401

  54"T0 &&& H O

  "0L0T0 &&& H O

  S0L0CT &&& H O %

H

3r ** CR0T0 $CR3 can e are+iated as C$ !does not work in Queryman%

CM Kmacro*name A&

 ! ,NS0RT &&& H O

  54"T0 &&& H O

  "0L0T0 &&& H O

  S0L0CT &&& H O %

H

=ere is the creation of a simple macro:

C"EATE MAC"$ $yfirstWmacro A&! 'PATE tale8 S0T column1 M column1 X 19

  2=0R0 column8 M 1987 H

&ELECT column1) column8) column

-R3$ tale1 ,NN0R @3,N tale8

  3N tale1&column7 M tale8&columnE

2=0R0 tale8&column8 M 1987H % H

Notice first that the macro contains two SQL statements: 54"T0 and S0L0CT& Ne.t) othstatements are enclosed in the parentheses) unlike a CR0T0 <,02 and lastly) each of these statements ends with a semi*colon !H% so the optimier can determine the scope of 

each command&

2hen the ao+e macro is e.ecuted) it updates the +alue in column1 y adding 19 to it for therow!s% identified with a +alue of 1987 in column8& Then) it immediately turns around andselects the row!s% to display the result of the update operation&

 s good as this might e) it is still limited to the row!s% with the +alue of 1987 in column8& Tomake the macro more fle.ile and functional) parameter +alues can e passed to itdynamically at e.ecution time& That way) each time the macro runs it can change the +alue incolumn1 for any row& So) the first run can update rows with 1987 in column8 and the ne.trun perform the same processing) ut for the row!s% containing a +alue of 198B or any other +alue in column8&

,n order to take ad+antage of the aility to pass a parameter +alue) the macro must e uiltto e.pect a +alue and then sustitute the +alue into the SQL statement!s%& This gi+es morepower) more fle.iility and ease of use to the macro& Therefore) parameters are normallypart of a macro and a +ery good techni/ue&

The ne.t CR0T0 $CR3 incorporates a parameter called in+alue:

CR0T0 $CR3 $yetterWmacro !in+alue ,NT0I0R% S

! 54"T0 tale8 S0T column1 M column1 X 19

  2=0R0 column8 M :in+alue H

Page 295: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 295/401

S0L0CT column1) column8) column

-R3$ tale1 ,NN0R @3,N tale8

 3N tale1&column7 M tale8&columnE

2=0R0 tale8&column8 M :in+alue H % H

The parameter must e defined within the macro& s seen ao+e) a parameter called in+alueis defined as an ,NT0I0R data type within parentheses following the name of the macro& ny +alid Teradata data type is acceptale for use within a macro& 3nce a +ariale nameand data type are defined) the +ariale name can e sustituted within the macro as manytimes as needed&

Now that the parameter has a name) the optimier must e ale to distinguish the parameter name from the names of tales and columns& To make this distinction) a colon !:% precedesthe name of the parameter& The colon notifies the optimier that in+alue is a +ariale and nota column found in the ""& ,nstead) it takes the +alue stored there and sustitutes it into oneor more SQL statements&

To add more power and fle.iility) additional parameters can e added to the macro&=owe+er) e+ery parameter defined must e gi+en a +alue at e.ecution time& ,f the parameter 

list is too long or too short) an error occurs and the e.ecution stops& Now) $yetterWmacroe.pects one parameter to e passed to it at e.ecution time& The command to e.ecute$yetterWmacro is shown elow& =owe+er) the method to modify a macro is co+ered first&

"EPLACE MAC"$

The R04LC0 $CR3 statement is used to modify an e.isting macro& ,t is written +irtuallythe same as the CR0T0 $CR3 ecause it replaces an e.isting macro with a new macro)in its entirety& Therefore) the name must e e.actly the same) or it will uild a new macro& ,f the wrong name is used and there is another o(ect y the same name) it might replace thewrong macro& ,t is a +ery good idea to do a =0L4 "T"S0 efore replacing a macro&

The following is the correct synta. format for a R04LC0 $CR3:

"EPLACE MAC"$ Kmacro*name S

 ! ,NS0RT &&& H O

  54"T0 &&& H O

  "0L0T0 &&& H O

  S0L0CT &&& H O %

H

The ne.t R04LC0 $CR3 changes $yetterWmacro that was pre+iously uilt& Thischange adds a second parameter as a character type and changes the SQL to use the new

+ariale& The new +ariale ecomes a secondary comparison to further define the row!s% for the 54"T0 and S0L0CT& dditionally) it changes the ,NN0R @3,N to a R,I=T 35T0R@3,N&

"EPLACE $CR3 $yetterWmacro !in+alue1 integer) in+alue8 char!%% S

!54"T0 mytale

  S0T column1 M column1 X 19

2=0R0 column8 M :in<alue0 N" column7 M :in<alue9 H

S0L0CT column1) column8) column) column7

Page 296: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 296/401

-R3$ mytale S $T R,I=T 35T0R @3,N tale8

  3N $T&column7 M tale8&columnE

2=0R0 $T&column8 M :in<alue0

  N" ! tale8&column7 M :in<alue9 $" MTcolumn I& N'LL % H % H

Now that we ha+e a couple of macros) it is time to e.ecute them&

EQEC'TE MAC"$

To run a macro) the 060C5T0 or 060C command is used& ,f the macro e.pectsparameters) they must e included in the 060C command enclosed inparentheses& 3ne or more missing parameter +alues cause the e.ecution to fail&The parameters can e pro+ided in a positional se/uence or +ia the parameter name& ,f the positional se/uence is used) it is your responsiility to list them in thesame se/uence that they appear in the CR0T0 $CR3 statement& 3therwiseuse the name of the parameter to set the +alue&

The synta. for e.ecuting a macro is:EQEC Kmacro*name ! Kparameter*+alue*list % O

H

The following are e.amples to e.ecute oth of the macros created ao+e:

The 060C for $yfirstWmacro is:

060C $yfirstWmacroH

Since there are no parameters) no +alues are pro+ided in the 060C command&

The ne.t three 060C commands are all +alid for e.ecuting $yetterWmacro that

contains two parameters:060C $yetterWmacro !198B) '#C'%H

060C $yetterWmacro !in+alue1M198B) in+alue8M'#C'%H

060C $yetterWmacro !in+alue8M'#C') in+alue1M198B%H

The first 060C ao+e uses positional assignment of +alues to the parameters inthe macro& The order of the +alues in the 060C is +ery important& The ne.t three060C commands use the parameter name to assign +alues& Notice that when theparameter names are used) their se/uence in the 060C does not matter& The060C simply matches the names and assigns the +alues to each +ariale& lsonotice that when all parameter +alues are present) it is shorter to use a positionalassignment list for the +alues&

 ll SQL contained in a macro is treated as a single transaction and any output isreturned to the user as if it were run directly& The output report from$yetterWmacro using the ao+e +alues at e.ecution looks like this:

1 Row Returned

Page 297: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 297/401

column0 column9 column@ column

119 198B ac #C

,f the second +alue of the macro parameter needed to e a N5LL) any of the

060C commands elow accomplish this:060C $yetterWmacro !199) N5LL%H

060C $yetterWmacro !199) %H

060C $yetterWmacro !in+alue8MN5LL) in+alue1M199%H

060C $yetterWmacro !in+alue1M199%H

Since the second +alue is null) the R04LC0 $CR3 added the ,S N5LLcomparison& s a result) the ao+e e.ecution returns the following row:

1 Row Returned

column0 column9 column@ column

1 199 def

Since macros contain SQL) you can 064L,N a macro:

064L,N 060C $yfirstWmacroH

064L,N 060C $yetterWmacro !198B) N5LL%H

 lthough the ao+e 064L,N works with actual data +alues passed to it) thee.planation is not an accurate estimation& This is due to the nature of the presenceof the literal +alues opposed to dynamic +alues eing passed to a macro in aproduction en+ironment&

The following displays a more accurate estimation when using parameteriedmacros:

'&IN8 A INTJ B C;A"(@)

EQPLAIN EIE $ybetter=macro /)*, )+0Note The 5S,NI is called a $odifier ecause it modifies the SQL statement

that follows it& ,ts function is to estalish +ariale names with datatypes& Then) these names are a+ailale for use in the SQL statement&

The 064L,N is another modifier&

 s a matter of discussion) the parameter +alues should match the data type of thecolumns referenced in the SQL& ,f they do not match) a con+ersion must eperformed& 4lus) we ha+e seen situations where the type difference caused theoptimier to not use a 4, and did a full tale scan instead& #e sure to 064L,Nmacros efore putting them into production&

Page 298: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 298/401

"$P MAC"$

The "R34 $CR3 statement has only one function& ,t deletes a macro out of the ""&Therefore) it is a +ery powerful and easy command to use& dditionally) there is no /uestionthat asks if you are sure you want to "R34 T=0 $CR3 and there is no undo functionality&,f a user has the pri+ilege to "R34 a macro and e.ecutes a "R34 $CR3 command) the

macro is gone&

The following is the synta. of the "R34 $CR3 command&

"$P MAC"$ Kmacro*name

H

 n e.ample:

"R34 $CR3 $yfirstWmacro H

5nlike the CR0T0 $CR3 that had to estalish the parameters and pro+ide the SQL) the"R34 $CR3 does not care& The name is all it needs to eliminate the macro from the ""&

Since there is no undo function for the "R34 $CR3) it is a good idea to ha+e the CR0T0$CR3 statement stored somewhere on disk a+ailale for reco+ery& ,f it is not sa+ed atcreation) efore dropping the macro) a S=32 $CR3 can e e.ecuted to return theCR0T0 $CR3 statement for sa+ing on disk& =owe+er) if a large macro is eing uilt) itshould e sa+ed initially& 3therwise) if the CR0T0 $CR3 is too large to store in the "")part of it may e lost using the S=32 $CR3&

8enerating &-L ,rom a Macro

$acros can also e used to easily perform administrati+e functions that would otherwisere/uire manual inter+ention& s a matter of fact) NCR distriutes se+eral macros with theinstallation of Teradata to monitor things like space utiliation&

, teach se+eral classes for the same Teradata customers& 2hen this occurs) there areusually tales) +iews and macros left o+er from the pre+ious class& There is not always a lotof time a+ailale to drop these o(ects either efore or after a class& So) , needed a fast wayto accomplish that operation& macro was the perfect solution&

The ne.t macro uilds "R34 T#L0 statements using #T0Q:

R04LC0 $CR3 "ropper !,n5ser !C=R!9%% % S

!0C=3 '&S0T "0-5LTSH'H

&0643RT "T -,L0Mdropfile&t.t

S0L0CT '"R34 T#L0 ' talename 'H' -R3$ "#C&Tales

2=0R0 5serName M :,n5ser and Talekind M 'T' H

To e.ecute the macro and SQL created from #T0Q:

060C "ropper !'mikel'%H

&R5N -,L0Mdropfile&t.tThe Teradata dataase has not historically had stored procedures& ,nstead) it offered thefunctionality of macros& Stored 4rocedures are new with <8R7 and pro+ide conditionalprocessing logic in addition to the SQL& Stored 4rocedures are co+ered in the last chapter  of 

Page 299: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 299/401

this ook& s a result) conditional and looping logic are now a+ailale for use in tools other than #T0Q) such as Queryman&

Chapter 1E: Transaction Processing

:hat is a Transaction

  transaction is the control applied within a dataase to guarantee data integrity& ,t relies onand monitors each SQL operation for a successful completion& The philosophy of atransaction is that all work completes or no work completes& ,t is normally considered an allor nothing proposition&

  transaction can e a single step or a multi*step operation& ,n Teradata) a single stepimplies a single SQL statement& Therefore) all SQL statements !,NS0RT) 54"T0 or "0L0T0% are) y default in Teradata mode) considered indi+idual and complete maintenancetransactions& This simply means that a changed data lock has een rewritten on disk& Thechange might e to include a new row !,NS0RT%) a row with at least one column +alue

modified from its original content !54"T0%) or one less row !"0L0T0%& 3nce the write of alock completes successfully) all other lock writes must work correctly) or the pre+iouswrites need to e undone or rolled ack& Rememer) transactions should e all rows arechanged) or no rows are changed&

-or e.ample) if all employees in a company are to recei+e an annual increase of 7U) it is notsufficient to gi+e the raise to one person& 0+eryone is supposed to e treated the same&Therefore) if the 54"T0 multiplies e+eryone's salary y 1&97 successfully) e+ery salary ine+ery row must reflect the increase& =owe+er) if the 54"T0 fails efore e+eryone recei+esthe raise) the dataase must go ack and re+erse out the raise from all the rows alreadychanged and written to disk& This re+erse process is called a rollack&

Teradata uses tale or row le+el locks and the Transient @ournal to guarantee the all or nothing aspect of a transaction& -irst) any changed data row is locked for 2R,T0 so no onecan R0" it until all writes are completed with the new data& Second) the Transient @ournalcaptures a copy of the original row in case a rollack is needed& Then) multiple SQLstatements can finish with the assurance that all or none of the changes complete&

 s a real world e.ample of a multi*statement re/uest: what if a ank customer needs totransfer money from their sa+ings account to co+er a check that is already written Thischange re/uires two SQL 54"T0 statements& The first 54"T0 sutracts the amount of the transfer from the row in the sa+ings account tale& The second 54"T0 adds that sameamount to the corresponding row in the checking account tale&

,t is important that oth changes work successfully for the operation to e completesatisfactorily& 3therwise) if the sutraction from the sa+ings account works and the additionto the checking account fails) there is a prolem& ,magine how unhappy you would e when

the monthly statement arri+es& There is money missing from your sa+ings account and thecheck ounced due to insufficient funds&

Likewise) it is important to end a transaction& Since a transaction must e all or nothing) twothings need to occur during the life of a transaction& -irst) to pre+ent access y other users)all changed rows are locked& This means that no user e.cept the one issuing the locks canget to the resource rows&

Page 300: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 300/401

Second) all updated rows ha+e a copy of the original row !efore image% stored in theTransient @ournal& The Transient Sournal stores these ros in the Permanent space o, the BC user (ata ictionary)

3nce a transaction ends successful) the work is committed) all locks are released and theefore images are deleted from the Transient @ournal& =owe+er) if the transaction fails) allefore images in the Transient @ournal are put ack into the tale!s% to undo the effect of thechanges made to these rows y the transaction& t that point) the locks can e released&This undo operation is called a rollack& ,t can take as long or longer to rollack the work asit did to do the work initially&

Loc+ing

Compatiility: Teradata 0.tension

Locking in Teradata is automatic and cannot e turned off for normal tales& There are four types of locks that are used and they are:

%igure 010 

The resource that is locked depends on the SQL command re/uested y the user& The lockmay e set at the dataase) +iew) tale) or row le+el&

%igure 01@ 

 ll SQL commands automatically re/uest a lock& The Teradata R"#$S attempts to lock theresource at the lowest le+el possile& The lowest le+el is a row lock& =owe+er) Teradataplaces more importance on performance than resource a+ailaility& This implies that theoptimier has the last say in the locking le+el that is used&

-or instance) an 54"T0 has the option of locking at the tale or row le+el& The optimier knows that when an entire tale is locked) all other users must wait to read e+en a single rowfrom the tale& =owe+er) when only a row is 2R,T0 locked) other users still ha+e access tothe tale) and only ha+e to wait if they need to read the row currently locked& Therefore)normally row le+el locks are preferale so that rows ha+e a ma.imum a+ailaility for users&This is especially important if another user is re/uesting a 54, +alue not used in the54"T0& This type of locking pro+ides more opportunity for concurrency of user re/uests

and etter o+erall performance&

=owe+er) the optimier also knows when all rows in a tale are going to e changed& ,t couldfollow the row locking to allow as much access as possile& =owe+er) e+entually all rows arelocked& lso) it knows that to lock a row and then read a row o+er and o+er again takeslonger than locking the tale once) reading all rows as fast as possile) and then releasingall locks at once& A ,ull ta!le scan needs all ros There,oreJ the normal ro le<el loc+ill !e escalated to a ta!le le<el loc+ ,or speed on a ,ull ta!le scan AdditionallyJ !yloc+ing the ta!leJ it eliminates the potential ,or a deadloc+ !eteen multiple user re>uests&

Page 301: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 301/401

Regardless of the approach to locking that the optimier chooses) e+entually all access tolocked rows is denied for a period of time& The chart in -igure 1E*8 indicates that a 2R,T0lock locks other 2R,T0 locks re/uested y other users& dditionally all R0" lock re/uestsare also locked ecause the current data is eing changed and therefore) not a+ailale untilit is finished& This is where the CC0SS lock can e useful&

%igure 019 ,t is also seen in -igure 1E*8  that the 2R,T0 lock does not lock an CC0SS lock&Therefore) a user can re/uest an CC0SS lock for a S0L0CT instead of the default R0"lock& This does howe+er mean that the data read may or may not e the latest +ersion&=ence) the nickname ;"irty Read&; This is commonly done in +iews& To re/uest a lockingchange) the L3CJ,NI -3R modifier can e used& ,t is written ahead of the SQL statementto modify the way it e.ecutes&

These are the +arious synta. formats of the L3CJ,NI $odifier:

L$C2IN8 Ktale*nameO -3R Kdesired*locking N32,TO

L$C2IN8 "$: %$" Kdesired*lockingL$C2IN8 ATABA&E Kdataase*name -3R Kdesired*locking

L$C2IN8 IE: K+iew*name -3R Kdesired*locking

L$C2IN8 TABLE Ktale*name -3R Kdesired*locking

The first synta. listed ao+e defaults to a R32 le+el lock using the desired lock& So) the firsttwo L3CJ,NI re/uests do the same thing& To make the command shorter) the L3CJ,NIcan e are+iated to L3CJ&

The first synta. format also shows the N32,T option& ,t indicates that if a resource is nota+ailale the statement should not wait& ,nstead) it will instantly #3RT& There is another option called $3"0 that can e used& =owe+er) it does not do anything and is there strictly

for compatiility with "#F8 SQL& Lastly) also for compatiility) the -3R can e changed to an,N& The N32,T is a+ailale for all locking re/uests&

The other specification in the ao+e formats is used for specifying the dataase o(ect tolock& ,n reality) multiple L3CJ,NI modifiers might e.ist on a single S0L0CT& -or instance) ina (oin operation an CC0SS lock might e re/uested for one tale and not the other&

%igure 01 

The ao+e chart shows that the S0L0CT is the only command that can use the L3CJ,NI-3R modifier for anything other than 06CL5S,<0& This is ecause most locks cannot edowngraded to a lesser lock) without causing potential data integrity issues& Since theS0L0CT is not changing data) it can e downgraded safely&

,t is +ery common to use the CC0SS locking when creating a +iew& Since most +iews onlyS0L0CT rows) a 2R,T0 lock is not needed& 4lus) if maintenance is eing performed on atale) selecting rows using a +iew with an CC0SS lock is not delayed due to a 2R,T0 lock&So) users are happy and don't call to complain that the ;system is slow&;

Page 302: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 302/401

 nother time to use the L3CJ,NI modifier is for multi*step transactions& Consider thissituation: The first step is a S0L0CT and otains a R0" lock& This lock allows other usersto also S0L0CT from the tale with a R0" lock& Then) the ne.t step of the transaction is an54"T0& ,t must now upgrade the R0" lock to a 2R,T0 lock&

This upgrade of the lock cannot occur while other users ha+e a R0" lock on the resource&Therefore) the transaction must wait for the R0" locks to disappear& This mightdramatically increase the time to complete the maintenance transaction& Therefore) yupgrading the initial default of a R0" lock to a 2R,T0 lock for the S0L0CT it eliminates thepotential for a delay in the middle of the transaction&

The ne.t S0L0CT uses the CC0SS lock) common in a <iew:

064L,N

L$C2IN8 "$: %$" ACCE&&

2=0R0 customerWname L,J0 '#illyU' H

19 Rows Returned0.planation

1& -irst) we lock $,J0L&CustomerWtale for access&

8& Ne.t) we do an all*$4s R0TR,0<0 step from $,J0L&CustomerWtale yway of an all*rows scan with a condition of  !;$,J0L&CustomerWtale&CustomerWname L,J0 ]#illyU ;̂% into Spool 1) whichis uilt locally on the $4s& The sie of Spool 1 is estimated with noconfidence to e 7 rows& The estimated time for this step is 9&1 seconds&

& -inally) we send out an 0N" TRNSCT,3N step to all $4s in+ol+ed inprocessing the re/uest&* The contents of Spool 1 are sent ack to the user as the result of statement 1& The total estimated time is 9&1 seconds&

Since the locking modifier can name the tale) each tale may use different locking whenmultiple tales are referenced in the same SQL statement& 2e recommend that you consultthe 5ser Reference $anual if you are going to e using the L3CJ,NI modifier e.tensi+ely& ,t

is not the intent of this ook to make you an e.pert on L3CJ,NI&

Transaction Modes

The Teradata dataase software was originally written to e compatile with "#F8) the ,#$mainframe R"#$S !Relational "ata #ase $anagement System%& ,t was de+eloped primarilyas a dataase computer to e connected to mainframe systems& ,n the years since then)Teradata has e+ol+ed to include connections to network attached computers&

 nother e+olution for Teradata is the inclusion of NS, !merican National Standards,nstitute% standards in its functionality and the format of its SQL commands& This allowsusers to learn SQL commands once and use them on se+eral R"#$S systems& t the same

time) most R"#$S +endors pro+ide e.tensions to their dataase that e.tend thefunctionality of their SQL& These e.tensions are what +endors call ;+alue add&; 0.tensionsmay take ad+antage of a particular strength of the R"#$S or pro+ide a uni/ue functionalityto make the user's life easier&

,t is good that all of the R"#$S +endors are conforming to the standards& This way the samere/uest on different systems does not create une.pected results on +arious systems&Teradata is a mature R"#$S and e.isted efore the standards were defined& Therefore)some of the techni/ues and commands for Teradata ecame part of the standardH others did

Page 303: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 303/401

not& 2hen the standard operation contradicts what customers ha+e come to count on) theree.ists the opportunity for confusion&

To resol+e this potential prolem) Teradata allows a user to specify which transaction modeto use for any SQL statement& The normal system default for a Teradata system is Teradatamode& =owe+er) Teradata can e configured to use NS, mode as the system default& Toestalish a site*specific system default) the system administrator can change the "#SControl Record as an administrati+e function&

Regardless of which mode is set as the system default) a user can o+er*ride it for a session&This means that a system running in Teradata mode can use NS, mode for one or moreSQL statements and of course) the opposite is also true& s far as the SQL is concerned) thesynta. does not change& 2hether in Teradata or NS, mode) the SQL is always writtene.actly the same& NS, commands work in Teradata mode and Teradata e.tensions work in

 NS, mode& T=0 SQL "30S N3T N00" T3 C=NI0 to match the mode& =owe+er) theoutput data may +ary from one mode to the other ased on the conditions outlined in thechart on the following page&

Comparison Chart

%igure 01D

&etting the Transaction Mode

Compatiility: Teradata 0.tension

 s mentioned ao+e) the Teradata default Transaction mode is set at the system

le+el& Teradata system can default to either Teradata or NS, mode& The systemle+el setting is estalished in the "#S Control Record&

2hen using #T0Q) it is possile to o+er*ride the transaction mode at the sessionle+el& Since the session is estalished at logon time) it is necessary to set themode prior to issuing a logon connection re/uest& Rememer) the transactionmode impacts the way SQL will e.ecute) so the mode must e estalished at the4arsing 0ngine !40% to affect the session&

Page 304: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 304/401

,n #T0Q) either of the following commands can e used to change to NS, or Teradata !#T0T% mode:

** set transaction mode to Teradata

&S0T S0SS,3N TRNSCT,3N #T0TH

or 

** set transaction mode to NS,

.&ET &E&&4#8 T"*8&*T4#8 *8&4Note the dot !&% is necessary ecause it is a #T0Q command and not SQL&

 lthough the NS, specification is o+ious) the #T0T is not intuiti+e& ,n the chartao+e) it is indicated that #0I,N TRNSCT,3N !#T% and 0N" TRNSCT,3N!0T% commands can e used to delineate an e.plicit transaction& The #T0T simplycomes from a comination of these two transactional commands to indicateTeradata transaction mode& n e.planation of implicit and e.plicit transactions isaddressed in this chapter&

The transaction mode only needs to e specified if the SQL output re/uiresdifferent characteristics than the mode that is estalished as the default for thesystem& ,f the default is acceptale) there is no need to change it&

Teradata Mode Transactions

 s mentioned earlier) Teradata mode considers e+ery SQL statement as a stand*alone transaction& This means that if the outcome of the statement is successful)the work is committed to the dataase& This is particularly important when data iseing written onto disk instead of simply read&

2hen multiple tales are eing updated) multiple SQL commands must e used&

single transaction can e estalished using a couple of different techni/ues inTeradata& The easiest and surest techni/ue is to put all the SQL statements into amacro& This works well in #T0Q) Queryman) and all client software applications&Therefore) it is the est techni/ue&

  second reliale techni/ue is a+ailale only when using #T0Q& ,t in+ol+es takingad+antage of the way #T0Q deli+ers the SQL to the optimier& The trick is tocontinue each suse/uent SQL statement on the same line as the semi*colon !H% of the pre+ious statement& 2hen #T0Q finds this condition) it automatically deli+ersthe commands as a single transaction&

The following demonstrates this techni/ue:

54"T0 0mployeeWTale

S0T Salary M Salary G 1&1

2=0R0 0mployeeWNo M 188DB

H 'PATE "epartmentWTale -R3$ 0mployeeWTale S 0

S0T #udgetWmount M #udgetWmount X !Salary G &91%

2=0R0 0&"eptWNo M "epartmentWTale&"eptWno

 N" 0&0mployeeWno M 188DB

H

Page 305: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 305/401

,n the ao+e script) oth updates must work successfully) or oth will e rolledack ecause the second 54"T0 is on the same line as the semi*colon for thefirst 54"T0& 2hen a semicolon !H% is not the last thing on a line) #T0Q treats thene.t SQL as part of the same transaction&

The last techni/ue uses the Teradata  #0I,N TRNSCT,3N !#T% and 0N"TRNSCT,3N !0T% commands to delineate the transaction in Teradata  mode&

 lthough these work in some of the other client tools) they should primarily eused in #T0Q&

2e say this ecause #T0Q has the aility to e.ecute in atch !ackground withoutuser interaction% and to check the outcome of the pre+ious SQL statement usinga &if command for +erification that it was successful& ,t also pro+ides hooks toterminate the e.ecution of the script or ranch around suse/uent SQL statementsthat should not e e.ecuted when a failure occurs& This control is important toguarantee the all or nothing philosophy of a transaction&

The ne.t transaction operates e.actly the same as the pre+ious two techni/ueswhen using #T0Q:

BT=

54"T0 0mployeeWTale

S0T Salary M Salary G 1&1

2=0R0 0mployeeWNo M 188DB H

&if errorcode 9 then &/uit 18

54"T0 "epartmentWTale -R3$ 0mployeeWTale S 0

S0T #udgetWmount M #udgetWmount X !Salary G &91%

2=0R0 0&"eptWNo M "epartmentWTale&"eptWno

  N" 0&0mployeeWno M 188DB H

0TH

3r 

BT=

54"T0 0mployeeWTale

S0T Salary M Salary G 1&1

2=0R0 0mployeeWNo M 188DB H

i, errorcode 4 6 then goto EndTrans

54"T0 "epartmentWTale -R3$ 0mployeeWTale S 0

S0T #udgetWmount M #udgetWmount X !Salary G &91%

2=0R0 0&"eptWNo M "epartmentWTale&"eptWno

  N" 0&0mployeeWno M 188DB H

ET=

la!el EndTrans

>uitNote #T and 0T are the are+iations for #0I,N TRNSCT,3N and 0N"

TRNSCT,3N to estalish an e.plicit transaction& ,n the first script)

Page 306: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 306/401

the if statement checks for an good completion as 9 and uses the &/uit18 as the error return code from the script& The second e.ample usesa ;go to; command to ranch to the end script& The concept of a scriptimplies a atch !without interacti+ity of a user% operation and thereforeit is important to use the &if to ha+e #T0Q check for a failure&

,t is important ecause if a failure occurs in the first 54"T0) it causes thetransaction to aort and the transaction automatically ends& Since there is nolonger a transaction in process and the flow is from top to ottom) the second54"T0 is e.ecuted as a new and single ;implied; transaction in Teradata mode&Then) a warning is issued when the 0T is e.ecuted ecause there is no transactionin process) due to the #3RT& See orting Teradata Transactions later in thischapter& Therefore) the check is important to pre+ent the e.ecution of the second54"T0 statement& ,f this same SQL were e.ecuted interacti+ely) the user wouldne+er enter the second 54"T0& =owe+er) in atch scripts all commands areperformed se/uentially !top to ottom% from a file stored on disk instead of eingtyped adhoc y a person&

 s seen ao+e) #T0Q can run in either atch or interacti+e mode) ut sinceQueryman is interacti+e only) the user is notified immediately of a failure with an

error code& 3nce the error is e+aluated) the user takes the appropriate action&=owe+er) when doing ;atch; or off*line processing) there is no user to take anaction& Therefore) it is important to pro+ide the appropriate checks and alances ina script&

AN&I Mode Transactions

 NS, mode transactions work the opposite of Teradata mode in the way they are controlled&,t assumes that all SQL statements are part of a single transaction& The user must re/uestthe end of a transaction and commit the work to disk in order to sa+e the work) release allheld locks and delete the efore images from the Transient @ournal&

The following command must e used to successfully end an NS, transaction !single or 

multi*step command%:

C3$$,T 23RJH

This command re/uests that) if the outcome of the statement is successful) the work iscommitted to the dataase& This is particularly important when data is eing changed&3therwise) if the user ne+er commits the work and logs off) the completed work isautomatically e rolled ack from the Transient @ournal) like it ne+er happened&

To perform the same transaction ao+e using #T0Q in NS, mode) the following commandscan e used:

54"T0 0mployeeWTale

S0T Salary M Salary G 1&1

2=0R0 0mployeeWNo M 188DB H

i, errorcode 4 6 then >uit 09

54"T0 "epartmentWTale -R3$ 0mployeeWTale S 0

S0T #udgetWmount M #udgetWmount X !Salary G &91%

2=0R0 0&"eptWNo M "epartmentWTale&"eptWno

 N" 0&0mployeeWno M 188DB H

Page 307: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 307/401

C3$$,T 23RJ H

 gain) in atch mode it is still important to use the &if to check the outcome& This is especiallytrue in NS, mode due to its perception of a transaction& NS, tends to commit allmodifications that work and rollack only the indi+idual statements that failed& This NS,definition is definitely different than my perception of a transaction& #ut now you know how itworks too&

A!orting Teradata Transactions

 nytime an error occurs in an SQL statement) it is automatically aorted) or ended with aad outcome !error code greater than 9%&

To manually aort a transaction) the user can issue either of the ne.t commands:

 #3RTH

or 

R3LL#CJH

Logging off and ending the session without performing an 0T also constitutes an aort of thetransaction& The caution here is that all work is rolled ack& The e.ample elow starts atransaction and runs se+eral SQL statements& 2atch what happens in the end when thetransaction is #3RT0"&

The ne.t commands use the Customer tale to demonstrate the functionality of an e.plicit#T0T transaction:

%igure 01 

#TH

Sel G from CustomerWtaleH

Rows Returned

Customer7num!er Customer7name Phone7num!er  

11111111 #illy's #estChoice

*187

1111 cme 4roducts *1111

1817 C0 Consulting *1818

DBAEBB 6Z 4luming 7D*BA7

BD87E "ataases N*5 88*1918

"0L0T0 -R3$ CustomerWtaleH

Page 308: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 308/401

Sel G from CustomerWtaleH

No Rows Returned

 #3RTH

GGG -ailure 17 5ser*generated transaction #3RT&

Sel G from CustomerWtaleH

Rows Returned

Customer7num!er Customer7name Phone7num!er  

11111111 #illy's #estChoice

*187

1111 cme 4roducts *1111

1817 C0 Consulting *1818

DBAEBB 6Z 4luming 7D*BA7

BD87E "ataases N*5 88*1918

The interesting aspect of this e.ercise comes after the "0L0T0& #ecause this is a multi*step transaction) all efore images of the deleted rows are in the Transient @ournal) ut not inthe tale& Therefore) the S0L0CT returns no rows as the correct status of the tale&=owe+er) the #3RT tells Teradata that the transaction has failed& So) it rolls the eforeimages from the Transient @ournal ack into the tale& Then) they are again a+ailale for thelast S0L0CT (ust as they were for the first S0L0CT&

  way to accidentally aort a multi*step transaction is to perform any other SQL statementafter using ""L& Since the "" is locked for 2R,T0) Teradata demands that you commitwork as the ne.t step of a multi*statement transaction& 3therwise) the dataase aorts your transaction and releases the locks&

A!orting AN&I Transactions

To manually aort a transaction in NS, mode) the user can issue the following command:

R3LL#CJ 23RJH

Logging off and ending the session without performing a C3$$,T will also constitute anaort of the transaction& The caution here is that all work would e rolled ack

The pre+ious e.ample in Teradata mode can e duplicated here& The only difference is thatR3LL#CJ 23RJ may e used to terminate the transaction& Regardless) if performedcarefully) the result is the same& Since NS, mode is always multi*step) any SQL attemptedafter ""L causes the transaction to aort&

Page 309: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 309/401

Chapter 1D: "eporting Totals and &u!totals

Totals and &u!totals

0arlier) we disco+ered the aility to e.ecute aggregates to find totals and sutotals using theIR354 #& =owe+er) an indi+idual row's detail column data is a+ailale when usingaggregates& The actual +alues are not seen) only the answer&Teradata has the capaility to generate the total and sutotals and at the same time displaythe detail data from the rows that goes into creating the totals& ,n this chapter) we e.plore theuse of the 2,T= and 2,T=…# functions to pro+ide oth totals and sutotals&

The following tale is used for the SQL e.amples in this chapter:

%igure 0F10 

Totals (:IT;)

Compliance Y Teradata 0.tension

Teradata pro+ides for the creation and display of a final total for all the data +alues in one or more columns& t the same time) it shows the detail +alues) row y row) that went into thetotal& To otain a grand total the S0L0CT contains a 2,T= to identify the column on which toperform an aggregate&

#ecause it is called a total) the S5$ function is normally used) howe+er) the other aggregates may also e used to generate a final +alue&

To produce a final total) use the following synta.:

S0L0CT Kcolumn*name

  ) Kcolumn*name

  ) Kcolumn*name

-R3$ Ktale*name

:IT; &'M( 3column1name4 )

H

The ne.t S0L0CT shows the detail of the rows in the tale with final total displayed at theend of the output report for the salary:

Page 310: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 310/401

Page 311: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 311/401

Last7Name %irst7Name ept7no &alary

Strickling Cletus 799 799&99

=arrison =erert 799 799&99

Reilly 2illiam 799 E999&99Smith @ohn 899 7B999&99

Total&alary/ 

906@H@G

-urthermore) it might e desirale to include an a+erage salary to the pre+ious e.ample asseen in the ne.t S0L0CT can accomplish this:

S0L0CT LastWName

  )-irstWName

  )"eptWno

  )Salary

-R3$ 0mployeeWtale

:IT; A8(salary) (TITLE KA<erage &alary/K)

  J &'M(salary ) (TITLE KTotal &alary/KJ %$"MAT K\\\\J\\HHHK)

2=0R0 "eptWno etween 199 and 99H

7 Rows Returned

Last7Name %irst7Name ept7no &alary

Chamers $andee 199 7BB9&99

Larkins Loraine 99 79899&99

Coffing #illy 899 71BBB&BB

Smith @ohn 899 7B999&99

A<erage&alary/ 

F@F9 

Total&alary/ 

\0FGJH@GGG

 s you can see in Teradata) it is relati+ely easy to otain a f inal numer for display from anaggregate) title it and format it) all this along with the detail row data that created it& Noticetoo that the totals can e formatted indi+idually and can e different&The ne.t section of this chapter addresses the aility to calculate and print sutotals&

&u!totals (:IT;…BY)

Compliance Y Teradata 0.tension s well as the aility to pro+ide a total) Teradata can also pro+ide one or more sutotals& Tootain a sutotal) the 2,T= incorporates a # designation& The 2,T=…# can eincorporated into e.isting SQL to pro+ide a sutotal&2hen using sutotals) it is important to choose a control column& ,t must contain a +alue thatgroups data together and causes a reak to occur when it changes& ,n addition) the +alue is

Page 312: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 312/401

also used to sort the data so that all reaks occur only once per uni/ue +alue& t the reak)the sutotal is displayed for the +alues up to that point and then reset for the ne.t group of +alues& 5nlike the IR354 #) the 2,T=…# performs a sort operation to with a defaultse/uence of SC order& =owe+er) if desired) the "0SC can e used to re/uest a descendingsort&The asic synta. of the 2,T=… # and sample output follows:

S0L0CT Kcolumn*name  )Kcolumn*name

-R3$ Ktale*name

:IT; &'M( 3column1name4 ) BY 3column1name4

HThe ne.t S0L0CT uses the 2,T=…# to add up the salaries within a department as onesutotal per department:

S0L0CT LastWName

  )-irstWName

  )"eptWno

  )Salary-R3$ 0mployeeWtale

:IT; &'M(salary) (TITLE Kepartmental &alaries/K) BY dept7no

2=0R0 "eptWno etween 199 and 899 H

Rows Returned

Last7Name %irst7Name ept7no &alary

Chamers $andee 199 7BB9&99

  epartmental&alaries/ 

GGD666

Coffing #illy 899 71BBB&BB

Smith @ohn 899 7B999&99

  epartmental&alaries/ 

GHGGGGG

,n the output) when the department numer changed from 199 to 899 a reak occurred& fter the sort) all the department 199 rows are together and precede all of the rows for department899& This reak process repeats for as many uni/ue +alues contained in the data&The ne.t S0L0CT demonstrates the comination of sutotals !2,T=…#% and total !2,T=%in a single re/uest:

S0L0CT LastWName

  )-irstWName  )"eptWno

  )Salary

-R3$ 0mployeeWtale

:IT; &'M(salary) (TITLE Kepartmental &alaries/KJ %$"MAT K\\\\J\\\HHK )

  BY dept7no

:IT; &'M(salary) (TITLE KTotal &alary/KJ %$"MAT K\\\\J\\\HHK)

Page 313: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 313/401

2=0R0 "eptWno ,N !199)899% H

Rows Returned

Last7Name %irst7Name ept7no &alary

Chamers $andee 199 7BB9&99

"epartmentalSalaries:

[7B)B9&99

Coffing #illy 899 71BBB&BB

Smith @ohn 899 7B999&99

"epartmentalSalaries:

[BA)BBB&BB

Total Salary: [1B)DB&BBLike any data +alue) when using #T0Q) the output can e formatted to dress up itsappearance& This is re/uested in the 2,T= or 2,T=…#&

Multiple &u!totals on a &ingle Brea+Like the 2,T=) the 2,T=…# may e used with more than one aggregate +alue on a singlereak& To accomplish this) simply add a comma after the pre+ious aggregate and code thene.t&

The ne.t S0L0CT adds an a+erage along with the sum:

S0L0CT LastWName

  )-irstWName

  )"eptWno

  )Salary

-R3$ 0mployeeWtale

:IT; A8(salary) (TITLE Kepartment A<erage/K)

  J &'M(salary ) (TITLE Kepartment Total/ K) BY dept7no

2=0R0 "eptWno etween 199 and 899 H

Rows Returned

Last7Name %irst7Name ept7no &alary

Chamers $andee 199 7BB9&99

  "epartment +erage:

7BB9&99

  "epartmentSalary:

7BB9&99

Coffing #illy 899 71BBB&BB

Smith @ohn 899 7B999&99

  "epartmental +erage:

77A88&88

  "epartment BABBB&BB

Page 314: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 314/401

Last7Name %irst7Name ept7no &alary

Salary:

,n the ao+e e.ample) each time the +alue in the department numer changes) oth

aggregates are displayed& Then) they are oth reset and the ne.t group of rows egins itsown calculation& ll of these e.amples contain one column in the # portion of the 2,T= … # to monitor for changes& $ore than one column may e specified& =owe+er) e aware that as more columnsare indicated) there is a higher proaility that one of the +alues in the columns is going tochange& 2hen this happens) a reak occurs and a sutotal is displayed& s a result) therewill e more sutotals displayed&

Multiple &u!total Brea+s2ith that said) it is likely that there is a need to ha+e more than one sutotal in the re/uest&Se+eral 2,T=…# sutotals can e incorporated into a single SQL statement& -or eachadditional sutotal) a different column is used for the ne.t sutotaled +alue from the list&Since each 2,T= …  # produces an ascending !lowest to highest +alues% sort) it is

important to arrange them carefully to create the se/uence desired in the output& The last2,T= … # in the S0L0CT statement is the ma(or sort se/uence& The first occurrence of 2,T=… # is the most minor sort and any sutotal etween them are also minor sorts)increasing in sort significance to the last 2,T=… #&

The Sales tale elow is used to show the output with sutotal multiple reaks&

Page 315: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 315/401

%igure 0F19 To code additional sutotals) simply add another 2,T= … # as shown in the followingS0L0CT sumitted using #T0Q:

S0L0CT 4roductW,"

  )SaleWdate !-3R$T '$$$"")'%

  )"ailyWSales !-3R$T '[[[[)[[[&AA'%

-R3$ SalesWtale

:IT; &'M( aily7sales ) (TITLE KBy Month/K)

  (%$"MAT K\\\\J\\\HHK) BY &ale7date#066

FG Sale date F 199 se/uences daily sales as monthly sales GF

:IT; &'M( aily7sales ) (TITLE KBy Product/K )

  (%$"MAT K\\\\J\\\HHK) BY Product7IFG 3R"0R # most minor sort puts rows in daily se/uence GF

2,T= S5$!"ailyWsales% !T,TL0 'Irand Total:') -3R$T '[[[[)[[[&AA'%

2=0R0 4roductW," ,N !1999) 8999%

3R"0R # saleWdate H

81 Rows Returned

Page 316: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 316/401

Product7I &ale7date aily7&ales

1999 Sep 8B)8999

[7B)B9&79

1999 Sep 8A)

8999

[7)99&88

1999 Sep 9)8999

[E)999&9D

#y $onth: [1A)9&EA

1999 3ct 91)8999

[79)899&7

1999 3ct 98)8999

[8)B99&9

1999 3ct 9)8999

[E7)99&99

1999 3ct 97)8999

[7)&19

#y $onth: [1A1)B7&9

  #y4roduct:

[1)897&D8

8999 Sep 8B)8999

[71)BBB&BB

8999 Sep 8A)8999

[7B)999&99

8999 Sep 9)

8999

[7A)B9&9

#y $onth: [1A)DB&A1

8999 3ct 91)8999

[7)B9&8A

8999 3ct 98)8999

[E)981&A

8999 3ct 9)8999

[7)899&1B

8999 3ct 97)8999

[8)B99&9

#y $onth:

[1EE)BD8&A9

  #y4roduct:

[9E)E11&B1

IrandTotal:

[ED)B1E&

Since an e.planation of what the sutotal represents is a good idea) it is common to add aT,TL0 to each sutotal& ,t dresses up the output instead of seeing the name of the aggregatewith the Kcolumn*name&

Page 317: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 317/401

 s a reminder of something mentioned earlier in this chapter) this capaility does not workwith 3"#C and Queryman

Page 318: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 318/401

Chapter 1B: ata e,inition Language

Creating Ta!les<ictor =ugo once said) ;n in+asion of armies can e resisted) ut not an idea whose timehas come&; ,f you talk to a typical "ataase dministrator setting up R"#$S !Relational"ata #ase $anagement% systems you will hear how difficult and time consuming it is to

create tales& Teradata) realiing the sheer magnitude and sie of most data warehouses)created an idea that the system should manage the difficult pieces of setup andadministration& This is an idea whose time has come&

This chapter is dedicated to the art and science of creating Teradata tales and the "ata"efinition Language !""L% of SQL& Lots of people confuse a poor dataase design withdestiny& They spend enormous time and energy setting up tale space) reorganiing thedata) and o+er inde.ing) (ust to get the system to function with limited capailities& Theyassume it is (ust part of the (o) ut after they e.perience Teradata  they realie andappreciate the straightforward manner in which Teradata functions&

"o not underestimate the importance of understanding how to manage tales in a datawarehouse& $ost people in data processing start their computer science work in an 3LT4en+ironment& This is radically different than most data warehouse en+ironments& ,n an on*

line dataase there may e doens or hundreds of different tales& ,n a data warehouseen+ironment there are often hundreds or thousands of different data tales& Teradata)designed for data warehousing) emphasies the importance of creating tales easily)effecti+ely) and efficiently& Teradata re/uires only that you ha+e 4ermanent space and utiliethe CR0T0 tale statement&

Ta!le Considerations ll relational dataase systems store rows in tales& s mentioned in chapter one) a tale isa two dimensional array that consists of rows and columns& Rows represent an entity withinthe dataase& row consists of columns that permit the storage of +alues needed within therow&

Regarding the storage of rows) relational theory states that the order or se/uence of rowsand columns in a tale should e aritrary& ,n other words) the storage order does not matter for rows or the arrangement of columns within a row& ou are) howe+er) only allowed onerow format per tale& lthough it makes no difference what se/uence the columns are in)once you pick a format) all rows contain the same columns in the same se/uence&

Columns within a row must ha+e a uni/ue name within the tale and a data type& 2ith thesetwo pieces of information) the dataase can store) manage) retrie+e and utilie the data&

Page 319: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 319/401

2hen it comes to character data) it may e fi.ed or +ariale in length& The nice thing aout+ariale length character data is that it can sa+e disk space&

Some dataase systems re/uire that all fi.ed length columns appear at the front of the rowand the +ariale length columns at the end& This is not true for Teradata& ,t automaticallyplaces +ariale length and null*ale columns at the end of the row internally and on disk&=owe+er) for display purposes) all columns appear in the order in which they are defined inthe CR0T0 T#L0 statement& This is one less restriction to worry aout with Teradata&

Ma.imum Columns per Ta!le

  Teradata tale may contain a ma.imum of 8E columns& -or most dataaseimplementations) this limit is more columns then needed for a usiness application& Consider this) if each column is 1 yte long) they cannot e displayed as an entire row ecause thenormal printer can only print 18 characters per line&

3riginally) Teradata only allowed 9 columns during the creation of a tale& Still today) , ha+eseen sites that follow this old restriction& They create the tale with 9 columns and thenalter the tale se+eral times to reach the desired numer of columns& ,f you find yourself 

changing old ""L and see this situation) simplify your life and e+eryone else's y doing it allin a single statement& Iet it right the first time?

Teradata also has a limit of 18 columns o+er a tale's lifetime& Therefore) if a tale has 8Ecolumns) the LT0R T#L0 statement can e used to drop and replace up to 8E columns&3nce you reach the 18*column limit you must create a new tale to continue dropping andadding columns& ,f this happens) it pro+es that not enough planning went into the originaldesign of the tale& Try not to follow the philosophy of) ;There is not enough time to do itright) ut plenty of time to redo it later&;

Ta!le Naming Con<entions

There are certain considerations to take into account when naming tales& Thefollowing outline enumerates them:No two dataases or users may ha+e the same name in the entire system&No two tales in the same dataase may ha+e the same name&

No two columns in the same tale may ha+e the same name&  tale can e a ma.imum of 9 characters& These include:

o 5ppercase and lowercase alphaetic characterso ,ntegers

o These special characters: W \ [

C"EATE TABLE

The CR0T0 tale statement estalishes the name of the tale) a name of each column inthe tale) its data type and any data attriutes& ,t also defines the 4rimary ,nde. for the tale&,n addition) you may specify data protection features) data attriutes and constraints thatdictate data /uality&

The following is the synta. for using CR0T0 T#L0:

CR0T0 Ktale*typeO T#L0 Kdataase*name&OKtale*name

) Ktale*le+el*attriutes O

Page 320: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 320/401

2,T= @35RNL T#L0 M Ktale*name O

! Kcolumn*definition*attriute*list %

Ktale*le+el*constraints O

H

or CT Kdataase*name&OKtale*name

) Ktale*le+el*attriutes O

2,T= @35RNL T#L0 M Ktale*name O

! Kcolumn*definition*attriute*list %

Ktale*le+el*constraints O

H

2hen you use the CR0T0 T#L0 command Teradata uses this to define a tale o(ect inthe "ata "ictionary !""% for the storage of rows& ,t inserts a row into the "#C&T<$ !Tale)<iew) $acro% tale for the tale nameH one row per column is inserted into the "#C&T<-ields

tale and a row for implicit user rights is inserted into the "#C&ccessRights tale&

The following CR0T0 T#L0 statement uilds a tale definition for a tale calledemployee:

CR0T0 Tale employee

!

emp  ,NT0I0R

Jdept  ,NT0I0R

Jlname  C=R!89%

J,name  <RC=R!89%

Jsalary  "0C,$L!19)8%

Jhire7date  "T0

%

'NI-'E P"IMA"Y INEQ(emp)=

The tale created ao+e is designed to show a simple e.ample& The tale now e.ists as aheader on each $4 in the system& Teradata is now ready for you to load the data and runthe /ueries& Lets discuss the ao+e fundamentals in detail&The tale called employee  is composed of si. columns !emp) dept) lname) fname) salary)and hireWdate%& 0ach column is assigned a data type that defines and controls the internalrepresentation of the data stored there& The emp  and dept columns ha+e a data type of INTE8E"& n integer is a 7*yte column that uses signed inary to represent numersranging from *8)17D)7B)E7B to 8)17D)7B)E7D&The lname is the ne.t column and it is defined as C;A"(96)& There are two pieces hereHThe C;A" piece tells Teradata to e.pect character data and the (96) reflects the numer of ytes to reser+e for this column's data +alues& Character data stores letters) numers) andspecial characters& The system will reser+e 89 ytes to store this data no matter if the actualdata entered is one character or 89& ,f the +alue entered takes up less than the full 89spaces then Teradata will pad the remaining ytes with spaces& ,f someone has a name of ]Coffing^ the system will internally store Coffing and 1 spaces&The ,name is defined as A"C;A"(96) This means that the fname is stored internally as a+ariale length character that could reach a ma.imum of 89 characters& ,n addition) a two*

Page 321: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 321/401

yte <ariale Length ,ndicator !<L,% is stored to indicate the actual length of each +aluecontained in this column& The name ]Tom^ is stored as characters and has a <L, indicatingthe length of this column is *ytes& ,ncluding the 8*yte <L, the internal storage is *ytesfor the column holding ]Tom^ and E*ytes for the column holding ]$ike^& Teradata handles thestorage representation transparently to the user&The salary column is defined as ECIMAL(06J9) This means that salary will represent anumer that can ha+e up to ten digits total with two of the digits eing to the right of thedecimal& Therefore) the largest +alue it can store is AA)AAA)AAA&AA& dditionally) if youentered a salary of D999 the system would see this as D thousand dollars& ,f you entered asalary of B999&9 it would represent B thousand dollars and 9 cents& ,t always aligns onthe decimal) whether literally present or assumed as &99 in the ao+e +alue of D999&The last column in our e.ample is named hire7date and this column represents a date&Teradata ill internally store the date as an integer ) ut recognie that integer as a date&-or more information aout dates see chapter B&

Column ata TypesTeradata currently supports NS, data types as well as Teradata e.tensions& The first chartelow !-igure 1B*1% shows the NS, standard types and the second chart !-igure 1B*8% is for the additional data types that are allowed as Teradata e.tensions&

%igure 0G10 

%igure 0G19 

This chart indicates which data types that Teradata currently supports as NS, Standards:

This chart indicates which data types that Teradata currently supports as e.tensions:

Page 322: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 322/401

The first e.ample was designed to show the CR0T0 T#L0 statement and a simplee.planation of the column types& Teradata also allows you to:

0.plicitly name the dataase where the tale will reside Create the tale as a S0T or $5LT,S0T tale "efine the protection methodologies such as -LL#CJ or @35RNL,NI "efine the internal row storage in #L3CJS and -R00S4C0

-urther define column attriutes "efine C3NSTR,NTS "efine S0C3N"R ,N",C0S "efine "0-5LT <L50S

0ach will e discussed in detail&

&peci,ying the ata!ase in a C"EATE TABLE &tatement

Someone once said) ;Life is like a eautiful melody) only the lyrics are messed up;& Since wedid not specify a dataase in the pre+ious e.amples) the system defaults to the currentdataase for the CR0T0 T#L0 statement& Sometimes this is when the lyrics get messedup& To ensure your tale is placed in the intended dataase it is a good idea to /ualify thedataase name in the CR0T0 statement&

=ere is the same e.ample again) with one change& The employee tale is created in thedataase called TomC&

CR0T0 Tale TomC&employee

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 %5N,Q50 4R,$R ,N"06!emp%H

P"IMA"Y INEQ considerations3ur e.amples ha+e had a tale le+el constraint of 'NI-'E P"IMA"Y INEQ ('PI) on thecolumn called emp& ou must select a 4R,$R ,N"06 for a tale at T#L0 CR0T0 timeor Teradata will choose one for you& There are two types of 4R,$R ,N"060S& They are5N,Q50 and N3N*5N,Q50 and are referred to as 54, and N54, !pronounced ]you*pea^and ]new*pea^%& 2e ha+e seen an e.ample of a 5N,Q50 4R,$R ,N"06 !54,%& Let usshow you an e.ample of a N3N*5N,Q50 4R,$R ,N"06!N54,%&

CR0T0 Tale TomC&employee

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

Page 323: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 323/401

)hireWdate "T0 %

P"IMA"Y INEQ!dept%H

Teradata also allows for multicolumn 4rimary ,nde.es) ut only allow up to 1E cominedcolumns ma. to represent the 4rimary ,nde.& =ere is an e.ample of a multicolumn 4rimary,nde.&

CR0T0 Tale TomC&employee

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 %

P"IMA"Y INEQ!emp) dept) lname%HThe data +alue stored in the column!s% of the 4R,$R ,N"06 !4,% is used y Teradata tospread the rows among the $4s& The 4rimary ,nde. determines which $4 stores an

indi+idual row of a tale& The 4, data is con+erted into the Row =ash using a mathematicalhashing formula& The result is used as an offset into the =ash $ap to determine the $4numer& Since the 4, +alue determines how the data rows are distriuted among the $4s)re>uesting a ro using the PI <alue is alays the most e,,icient retrie<al mechanism,or Teradata&,f you don't specify a 4, at tale create time then Teradata must chose one& -or instance) if the ""L is ported from another dataase that uses a 4rimary Jey instead of a 4rimary,nde.) the CR0T0 T#L0 contains a 4R,$R J0 !4J% constraint& Teradata is smartenough to know that 4rimary Jeys must e uni/ue and cannot e null& So) the first le+el of default is to use the P"IMA"Y 2EY column(s) as a 'PI ,f the ""L defines no 4R,$R J0) Teradata looks for a column defined as 5N,Q50& s asecond le+el default) Teradata uses the ,irst column de,ined ith a 'NI-'E constraint asa 'PI 

,f none of the ao+e attriutes are found) Teradata uses the ,irst column de,ined in  thetale as a N3N*5N,Q50 4R,$R ,N"06 !N54,%&

The ne.t CR0T0 T#L0 statement uilds a tale definition for a tale called employee) utdoes not define a 4rimary ,nde.& 2hich column do you think it will choose

CR0T0 Tale employee

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 % HSince there is no 4, listed) Teradata must chose one& The re/uest does not define a 4J nor is there is a 5N,Q50 constraint& s a result) Teradata utilies the first column !emp% as aN'PI& 2e suggest you always name the 4, specifically in the ""L& That way there is noconfusion aout what column!s% are intended to e the primary inde.&

Page 324: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 324/401

Ta!le Type &peci,ications o, &ET & M'LTI&ET

There are two different tale type philosophies so there are two different type tales& Theyare S0T and $5LT,S0T& ,t has een said) ; man with one watch knows the time) ut a manwith two watches is ne+er sure;& 2hen Teradata was originally designed it did not allowduplicate rows in a tale& ,f any row in the same tale had the same +alues in e+ery column

Teradata would throw one of the rows out& They elie+ed a second row was a mistake& 2hywould someone need two watches and why would someone need two rows e.actly thesame This is S0T theory and a S0T tale kicks out duplicate rows&The NS, standard elie+ed in a different philosophy& ,f two rows are entered into a tale thatare e.act duplicates then this is acceptale& ,f a person wants to wear two watches then theyproaly ha+e a good reason& This is a $5LT,S0T tale and duplicate rows are allowed& ,f you do not specify S0T or $5LT,S0T) one is used as a default& =ere is the issue: the defaultin Teradata mode is &ET and the default in AN&I mode is M'LTI&ET&

Therefore) to eliminate confusion it is important to e.plicitly define which one is desired&3therwise) you must know in which mode the CR0T0 T#L0 will e.ecute in so that thecorrect type is used for each tale& The implication of using a S0T or $5LT,S0T tale isdiscussed further&

&ET and M'LTI&ET Ta!les

  S0T tale does not allow duplicate rows so Teradata checks to ensure that no two rows ina tale are e.actly the same& This can e a urden& 3ne way around the duplicate row checkis to ha+e a column in the tale defined as 5N,Q50& This could e a 5ni/ue 4rimary ,nde.!54,%) 5ni/ue Secondary ,nde. !5S,% or e+en a column with a 5N,Q50 or 4R,$R J0constraint& Since all must e uni/ue) a duplicate row may ne+er e.ist& Therefore) the checkon either the inde. or constraint eliminates the need for the row to e e.amined for uni/ueness& s a result) inserting new rows can e much faster y eliminating the duplicaterow check&

=owe+er) if the tale is defined with a N54, and the tale uses S0T as the tale type) now a

duplicate row check must e performed& Since S0T tales do not allow duplicate rows acheck must e performed e+ery time a N54, "54 !duplicate of an e.isting row N54, +alue%+alue is inserted or updated in the tale& "o not e fooled? duplicate row check can e a+ery e.pensi+e operation in terms of processing time& This is ecause e+ery new rowinserted must e checked to see if it is a duplicate of any e.isting row with the same N54,Row =ash +alue& The numer of checks increases e.ponentially as each new row is addedto the tale&

2hat is the solution There are two: either make the tale a $5LT,S0T tale !only if youwant duplicate rows to e possile% or define at least one column or composite columns as5N,Q50& ,f neither is an option then the S0T tale with no uni/ue columns will work) utinserts and updates will take more time ecause of the mandatory duplicate row check&

#elow is an e.ample of creating a S0T tale:

CR0T0 S0T Tale TomC&employee

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

Page 325: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 325/401

)hireWdate "T0 %

'NI-'E 4R,$R ,N"06!emp%HNotice the 5N,Q50 4R,$R ,N"06 on the column emp& #ecause this is a S0T tale it ismuch more efficient to ha+e at least one uni/ue key so the duplicate row check is eliminated&

The following is an e.ample of creating the same tale as efore) ut this time as a

$5LT,S0T tale:CR0T0 M'LTI&ET T#L0 employee

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 %

P"IMA"Y ,N"06!emp%HNotice also that the PI is no a N'PI ecause it does not use the word 5N,Q50& This is

important? s mentioned pre+iously) if the 54, is re/uested) no duplicate rows can einserted& Therefore) it acts more like a S0T tale& This $5LT,S0T e.ample allows duplicaterows& ,nserts will take longer ecause of the mandatory duplicate row check&

Protection %eatures

The data warehouse of today is ;mission critical; and protecting the data can ecome amission& ;2hat goes up must come down Y (ust ask any system administrator&; , wasrecently on a plane when , heard the words) ;,n case of a water landing your seat cushionwill act as a floating de+ice&; 4ersonally) this is not my idea of protection? s comedianSte+en 2right once said) ;2hy don't they make the whole plane out of that lack o. stuff;Teradata gi+es you a lot more assurance than a floating seat co+er in shark infested waters&,n fact) Teradata protects the data in numerous ways and has no single point of failure&These features are uilt directly into the dataase and can e assigned at the tale le+el&

 ttriutes can e assigned within a tale to pro+ide a +ariety of protection features andstorage characteristics& lthough each of these has a default at the system le+el) they can eo+er*ridden at the time a tale is created& This section discusses and demonstrates thesefeatures&Teradata allows you to specify which data protection features to use for a tale& Thesefeatures include %ALLBAC2  and Permanent Sournaling& They can also e added or modified after the tale has een created using the LT0R command) which is discussedlater in this chapter&

%ALLBAC2-LL#CJ re/uests that a second copy of each row inserted into a tale e stored onanother $4 in the same cluster& This is done in case the $4 goes down or the disks fail&There are usually four $4s grouped together in a cluster& -LL#CJ allows for processingto continue in the e+ent that an $4 is lost& As a matter o, ,actJ %ALLBAC2 allos ,or theloss o, one AMP in each cluster  cluster is normally comprised of two or four $4s thatwork together&

-LL#CJ pro+ides an e.tra insurance policy that guarantees data a+ailaility in case an $4 is lost& =owe+er) as with all insurance policies) there is a cost& The cost for -LL#CJ

Page 326: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 326/401

is that twice as much disk storage space is used for row storage as compared to not using-LL#CJ& The cost is also twice the ,F3 on inserts) updates) and deletes ecause thereare always two copies to write& 3ne copy goes to the primary $4 where it elongs and theother copy goes to different $4 in the same cluster& The good news is that Teradata $4soperate in parallelH so) it does not take twice as long to store a duplicate row& #oth rows areplaced on their respecti+e $4s at nearly the same time&

-LL#CJ is an optional feature& ou can use -LL#CJ protection on all tales) notales) or some tales& -LL#CJ is usually created on important tales that are missioncritical& Therefore) the "" is automatically -LL#CJ protected& -allack is a great featureto ensure e.tra protection on important data that needs to e readily a+ailale&

=ere is an e.ample of a tale created with -LL#CJ&

CR0T0 S0T T#L0 employee) %ALLBAC2

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 %

'NI-'E P"IMA"Y INEQ!emp%H

=ere is another e.ample that e.plicitly states N3 -LL#CJ

CR0T0 &ET T#L0 employee) N$ %ALLBAC2

! emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 %

'NI-'E P"IMA"Y INEQ(emp)=

Teradata naturally defaults to N3 -LL#CJ& #ecause these protection features can eassigned at the dataase or user le+el it can e a good idea to e.plicitly state whether or notyou want -LL#CJ& 2hen in dout spell it out?

Permanent Sournal

-allack is different than the 4ermanent @ournal& 2here -LL#CJ has a duplicate copy of 

all rows in a protected -LL#CJ tale) permanent (ournaling in+ol+es keeping an audit trailof all new) deleted or changed data& -or e.ample) if a tale has one million rows and isfallack protected then there are one million fallack rows& ,f a 4ermanent @ournal is usedinstead of -LL#CJ) the only rows copied to the (ournal are for the inserts) updates) anddeletes since the last @35RNL ackup& Therefore) in most cases this is far less e.pensi+ethan storing the additional one million rows needed for fallack& 4lus) you can tailor your @35RNL with specific options& ,t is called a 4ermanent @ournal ecause the rows staythere until the user deletes them& The user deletes them when they ha+e een acked up totape& This is the philosophy of the 4ermanent @ournal&

Page 327: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 327/401

@ournal options are: BE%$"E S$'"NAL * captures an image of a tale row efore it changes A%TE" S$'"NAL * captures an image of a tale row after it changes 'AL BE%$"E S$'"NAL * captures two images of a tale row efore it

changes and stores the images on two different $4s 'AL A%TE" S$'"NAL  Y captures two images of a tale row after it

changes and stores the images on two different $4s

,f a tale is -LL#CJ protected the (ournal is also -LL#CJ protected& =owe+er) the N3"5L option can e added to allow the tale to use -LL#CJ and the (ournals not toutilie -LL#CJ&

#esides the "5L option on the @35RNL tale) you can also re/uest L3CL or N3TL3CL& These are in reference to the $4 used in respect to the data row& L3CL puts the

 (ournal entry on the same $4 as the data row& The default is N3T L3CL for minimiingthe loss of data rele+ant to the loss of an $4&

4ermanent (ournals are optional& They can e used for all tales) no tales) or some tales&There is one purpose for a #0-3R0 (ournal and a different purpose for an -T0R (ournal&The #0-3R0 (ournal is designed to perform a manual rollack in case of a programmingerror& n -T0R (ournal is designed to perform a manual roll forward in the e+ent of ahardware failure that causes data to e lost on disk& Lets discuss oth of these scenariosusing two e.amples&

BE%$"E SournalTo e.plain (ournaling) lets say that the 0$4L300 tale is created with a #0-3R0 (ournal&Then) a programmer is told to gi+e e+ery employee a U raise& ,nstead) e+ery employee isaccidentally gi+en a 9U raise& #ecause there is a #0-3R0 (ournal you ha+e the aility tomanually rollack the data to a point in time #0-3R0 the employee update to correct theprolem& s you can see) a BE%$"E Sournal might !e used to roll!ac+ a programmingerror 

A%TE" Sournal

Lets look at an -T0R (ournal e.ample& Lets say management has decided not to use-LL#CJ on any tales& They ha+e concluded that the data is not mission*critical and itcan e restored from ackup tapes in a reasonale time frame) if necessary& To make surethe system is acked up a -5LL SST0$ #CJ54 is performed on the first day of eachmonth& 4lus) an -T0R @35RNL has een defined on all the tales in the system& 0+erytime a new row is added or a change is made to an e.isting row) Teradata captures the

 -T0R image& Then) a hardware failure occurs on the th day of the month and the data islost&To reco+er) you fi. the hardware prolem) and then reload your data from the -5LL SST0$#CJ54 done at the 1st of the month& Then apply your -T0R @35RNL to restore therows that were added or changed from the 1 st to the th day of the month& &oJ as illustrated

hereJ you can use an A%TE" S$'"NAL to roll data ,orard  This is usually done torestore data lost due to a hardware prolem&

The following e.ample shows the use of the 40R$N0NT @35RNL:

CR0T0 T#L0 TomC&employee) -LL#CJ

BE%$"E S$'"NALJ

'AL A%TE" S$'"NAL

! emp ,NT0I0R

Page 328: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 328/401

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0 %

5N,Q50 4R,$R ,N"06!emp%H

This e.ample has created the tale called employee in the TomC dataase& 2e ha+e chosena #0-3R0 @35RNL and a "5L -T0R @35RNL& @ournaling has a natural default of N3& That means if you don't specify this protection at either the tale or dataase le+el thedefault is N3 @35RNL,NI&

Jnowing what you now know from the pre+ious paragraph) how many times do you think the -T0R @35RNL row will e stored on disk

The answer is 7 times& This is ecause the tale is -LL#CJ protected) so the (ournals arealso -LL#CJ protected& Therefore) ecause the -T0R @35RNL is "5L each changeto a row is stored twice) and two more times ecause oth "5L entries are also

-LL#CJ protected&

 s you soon realie) -LL#CJ with "5L (ournaling can e +ery e.pensi+e in terms of disk space) e+en more so than -LL#CJ y itself&

Internal &torage $ptions

  frustrated 4C user was once /uoted as saying) ;2ho's Ieneral -ailure and why's hereading my disk; $ost people don't know what is going on inside the disks and in mostcases (ust don't care& ,n a data warehouse en+ironment ha+ing the aility to influence howdata is stored inside the disks can e a great ad+antage& Some tales will e utilied yapplications designed to read millions of records while others will operate in an 3LT4 typeen+ironment where updating single records is the focus&

Teradata gi+es the tale creator the aility to influence how the data is stored on the disk&The two optional tale le+el attriutes are "T#L3CJS,Z0 and -R00S4C040RC0NTI0& ,f either of these options is not specified in the CR0T0 T#L0) they defaultto +alues estalished in the "#C Control record at the system le+el& 5nless you are aTeradata e.pert let the system defaults do their (o& =owe+er) if you can understand theconcepts that are aout to e e.plained) as well as your application re/uirements) you cancustomie your disk en+ironment to ma.imie effecti+eness&

ATABL$C2&IE

The "T#L3CJS,Z0 determines a ma.imum lock sie for multiple row storage on disk&The data lock is the physical ,F3 unit for the Teradata file system& Larger lock siesenhance full tale scan operations y retrie+ing more rows in a single ,F3& Smaller locksies are est for on*line transaction*oriented tales to minimie o+erhead y retrie+ingsmaller locks& ou can specify this numer in #T0S) J,L3#T0S or J#T0S& #T0Sspecifications are rounded to the nearest sector of 18 #T0S& J#T0S and J,L3#T0Sare in set increments of 1987 #T0S&

Teradata is designed to take ad+antage of "T#L3CJS,Z0 settings ecause of theunpredictale nature of the data warehouse en+ironment& 2hile most dataases ask that

Page 329: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 329/401

you define tale space Teradata does not& This is ecause Teradata uses +ariale lengthlocks& This means that when a tale is small it is allocated a few disk sectors at 18 yteseach& Then) as the tale grows) the numer of sectors used y the lock grows with the newrows until it reaches the ma.imum lock sie& ,t is like a alloon& s more air is inserted) thealloon e.pands& 0+entually the alloon gets to the ma.imum sie and the only way to sa+emore air is to get a second alloon&

Teradata's +ariale lock design allows the system to handle the space instead of makingthe "# do it& The "T#L3CJS,Z0 is the setting that determines when it is time to getadditional locks !alloons%& 3n large data warehouse applications that read millions of rowsit is est to ha+e a few ig alloons& 3n applications that update on one or two records at atime it is etter to ha+e many smaller alloons&

,f "T#L3CJS,Z0 is not specified) the sie used is a default of either 88E !E sectors%or E987 !18D sectors%) depending on the cylinder sie setting& Cylinder sie is a system*le+el +alue shown as Sects4erCyl with the -iler utility or Numer of "isk #locks 4er Cylinder with the pdeconfig utility& 4rior to <8R&9 the default cylinder setting was 17BB sectors& 2ith<8R&9) the sie increased the default cylinder setting to BD8 sectors&

 dditionally) the lock sie is only the ma.imum when there is more than one row in a lock&

,f a single row e.ceeds the "T#L3CJS,Z0 setting it is stored in its own data lock& Thelock will e the length of the row and rows are ne+er split into multiple data locks&

$,N,$5$ "T#L3CJS,Z0 sets the minimum or smallest data lock sie for locks thatcontain multiple rows to the minimum legal +alue of either E177 or D1EB ytes !18 sectors or 17 sectors%) depending on the cylinder sie setting in the "#S Control Record& ou can usethe keywords of $,N,$5$ "T#L3CJS,Z0 or $,N "T#L3CJS,Z0 to change thedefault&

$6,$5$ "T#L3CJS,Z0 is the largest possile "T#L3CJS,Z0 setting for the tale)which is E987 ytes !18D sectors%& ou can use the keywords $6,$5$"T#L3CJS,Z0 or $6 "T#L3CJS,Z0 to change the default&

Normally) larger lock sies re/uire less physical disk space& This is ecause large lockscontain more rows& Therefore) fewer locks are needed and since each lock re/uires alock header and control data) less space needs to e allocated for them&

%"EE&PACE PE"CENTA8EThe -R00S4C0 40RC0NTI0 tells the system at what percentage Teradata should keepa cylinder free of rows on data loads when using %astload and Multiload load utilities& -R00S4C0 19 40RC0NT keeps 19U of a cylinder's sector space free when loading thedata& <alid +alues for the percentage of free space range from 9*D&

The +alue used for -R00S4C0 should mimic the usage of the tale& s the numer of rows eing inserted y clients) other than -astload and $ultiload increases) the +alue of -R00S4C0 might also increase& This causes the secondary row inserts to e.ecute faster 

ecause space is already a+ailale on disk to store the new rows in the same cylinder&Therefore) fewer cylinder splits will occur as a result of insufficient space at insert time& ,nother words) we don't low the ;alloon; all the way up& 2e know we will e utiliing SQL todo more inserts and we want e.tra room for the alloon to e.pand&

3n the other hand) if the tales only recei+e rows loaded y -astload and $ultiload) the-R00S4C0 +alue can e set to 9 for ma.imum utiliation of the disk space within eachcylinder since inserts are not performed y other clients& ,f we are not going to use SQLcommands to insert additional data we can low the alloon all the way up ecause it won'tneed to e.pand any further&

Page 330: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 330/401

Since these parameters ha+e defaults kept in system parameters as part of the "#S Controlrecord) they are seldom used in the CR0T0 T#L0 statement) ut Teradata gi+es you theoption of o+er*riding the default on any particular tale&

The following CR0T0 T#L0 specifies -LL#CJ and estalishes +alues for oth"T#L3CJS,Z0 and -R00S4C0:

CR0T0 Tale TomC&employee) -LL#CJ)ATABL$C2&IE?0@G BYTE&J

%"EE&PACE ? 96 PE"CENT

!

emp ,NT0I0R

)dept ,NT0I0R

)lname C=R!89%

)fname <RC=R!89%

)salary "0C,$L!19)8%

)hireWdate "T0

%

5N,Q50 4R,$R ,N"06!emp%H

 s pre+iously mentioned) if you don't specify a "T#L3CJS,Z0 or -R00S4C040RC0NT then the system uilds the tale using the default parameters for "T#L3CJS,Z0 and -R00S4C0 40RC0NT found in the "#S Control Record& Ne+er specify these without a discussion with your dataase administrator& Rememer) to changeand to change for the etter are two different things& ,f you don't know it Y don't low it?

Column Attri!utes

 lfred North 2hitehead once said) ;2e think in generalities) ut we li+e in details;& 2e ha+eseen e.amples in this chapter of creating tales with simple column definitions& Thesee.amples ha+e een generalities) ut often we need to model our columns in great detail& ,tis time to take the ne.t step& 2hen defining a tale it is normally ad+antageous to e morespecific regarding the definition of the columns and their attriutes&

%igure 0G1@ 

The ne.t CR0T0 T#L0 uilds a tale definition with attriutes&

CR0T0 Tale TomC&employee

Page 331: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 331/401

!

emp ,NT0I0R

)dept ,NT0I0R N$T N'LL

)lname C=R!89% N$T CA&E&PECI%IC

)fname <RC=R!89% TITLE K%I"&T NAMEK

)salary "0C,$L!19)8% %$"MAT KJJHHHK

)hireWdate "T0 %$"MAT KmmmBddJByyyyK

)#yteWcol #T0!19% compress K666666K.!

% 5N,Q50 4R,$R ,N"06!emp%H,n the ao+e e.ample the columns ha+e een further defined using column attriutes& Thedept column is defined with the N$T N'LL attriute& This means that a N5LL +alue cannote stored in the dept column&The lname column has een further defined to state that for comparison purposes) the datais not casespecific& This means that it does not matter if the data is in upper case) lower case) or a comination&The ,name column has a T,TL0 associated with it& So) whene+er it is selected) ]-,RST

N$0^ appears as the report heading instead of the column name&The salary column is automatically formatted as currency in the output when selected using#T0Q&The hire7date is also formatted& ,t displays as the alpha month followed y the numeric dayand 7*digit year&Lastly) the Byte7Col column is added& ,t is a yte column with a length of 19& The e.ampleshows how to initialie it with a +alue of ero& ,t is pro+ided as a he.adecimal numer usingthe . designation& This designation would also e a +alid comparison for retrie+al of therow& Notice the word compress&This compress does not mean we are going to use 2,NZ,4 to shrink the column& Compressallows you to take one specific +alue and store the default in the tale header& Let mee.plain& Lets say the "ept of $otor <ehicles in California has a dataase that tracks allpeople with a California dri+er's license& round AA&AU of the dri+ers would ha+e Californiaas their state code on their address& ,nstead of storing ;CL,-3RN,; in millions of records

the compress will store the +alue ;CL,-3RN,; in the tale header& Now) a +alue can eassumed in a row as a default unless another +alue e.ists inside the column&

Constraints

3ne of our est Teradata training customers has a data warehouse with o+er 79)999 users&0+en though their enterprise data warehouse may span continents) the data warehouseReturn 3n ,n+estment game is played on a field that is inches wide& The space etweenthe users ears? ,t is the users that make the data warehouse great& 2hen users gaine.perience and use intuition) imagination) and e.perience they can find the company igdollars& 2hen 5sers can ask any /uestion) at any time) on any data) the oundaries are

unlimited&But sometimes !oundaries are necessary] t times it is ad+isale to add restrictions tothe tale and columns within a tale& This is done to pro+ide data integrity) a+ailaility andease of use to the tale and its data& 5sers can still use their imagination and ask any/uestion) ut on all inserts) updates) and deletes Teradata will e watching&

Relational theory descries columns and the attriutes a column can ha+e as part of adomain& The domain includes the data type and +alid +alue oundaries ased on usinessre/uirements or restrictions& #ecause NS, does not support a rigorous atomic definition of adomain) it is up to the dataase designer to define the domains for a tale and their legal

Page 332: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 332/401

+alues y creating constraints on one or more columns& Constraints keep the tale in checkto enforce certain rules&

Think of domains as standards& ,f e+eryone in the company tracking information aoutemployees sets up the employee numer as an integer ranging from 1 Y 199)999)999 thenwhen there is cross functional analysis across usiness units each will see employeenumer as an integer& Comparisons will e easy& $ake columns with the same functions thee.act same data types !with the same range% and your columns are said to e from thesame domain&

Teradata has some fundamental rules aout constraints: lways name tale le+el constraintsConstraint names can e up to 9 charactersConstraint names must e uni/ue among all other constraint names defined for a

taleConstraints can e specified at the column or tale le+el

The system does not assign names to constraints you do not name

ou also ha+e the aility to define constraints on column +alues during the CR0T0 Taleprocess& This can also e done using the LT0R command once the tale has een created&Constraints generally fall into three areas:

5ni/ueCheckReferential ,ntegrity

Constraints are defined at the column or tale le+el&

%igure 0G1 

%igure 0G1D 

'NI-'E ConstraintThe great writer $ark Twain was /uoted as saying) ;2hene+er you find you are on the sideof the ma(ority) it is time to pause and reflect&; Sometimes it is good to e on the side of thema(ority) ut at other times it is est to e 5N,Q50& The 'NI-'E constraint is used toenforce uni/ueness of +alues stored within the column!s%& This means that no two rows in

the tale can ha+e the same +alue for the column or columns utiliing the 5N,Q50constraint&

 n employee numer is an e.cellent e.ample& 0ach employee must ha+e an employeenumer) and no two employees can e+er ha+e the same employee numer& t the sametime) we must ensure that no employee has N'LL data  for their employee numer& TheTeradata system enforces the uni/ueness y making a column with the 'NI-'E constrainta 'ni>ue &econdary Inde. ('&I)& Teradata makes the column a 5ni/ue 4rimary ,nde.!54,% only if during the T#L0 CR0T0 statement no 4rimary ,nde. or 4R,$R J0 ise.plicitly stated&

Page 333: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 333/401

2hen a tale is created using this constraint) rows containing duplicate +alues cannot estored in the tale& ,f the tale is not created using a 5N,Q50 constraint and it is later alteredto add the constraint) if the data is not uni/ue the LT0R statement fails ecause the data+iolates the constraint&

C;EC2 Constraint0+en 2ayne Iretky) the greatest hockey player e+er missed a check on occasion) utTeradata will not? The C;EC2 constraint allows for a range of +alues to e checked or for specific +alue limits to e placed on a column& -or e.ample you can check that a column+alue falls within a certain range such as 0$4 #0T200N 1 N" AA& ou can also check tosee that a column +alue is greater than another column or +alue& s an e.ample: C=0CJ0$4 9& ou can also C=0CJ 0$4 "04T& ou can e+en utilie a compound check like0$4 #0T200N 1 N" AA N" 0$4 "04T&

2hen a tale is created using this constraint) rows containing in+alid +alues cannot eentered into the tale& ,f the tale is altered later on with a C=0CJ) and the data is not +alidfor the constraint) the LT0R statement fails since the data +iolates the constraint&

"e,erential Integrity ("I) Constraint

Referential ,ntegrity !R,% insists that a row cannot e inserted unless the +alue in the columnhas a corresponding +alue e.isting in another tale& This also means a row cannot edeleted if a corresponding +alue in another tale still e.ists& -or e.ample) imagine gettingfired and your employer deletes you from the employee tale) ut forgets to delete you fromthe payroll tale& R, check can e used to enforce data integrity and pre+ent this scenario&Referential ,ntegrity does not allow anyone to e deleted from the employee tale unlessthey were already deleted from the payroll tale& "arn) R, can hurt your #ahamas retirement&

2hen R, is estalished on a new tale) in+alid data +alues cannot e entered into a column&=owe+er) if a tale is altered to egin enforcing R,) the data might already e incorrect&2hen this happens) the LT0R creates a copy of the original tale and stores rows in it that+iolate the R, constraint& ,t is up to you to look for the tale copy and correct any errors in the

actual tale& R, is the only constraint that can e added with data that +iolates the constraint&

e,ining Constraints at the Column le<el

,t is possile to estalish the constraint directly on the column definition& ,t makes for an easydefinition process& =owe+er) it does spread the +arying constraints throughout the ""Lstatement& Sometimes the CR0T0 T#L0 can e +ery large? This makes the constraints ait more difficult for people to find& 2e ha+e seen constraints placed at the column le+el on""L so large that $agellan couldn't find his way through it&

The other issue for a column le+el definition is that only one column can e in+ol+ed& Sincesome constraints may in+ol+e multiple columns) these definitions must e defined at thetale le+el and not the column le+el& #oth le+els are co+ered in this section&

=ere is an e.ample of creating a tale with column le+el constraints:

CR0T0 Tale TomC&employee

! emp ,NT0I0R N$T N'LL

  C$N&T"AINT EmpP2 P"IMA"Y 2EY

)dept ,NT0I0R C$N&T"AINT "e,70 "E%E"ENCE& epartment(dept)

  BET:EEN 06 AN 066

Page 334: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 334/401

)lname C=R!89% N$T N'LL

)fname <RC=R!89% N$T N'LL

)salary "0C,$L!19)8% C$N&T"AINT &alChec+

  C;EC2 (salary 4?06666 and salary 3 0666666)

)hireWdate "T0

)socWsec ,NT0I0R N$T N'LL

  C$N&T"AINT Name'ni> 'NI-'E ) H,n the ao+e tale) the emp column must ha+e a +alue ecause it cannot e null& ,t also hasa primary key named 0mp4J and therefore) ecomes the 54, of this tale ecause no4rimary ,nde. was e.plicitly defined&The dept  column has an R, constraint named "e,70  on the column called dept  in theepartment ta!le& This means that a dept cannot e entered into the employee tale unlessthat dept e.ists in the department tale& This is referential integrity as its est?There is a C;EC2 constraint called &alChec+ on the salary column and it re/uires thesalary to e at least [19)999&99 up to a ma.imum of [AA)AAA&AA&The last two constraints are on the soc7sec column& -irst) there is the N3T N5LL thatre/uires a +alue to e stored there& Then) the Name'ni> constraint re/uires that the +alue

e different from any other +alue in other rows ecause it must e uni/ue&

e,ining Constraints at the Ta!le Le<el#esides using column le+el constraints) tale le+el constraints can also e used& This is theonly way to implement multi*column constraints& multi*column constraint in+ol+es morethan one column& All ta!le le<el constraints should alays !e named& Tale le+elconstraints are esta!lished a,ter  the column definitions& =ere is an e.ample:

CR0T0 Tale TomC&employee) -LL#CJ

! emp ,NT0I0R N$T N'LL

)dept ,NT0I0R

)lname C=R!89% N$T N'LL

)fname <RC=R!89% N$T N'LL

)sal "0C,$L!19)8%

)hireWdate "T0

)socWsec ,NT0I0R N$T N'LL)

C$N&T"AINT EmpP2 P"IMA"Y 2EY (emp)J

C$N&T"AINT "e,70 %$"EI8N 2EY (dept) "E%E"ENCE& epartment(dept)J

C$N&T"AINT Name'ni> 'NI-'E (lnameJ ,name)J

C$N&T"AINT &al7ept7Chec+ C;EC2 (sal 4? 06666 AN sal 3 066666

  AN dept BET:EEN 06 AN 066)JC$N&T"AINT Name'ni> 'NI-'E (soc7sec) ) =2e feel this type of definition is easier to read and understand than looking for constraintsthroughout the ""L& These constraints are all the same as in the first e.ample) with onee.ception& =ere) the name constraint called Name'ni>  uses a comination of oth the,name and the lname columns to create a 5S,& Notice too that N3T N5LL must still e atthe column le+el&

Page 335: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 335/401

'tiliXing e,ault alues ,or a Ta!le

  default +alue control phrase determines the action to e taken when you do not supply a+alue for a field& "efault +alue control phrases are only +alid when used with the columnsdefined in the CR0T0 T#L0 and LT0R T#L0 statements as well as parameters definedin the CR0T0 $CR3 and R04LC0 $CR3 statement&

  default +alue control phrase determines the action to e taken when you do not supply a+alue for a field& ,nstead of placing a N5LL the system will place the default +alue listed inthe CR0T0 or LT0R tale command& The following rules and guidelines apply to default+alue control phrases:

-ields must e defined in CR0T0 T#L0 and LT0R T#L0 statements

4arameters must e defined in CR0T0 $CR3 and R04LC0 $CR3statements

"efault +alue controls are not  effecti+e for +iews and e.pressions&

The normal default +alue for a field is null unless you specify N3T N5LL&

Teradata allows you to specify default +alues when creating a tale& s seen earlier) thekeyword "0-5LT <L50S can e used in an ,NS0RT& 2hen this is done) any columns

that ha+e default +alues defined in the CR0T0 T#L0 statement use the default instead of a N5LL& ll columns without a "0-5LT phrase defined for them contain a N5LL& =owe+er)if a column does not ha+e a "0-5LT defined and has an attriute of N3T N5LL) an error isreturned and the insert fails&

#elow is an e.ample of a tale with defaults&

CR0T0 T#L0 TomC&"eptW"efaults

! "ept ,NT0I0R E%A'LT 06

)"eptWname C=R!89% E%A'LT K&alesK

)$grW0mp\ ,NT0I0R

%

4R,$R ,N"06!dept%H

2e ha+e now created an empty tale called "eptW"efaults& 2e will now insert data in our ne.t e.ample&

,NS0RT ,NT3 T3$C&"04TW"0-5LTS E%A'LT AL'E&=

2e will now select from the "04TW"0-5LTS tale&

S0L0CT G from T3$C& "04TW"0-5LTSH

1 Row Returned

ept ept7name Mgr7EmpW

19 Sales

C"EATE TABLE to Copy an e.isting ta!le

Confucius taught us ; (ourney of a thousand miles egins with a single step&; The (ourney of the "# copying a tale used to e inefficient and contain too many steps& Teradata <8R7)

Page 336: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 336/401

has taken on the challenge) stepped up to the plate and scored a home run& ,n Teradata<8R7 and eyond) there is a new format that does it all in one easy command&

,t has een modified to create a new tale from the definition of an e.isting tale& The onlydifference etween the tales is the tale*name& ll columns ha+e the same names) datatypes and constraints& ll indices and tale options are also identical&

The new synta. is:

CR0T0 T#L0 Kdataase*name&OKtale*name S

  Kdataase*name&OKoriginal*tale*name

2,T= P "T N3 "T

5N,Q50 O 4R,$R ,N"06 !Kcolumn*list% O

H

Notice the specification of 2,T=& ,t is re/uired and re/uests either the "T or N3 "Tspecification& 2hen "T is re/uested) not only does the system create the new tale) ut italso copies all of the rows and columns from the original tale into the new tale& The N3"T specification means that the original data rows are not to e copied into the new tale&

,t remains empty of rows&

This is nice ecause it is now easier than using the S=32 T#L0 to get the ""L) copyingthe ""L) changing the tale*name and then sumitting the ""L& 4lus) if you do want thedata rows) there is no need to perform a separate ,NS0RTFS0L0CT& 3ptionally) another dataase or user area may e used to /ualify the names of the two tales& Creating andduplicating tales has ne+er een easier? ,n addition) the ;e.isting; tale could e a deri+edtale) ut you proaly want to specify which column or columns to use as the primaryinde.&

Altering a Ta!le

The only thing in life we can consistently count on is change& This is especially true in a datawarehouse en+ironment& s usiness re/uirements change) sometimes it is necessary toreflect those changes into the tales& Teradata allows for modification of a tale at either thetale or column le+el using the LT0R command&

=ere is a list of the tale changes a+ailale to the LT0R T#L0: dd one or more new columns to an e.isting tale& dd new attriutes for one or more columns in a tale&"rop one or more new columns to an e.isting tale&

$odify constraints on an e.isting tale at the column or tale le+el& dd or remo+e -LL#CJ or @35RNL,NI$odify the "T#L3CJS,Z0 or -R00S4C0 40RC0NT

Change the name of a column in an e.isting tale

ou can LT0R a T#L0 at oth the column and tale le+el& tale le+el change includesprotection features or internal storage options such as -LL#CJ) @35RNL,NI)-R00S4C0 40RC0NT) etc& The column le+el allows you to change indi+idual columnattriutes& -or e.ample you might e adding the T,TL0) -3R$T) or another column le+elchange&

The synta. for the LT0R statement is:

 LT0R T#L0 Kdataase*name&OKtale*name

Page 337: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 337/401

) Ktale*le+el*attriutes O

2,T= @35RNL T#L0 M Ktale*name O

"" Kcolumn*name Kdata*type O Kattriute*list O O

"R34 Kcolumn*nameO

"" Ktale*le+el*constraint O

$3",- Ktale*le+el*constraint O

"R34 Ktale*le+el*constraint O

H

The following LT0R modifies the tale to -LL#CJ at the tale le+el:

 LT0R T#L0 TomC&0mployee) %ALLBAC2H

The 0mployee tale in the TomC dataase now has a -LL#CJ copy of each row& ou canalso remo+e -LL#CJ) which is /uick and easy& The system merely places the -LL#CJlocks of a tale on the -ree Cylinder List and the locks are gone& This happensimmediately& =owe+er) adding -LL#CJ to a tale is another story& This change may takea lot of time) depending on the numer of rows in a tale& 2hen you add -LL#CJ thesystem duplicates each row and places that row on another $4 in the same cluster& ouare essentially doing a -ull Tale Scan !-TS% and a copy& ,f you ha+e a million rows in thease tale you are creating and distriuting a million -LL#CJ rows& The good news isthat Teradata does this in parallel?

The following LT0R makes (ournaling changes at the tale le+el:

 LT0R T#L0 TomC&0mployee) N$ BE%$"E S$'"NALJ 'AL A%TE" S$'"NAL=

The 0mployee tale no longer has a #0-3R0 @35NL and now has a "5L -T0R@35RNL&

The following LT0R adds a T,TL0 of ]School^ to one of the e.isting columns:

 LT0R T#L0 TomC&SchoolA SchoolWName TITLE K&choolK=

 lthough the ao+e appears to e adding a column) the SchoolWName column alreadye.ists& 2hen we e.plained Teradata to Sherlock =olmes he found another clue& Sherlocksaid) ;Since the SchoolWName did not contain a data type) it could not possily e adding anew column) ut could only e altering an e.isting column&; Sherlock was impressi+e& , wenton to ask him what type of school he thought this tale held& =e said) ;0lementary my dear;&

ou can make multiple changes to a tale with one LT0R statement& The ne.t re/uestmakes multiple changes to a tale y adding multiple columns&

This e.ample adds -LL#CJ and two new columns !SocWSec and "eptWName% to the

tale 0mployee: LT0R T#L0 TomC&0mployee) %ALLBAC2

A &oc7&ec INTE8E"

JA ept7Name Char(96)=

Notice in the ao+e e.ample that when adding new columns you must specify a data type&

Page 338: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 338/401

The ne.t re/uest makes three changes to the tale& The first is a (ournaling change at thetale le+el& The second is at the column le+el and it drops the column called SocWSec& Thethird change is also at the column le+el& ,t adds a T,TL0 to the column called "eptWName:

 LT0R T#L0 TomC&0mployee) 'AL A%TE" S$'"NAL

"R34 &oc7&ec)

 "" "eptWName TITLE KnameKH

The ne.t re/uest changes the name of a column& The old column name was lname and thenew column name is LastWName&

 LT0R T#L0 TomC&0mployee

"ename lname to LastWNameH

There are some restrictions hen renaming columnsJ they are/A ne column name cannot match any e.isting column name in the same

ta!leThe a,,ected column cannot !e a part o, an inde.

The a,,ected column cannot !e part o, a re,erential integrity constraint

The a,,ected column cannot !e re,erenced in the 'PATE $% clause o, a

trigger 

ropping a Ta!le

The opposite of the CR0T0 T#L0 command is the "R34 T#L0& The "R34 commanddeletes o(ects out of the "ata "ictionary !""% and the data rows inside the tale aredeleted from the system& #e CR0-5L? Ione is gone& So) make sure you are in the correctdataase?

The synta. to drop a tale is:

"R34 T#L0 Kdata*ase*name&OKtale*name

H

To ensure you are dropping the correct tale you can also specify the dataase where thetale resides y /ualifying the tale name with the dataase name&

To drop the tale 0mployee in the dataase TomC you can use this command:

"R34 T#L0 TomC&0mployeeH

ou can use two different SQL commands to accomplish the same thing& The first switchesto the dataase TomC nd the second drops the tale&

"T#S0 TomCH

"R34 T#L0 0mployeeH

#ecause you can ha+e the same tale names in different dataases it is important whenperforming the "R34 function that you are sure you are getting rid of the tale you want todrop&

Page 339: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 339/401

ropping a Ta!le <ersus eleting "os

,n most dataase systems) it is faster to drop a tale than it is to delete of the rows& ,t ise.actly the opposite in Teradata& s mentioned earlier) the delete of all rows of a tale is thefastest thing that Teradata does& So) if you wish to get rid of all of the rows) use the "0L0T0command instead of the "R34 command&

-urthermore) once a tale is dropped it is no longer in the system& The data definition storedin the "" is gone& The access rights to the tale are also deleted from the access rightstale& There are times when a dataase administrator or user drops a tale and creates thetale again to fill it with fresh data& 2hen doing this) the access rights of pre+ious users needto e re*estalished&

This is why you drop a tale when it is no longer needed) ut "0L0T0 the data rows from atale that you want to refresh with new data& tale loaded monthly with new data might fitthis category& This allows the access rights to remain the same& The old data is deleted andthe new data loaded& The access rights are unaffected ecause the data definition in the ""has not changed and the access rights tale is not affected&

 dditionally) since the "R34 re/uires locking the "" for 2R,T0 to drop the tale and deletethe rows) a "0L0T0 for (ust the data rows is faster& "0L0T0 of rows within a tale is fast&,t is much faster than a "R34 ecause a "R34 is actually deleting multiple rows frommultiple "" tales& -or more details on the speed of a "0L0T0 command) see chapter 1 inthis ook&

"enaming a Ta!le

The ne.t capaility discussed here is the aility to rename an e.isting tale& The R0N$0T#L0 command is useful when a tale name needs to e changed&

The synta. of the R0N$0 command:

R0N$0 T#L0 dataase*name&OKtale*name

  T3 dataase*name&OKtale*name

H

=ere is an e.ample:

R0N$0 T#L0 TomC&Employee to TomC&EmpQQH

2e ha+e changed the tale named 0mployee to 0mp66&

'sing &econdary Indices

The 4rimary inde. is always done at tale create time& The 4rimary ,nde. is the mechanismused to distriute the tale rows e+enly across the $4s& 0+ery tale in Teradata must ha+eone and only one 4rimary ,nde. and it is the fastest way to retrie+e data& tale can alsoha+e up to 8 secondary indices& ll indices can e single column or multiple columns& multi*column secondary inde. can e any comination of up to si.teen columns&

A secondary inde. !ecomes an alternate read path to the data& They can e ane.cellent way to speed up /ueries& secondary inde. can e defined as a 5ni/ueSecondary ,nde. !5S,% or Non*5ni/ue Secondary ,nde. !N5S,%&

Page 340: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 340/401

The following is the synta. for creating a secondary inde.:

CR0T0 5N,Q50O Kinde.*name !Kcolumn*list%

3R"0R # <L50S !Kcolumn*list% O O on dataase&OKtale*name

LLO

H

The e.ample elow does not specify 5N,Q50 and therefore creates a non*uni/uesecondary inde. on the dept column of the tale 0mployee&

CR0T0 ,N"06!dept% on TomC&0mployeeH

The ne.t e.ample creates a uni/ue secondary inde.!5S,% on the comination of first and lastnames with an inde. name of nameWid.W1in the 0mployee tale&

CR0T0 5N,Q50 ,N"06 nameWid.W1 !fname) lname% on TomC&0mployeeH

:hy ould someone choose to name an inde. It is easier to drop i, it is a multi1column inde.& ou would (ust use the synta.:

"$P INEQ nameWid.W1 on TomC&0mployee

The ne.t e.ample creates a Non*uni/ue secondary inde. !N5S,% on the last name andassigns a name of nameWid.W8 for it:

CR0T0 ,N"06 nameWid.W8 !lname% on TomC&0mployeeH

:hen initially creating an '&IJ the ros o, the ta!le must all !e read using a ,ull ta!lescan uring this processJ i, a duplicate <alue is encounteredJ the C"EATE INEQcommand ,ails All duplicate <alues must !e eliminated !e,ore an '&I can !e created&

The tale 0mployee now has three secondary indices& non*uni/ue inde. on the columndept) a uni/ue inde. on the fname and lname comination) and a non*uni/ue inde. that isnamed nameWid. on lname&

Rememer) we suggest that you name any inde. that uses more than one column& ,f youwish to name an inde. with one column) the suggestion is to use a name that is shorter thanthe column name&

ou can also drop an inde. that is not named& The following drops the inde. on a multi*column key in the 0mployee tale:

rop inde. (lnameJ,name) on TomC&0mployeeH

  classical secondary inde. is itself a tale made up of rows ha+ing two main parts& The firstis the data column itself inside the secondary inde. tale) and the second part is a pointer showing the locations of the row in the ase tale& #ecause Teradata is a parallelarchitecture) it re/uires a different means for distriuting and retrie+ing its data Y hashing&

Teradata has a +ery cle+er way of utiliing uni/ue secondary indices& 2hen a secondaryinde. command is entered Teradata hashes the secondary inde. column +alue for each rowand place the hash in a secondary inde. sutale along with the R32*," that points thease row where the desired +alue resides& This approach allows for all 5S, re/uests in the2=0R0 clause of SQL to ecome two*$4 operations& N5S, used in the 2=0R0 clausestill re/uires all $4s) ut the $4s can easily check the secondary inde. sutale to see if they ha+e one or more /ualifying rows&

Teradata creates a different secondary inde. sutale for each secondary inde. placed on atale& The price you pay is disk space and o+erhead& The disk space comes from 40R$ for 

Page 341: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 341/401

the secondary inde. sutales and there is o+erhead associated with keeping them currentwhen a data row is changed or inserted& There are three +alues stored in e+ery secondaryinde. sutale row& They are:

Secondary ,nde. data +alueSecondary ,nde. Row*," !This is the hashed +ersion of the +alue%

4rimary ,nde. Row*," !This locates the $4 and the row of the ase row%

=ashing the secondary inde. +alue and storing it in the secondary sutale is a fast andefficient way to gain an alternate path to the data& This is e.tremely efficient unless the /ueryasks for a range of +alues to e selected& -or e.ample) many /ueries in+ol+ing dates ask for a range ased on a start and end date using the 2=0R0 clause& The /uery might try to findall orders where the orderWdate is etween "ecemer 8) 8991 and "ecemer 1) 8991& secondary inde. done on a "T0 field does not allow for a range unless it is <L50*3R"0R0" instead of =S=*3R"0R0"&

:e suggest that all ATE columnsJ here you ant a secondary inde. ,or range>ueriesJ should speci,y the secondary indices to !e AL'E1$"E"E& +alue orderedN5S, stores the sutale rows in se/uence y the data +alue and not y the row hash +alue&Therefore) range checks work +ery well& The golden rule for <alue*3rdered secondaryindices is that they can only e performed on a single column N5S, that is four*ytes or less&<alid data types supported are:

"T0#T0,NT ,NT0I0R

"0C,$LS$LL,NT

=ere is an e.ample of creating a +alue*ordered secondary inde. on =ireWdate&

CR0T0 INEQ (;ire7date) $"E" BY AL'E& on TomC&0mployee =

There is no such thing as a +alue ordered 5S,& So) do not use the 5N,Q50 keyword whenattempting to create this type of inde.& There are only <alue*3rdered N5S,'s&

,f statistics are not collected for a N5S, column !see ne.t section  in this chapter for C3LL0CT STT,ST,CS%) the optimier will ne+er use the N5S, when referenced in a2=0R0 clause& lso) a composite N'&I (multi1column) ill almost ne<er !e used) e+enwith statistics& ,nstead) it is usually etter to make multiple N5S, indices and collect statisticson all of them& This allows Teradata to use what is called #itmap Set $anipulation !#$S$Sin the 064L,N output%& This uses the selecti+ity of multiple N5S,s together to make themhighly selecti+e and therefore used for row retrie+al& &

Soin Inde.

Compatiility: Teradata 0.tension

  @oin ,nde. is an inde. tale that pre*(oins the (oined rows of two or more tales and)optionally) aggregates selected columns& They are used to speed up /ueries that fre/uently

 (oin certain tales& Teradata (oin inde.es can e defined as hash*ordered or +alue*ordered&@oin inde.es are defined in a way that allows (oin /ueries to e resol+ed without accessingor (oining their underlying ase tales&

  @oin ,nde. takes two or more tales and physically Roins the tales together into another physical inde. ta!le& ,t also updates the @oin ,nde. tale when the ase rows of the (oiningase tales are updated& @oin inde.es are a great way to aggregate columns from taleswith a large range of +alues& @oin ,nde. can play the role of a summary tale without

Page 342: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 342/401

denormaliing the logical design of the dataase and without causing update anomaliespresented y denormalied tales& This actually gi+es you the aility to keep your detail datain rd normal form and your summary tales in a star schema format& #rilliant Teradata?

The synta. for a @3,N ,N"06 is:

CR0T0 @3,N ,N"06 Kdataase*name&OKinde.*name

N3O -LL#CJO

 S S0L0CT

KcolumnsO

S5$ numeric*e.pressionO

C35NT column*e.pressionO

06TRCT year month from date*e.pressionO

-R3$ Kdataase*name!s%&OKtale*namesO

2=0R0 Ksearch*conditionO

IR354 # Kcolumn*nameO

3R"0R # Kcolumn*nameO4R,$R ,N"06!Kcolumn*name%

inde. Kcolumn*name 3R"0R y =S= <L50SO

H

=ere is an e.ample of creating a @oin ,nde. etween the 0mployee tale and the"epartment tale:

CR0T0 S$IN INEQ T3$C&emp7dept7id. S

S0L0CT emp) e&dept) lname) fname) sal)

  dname) mgremp) udget

-R3$ TomC&Employee as e ,NN0R TomC&epartment as d

3N e&dept M d&deptH,n the e.ample ao+e a @3,N ,N"06 called emp7dept7id. has een created on the tales0mployee and "epartment& The rows from the two tales ha+e een physically (oinedtogether and will e maintained when rows in the 0mployee or "epartment tales changeecause of ,NS0RTS) 5"T0S) or "0L0T0S& 2hen users run /ueries they don't specify or mention the @3,N ,N"06 tale& ,nstead) when they run /ueries that can e satisfied y the@3,N ,N"06 tale faster the Teradata dataase will choose to pull the data from the @3,N,N"06 tale instead of the ase tales& 2hen SQL is run and the columns asked for are anycomination of the ao+e columns defined in the @3,N ,N"06 then Teradata may choose touse the @3,N ,N"06 instead of the actual ase tales& This is called a co<ering >uery&

ou can also e.plicitly define a 4rimary ,nde. for a @3,N ,N"06& Teradata spreads the rowsof the (oin inde. across the $4s& The $4s read and write the rows in parallel& So) utiliinga good 4rimary ,nde. can e important&

CR0T0 S$IN INEQ T3$C&S$INIQ79 S

S0L0CT emp) e&dept) dname

-R3$ TomC&0mployee as e) TomC&"epartment as d

2=0R0 e&dept M d&dept

P"IMA"Y INEQ(emp)=

Page 343: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 343/401

ou can also drop a @3,N ,N"06& =ere is an e.ample:

"$P S$IN INEQ T3$C&@3,N,"6W8H

Collecting &tatistics

The Teradata 40 or optimier follows the saying) ;,f you fail to 4LN you 4LN tofail;& The 40 is responsile for taking users SQL and after optimiing the SQLcomes up with a 4LN for the $4s to follow& The 40 is the #oss and the $4sare the workers& sk yourself two /uestions:

1& Could you ha+e a Teradata system without $4s 3f course not? $4s read and write the data&

8& Could you ha+e a Teradata system without 40's 3f course not? Could you get along without your oss !kidding)

kidding%

The Teradata 4arsing 0ngine !40% is the est optimier in the data warehouseworld) ut it needs you to C3LL0CT STT,ST,CS so it can optimie its work& Thestatistics allow the optimier to use its +ast e.perience to 4LN the est way tofulfill the /uery re/uest& ,t is particularly important for the optimier to ha+eaccurate tale demographics when data is skewed&The purpose of the C3LL0CT STT,ST,CS command is to gather and storedemographic data for one or more columns or indices of a ta!le or Roin inde.&This process computes a statistical profile of the collected data) and stores thesynopsis in the "ata "ictionary !""% for use during the 40's optimiing phase of SQL statement parsing& The optimier uses this synopsis data to generate efficienttale access and (oin plans&Lets re+iew: The 4arsing 0ngine 4rocessor !404% which is also referred to as theoptimier takes SQL re/uests from a user and comes up with a 4lan for the ccess$odule 4rocessors !$4s% to e.ecute& The 404 uses statistics to come up withthe most cost efficient plan& ou must C$LLECT &TATI&TIC& on any columns or indices of a tale you want the optimier to use with high confidence&

,f statistics are not collected) the 40 randomly chooses an $4 in which it will aska series of /uestions& The 404 will then estimate ased on the total numer of 

 $4s to estimate the numer of rows in the entire tale& This ;guess*timate; +aluecan e inaccurate) especially if the data is skewed&ou should C3LL0CT STT,ST,CS on all tales& ou also ha+e the aility toC3LL0CT STT,ST,CS on a Iloal temporary tales) ut not <olatile tales&

2e recommend you refresh the statistics whene+er the numer of rows in a taleis changed y 19U& -or e.ample) a $ultiLoad (o may ,NS0RT a million records ina A million*row tale& Since the tale has an additional 19U of new rows it isdefinitely time to refresh the C3LL0CT STT,ST,CS& ,n reality) we refresh statisticsy using the C3LL0CT STT,ST,CS command again any time the tale changes

y more than 19U&

The first time you collect statistics you collect them at the inde. or column le+el& fter that you (ust collect statistics at the tale le+el and all pre+ious columnscollected pre+iously are collected again& ,t is a mistake to collect statistics onlyonce and then ne+er do it again& ,n reality) it is etter to ha+e no statistics than toha+e ridiculously incorrect statistics& This is ecause the optimier is gullile andelie+es the statistics) no matter how inaccurate&

Page 344: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 344/401

Collecting Statistics is rough on system resources so it is est to do it at night in aatch (o or during other off peak times& ou can see what statistics ha+e eencollected on a tale and the date and time the STT,ST,CS were last collected withthe following:

=0L4 STT,ST,CS Ktale*name command

H

=ere are some e.cellent guidelines on what you should collect statistics on: ll Non*5ni/ue indicesNon*inde. (oin columnsThe 4rimary ,nde. of small tales4rimary ,nde. of a @oin ,nde.

Secondary ,ndices defined on any (oin inde.@oin inde. columns that fre/uently appear on any additional (oin inde.

columns that fre/uently appear in 2=0R0 search conditionsColumns that fre/uently appear in 2=0R0 search conditions or in the

2=0R0 clause of (oins&

The two key words to collect and drop statistics are:C$LLECT &TATI&TIC& "$P &TATI&TIC& 

=ere is the synta. to collect statistics:

C3LL0CT STT,ST,CS 3N Ktale*name

C3L5$N Kcolumn*name ,N"06!Kcolumn*name% O

H

=ere is an e.ample of collecting statistics on the column dept and the multicolumninde. of lname) fname columns in the employee tale&

C3LL0CT STT,ST,CS on TomC&0mployee column dept=

C3LL0CT STT,ST,CS on TomC&0mployee Inde.(lnameJ ,name)=2e ha+e C3LL0CT0" STT,ST,CS for the employee tale in two separatestatements& ou will always C3LL0CT STT,ST,CS on a column or inde. one at atime initially& ou must use the C3LL0CT STT,ST,CS command for each columnor inde. you want to collect in a tale& ,n the ao+e e.amples) we collectedstatistics on the column dept and the inde.!lname) fname%&  You can collectstatistics at either the column or inde. le<el  ,t is est to C3LL0CTSTT,ST,CS at the column le+el unless you are dealing with a multi1columninde.& C3LL0CT at the inde. le+el only for indices that are multicolumn indices&3therwise collect columns and single column indices at the column le+el& Singlecolumn indices actually perform the same C3LL0CT STT,ST,CS functions as if they were collected at the column le+el& 4lus) if you drop an inde.) you lose thestatistics&

The tale 0mployee now has C3LL0CT0" STT,ST,CS defined within the tale& lthough you must collect statistics the first time at the column or inde. le+el youonly collect statistics at the T#L0 L0<0L for all refreshing of STT,ST,CS& =ere isan e.ample of C3LL0CT,NI STT,ST,CS at the tale le+el&

C3LL0CT STT,ST,CS on TomC&0mployeeH

Page 345: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 345/401

The system will refresh the C3LL0CT STT,ST,CS on the columns and indices ithad pre+iously collected on the tale&

;ashing %unctions

Teradata uses parallel processing with its architecture of $4s and 404s& The 4rimary,nde. must e chosen whene+er you create a tale ecause it is the sole determinant of which $4s owns which rows& This concept pertains to data storage and data retrie+al&4icking the proper column!s% for the 4rimary ,nde. is e.tremely important for distriution andtherefore) for performance& The hashing functions introduced in this section pro+ideinformation pertaining to the selection of the $4 where each indi+idual row is stored&

 s mentioned pre+iously) Teradata uses a hashing algorithm to determine which $4 isresponsile for a data row's storage and retrie+al& This mathematical meat grinder isconfigured to generate a 8*it inary numer called the Row =ash for any data +aluepassed to it& This makes the placement of rows on $4s a random process& et) it willgenerate the same 8*it +alue whene+er the same data +alue is passed into it& Then) thefirst 1E*its called the "estination Selection 2ord !"S2% is used to select the appropriate

 $4& 5sing this techni/ue o+er a large numer of rows with uni/ue +alues) the systemnormally generates a good distriution of data rows the +ast ma(ority of the time&

There are now hashing functions) which can e incorporated into SQL) to produce and usethe same hash +alue result for testing current or future distriution le+els& ,n other words)these functions can e used to e+aluate the distriution of the rows within any or all tales or determine the acceptaility of other columns as a potential primary inde.&

;A&;"$:

The =S=R32 function is used to produce the 8*it inary !#T0!7% data type% Row =ashthat is stored as part of the data row& ,t can return a ma.imum of 7)8A7)AED)8A uni/ue+alues& The +alues produced range from 9 to --------&

3ne might think that 1E different +alues can e passed to the =S=R32 function since 1Ecolumns can e used in an inde.& =owe+er) we ha+e used up to 9 different +alues and itcontinues to produce uni/ue output +alues&

The asic synta. for using the =S=R32 function follows:

S0L0CT =S=R32! Kdata*column*+alue ) Kdata*column*+alue8 &&& O O %

H

0.amples using =S=R32:

S0L0CT =S=R32!N5LL% S N5LLW=S=

  )=S=R32!'Larkins'% S LarkW=S=

  )=S=R32!% S N3W=S= H

1 Row Returned

N'LL7;A&; Lar+7;A&; N$7;A&;

99999999 070D#C --------

Page 346: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 346/401

Now that the functionality has een demonstrated) a more realistic use might e thefollowing to e.amine the data distriution and determine the a+erage numer of rows per +alue:

S0L0CT C35NT!G% F C35NT!",ST,NCT!=S=R32!StudentWid%%%

 S <IWR32WCT

-R3$ StudentWtaleH

1 Row Returned

A87"$:7CT

1

 s good as this is) the =S=R32 function does not pro+ide a lot more help in thee+aluation process& =owe+er) when comined with the other =ashing -unctions) it yieldssome +ery helpful data demographics&

;A&;B'C2ET

The =S=#5CJ0T function is used to produce the 1E*it inary =ash #ucket !the "S2%that is used with the =ash $ap to determine the $4 that should store and retrie+e the datarow& ,t can return a ma.imum of E)E uni/ue +alues& The +alues range from 9 to E)not counting the N5LL as a potential result& The input to the =S=#5CJ0T is the 8*itRow =ash +alue&

The asic synta. for using the =S=#5CJ0T function follows:

S0L0CT =S=#5CJ0T! Krow*hash*+alue O %

H

0.ample using =S=#5CJ0T function:

S0L0CT =S=#5CJ0T!N5LL% S N5LLW#5CJ0T

  )=S=#5CJ0T!% S N3W#5CJ0TH

1 Row Returned

N'LL7B'C2ET N$7;A&;

E

  more realistic use is to determine the numer of rows in each =ash #ucket using thefollowing S0L0CT:

S0L0CT C35NT!G% S N#RWR32S  )=S=#5CJ0T!=S=R32 !StudentW,"%% S #ucketWNo

-R3$ StudentWtale

IR354 # 8 H

19 Rows Returned

Page 347: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 347/401

NB"7"$:& Buc+et7No

1 19E

1 8EBD1

1 AE71 117

1 8871

1 7DE7

1 A9A7

1 88811

1 79871

1 97A

The =ash #ucket is also known as the "estination Selection 2ord !"S2%& This is due to its

use of the =ash #ucket to determine the destination $4& Like Teradata) the S0L0CT canuse the =S=#5CJ0T as input into the =S=$4 function&

;A&;AMP

The =S=$4 function returns the identification numer of the primary $4 for any =ash#ucket numer&

The input to the =S=$4 function is an integer +alue in the range of 9 to E& 2hen no+alue is passed to the =S=$4 function) it returns a numer that is one less than thenumer of $4s in the current system configuration& ,f any other data type is passed to it) arun*time error occurs&

The asic synta. for using the =S=$4 function follows:

S0L0CT =S=$4! Khash*ucket %

H

0.amples using =S=$4 function:

S0L0CT =S=$4!N5LL% S N5LLW#5CJ0T

  )=S=$4 !% S N3W#ucketH

1 Row Returned

N'LL7B'C2ET N$7Buc+et

The following S0L0CT displays the $4 where each row li+es:

S0L0CT StudentW,"

  )=S=#5CJ0T!=S=R32!StudentW,"%% S #ucketWNo

  )=S=$4!=S=#5CJ0T!=S=R32!StudentW,"%%%

  S $4WNo

Page 348: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 348/401

-R3$ StudentWtale

3R"0R # 1H

19 Rows Returned:

&tudent7I Buc+et7No AMP7No

1889 8EBD1

18E7 19E

81888 A9A7 8

87181 88811 9

8E9999 97A 8

8B998 117

881 79871 9

87E8 AE7 9

79 7DE7 9

78799 8871 9

This e.ample outputs one row for e+ery row in the tale& This is a small tale so the pre+iouse.ample is feasile& =owe+er) most tales ha+e up to millions of rows and this S0L0CT isnot meaningful&

The following makes Teradata do the e+aluation:

S0L0CT C35NT!G% ;Count;

  )=S=$4!=S=#5CJ0T!=S=R32!StudentW,"%%%

  S $4WNo

-R3$ StudentWtaleIR354 # 8

3R"0R # 8 H

Rows Returned:

Count AMP7No

8 9

1

7 8

1

The one thing that ecomes o+ious is that on this system) the Student Tale does not ha+erows on all $4s& ,n a production en+ironment) this might e a prolem& The 4rimary ,nde.might need to e re*e+aluated&

Page 349: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 349/401

;A&;BA2AMP

The =S=#J$4 function returns the identification numer of the -allack $4 for any=ash #ucket numer&

The input to the =S=#J$4 function is an integer +alue in the range of 9 to E&

2hen no +alue is passed to the =S=$4 function) it returns a numer that is one lessthan the numer of $4s in the current system configuration& ,f any other data type ispassed to it) a run*time error occurs&

The asic synta. for using the =S=#J$4 function follows:

S0L0CT =S=#J$4 ! Khash*ucket %

H

0.amples using =S=#J$4 function:

S0L0CT =S=#J$4 !N5LL% S N5LLW#5CJ0T

  )=S=#J$4 !% S N9W#ucketH

1 Row Returned:N'LL7B'C2ET N$7Buc+et

The following shows the StudentW,") the #ucketWNo and the $4 that contains the fallackrows for each StudentW,"&

S0L0CT StudentW,"

  )=S=#5CJ0T!=S=R32!StudentW,"%% S #ucketWNo

  )=S=#J$4!=S=#5CJ0T!=S=R32!StudentW,"%%%

  S #JW$4WNo

-R3$ StudentWtale

3R"0R # H

19 Rows Returned

&tudent7I Buc+et7No BA27AMP7No

18E7 19E 9

8E9999 97A 9

8B998 117 9

87E8 AE7 1

1889 8EBD1 1

81888 A9A7 1

87181 88811 8

881 79871 8

78799 8871 8

79 7DE7

Page 350: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 350/401

The output once again reflects one row for each row of the tale& This is a small tale andtherefore it is reasonale to output a small numer of rows& =owe+er) most tales ha+e up tomillions of rows and this S0L0CT would not e meaningful&

The following makes Teradata do the e+aluation:

S0L0CT C35NT!G% ;Count;

  )=S=#J$4!=S=#5CJ0T!=S=R32!StudentW,"%%%

  S $4WNo

-R3$ StudentWtale

IR354 # 8

3R"0R # 8 H

7 Rows Returned:

Count AMP7No

9

1

8

1

The -LL#CJ rows for the Student tale are spread etter than the 4rimary ,nde. and doha+e rows on all $4s& So) the real /uestion might e) ;=ow well do all the rows !4rimary X-LL#CJ% distriute across all of the $4S;

The following S0L0CT can help determine that situation y finding all the 4rimary rows withtheir $4 and all the -LL#CJ rows with their $4s and than adding them together for the total !notice it uses a deri+ed tale to consolidate the rows counts%:

S0L0CT S5$!NrRows% S ;Rows 4er $4;

  )$4WNr 

-R3$ !S0L0CT C35NT!G%

  )=S=#J$4!=S=#5CJ0T!=S=R32!StudentW,"%%%

  -R3$ StudentWtale IR354 # 8

  5N,3N LL

  S0L0CT C35NT!G%

  )=S=$4!=S=#5CJ0T!=S=R32!StudentW,"%%%

  -R3$ StudentWtale IR354 # 8%

  "T !NrRows) $4WNr%

IR354 # 8

3R"0R # 8 H

7 Rows Returned:

Page 351: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 351/401

"osPer AMP

AMP7N!r 

9

1

8

 s seen here) the spread of oth the primary data and the fallack data is +ery consistent&These are great functions to e+aluate actual data distriution on the column!s% that are theprimary inde. or any column can e used to test other distriution +alues&

Conclusion

Teradata  makes it easy to create and drop tales& This chapter has discussed thefundamentals and ad+anced techni/ues to easily create and maintain the tales in a datawarehouse& ,f you set up the tale definitions correctly the first time then you will e wellahead of the game& 5nderstand the simple e.amples used in the eginning part of thischapter first& That will get you started& Then) utilie the ad+anced techni/ues to ma.imie thefle.iility Teradata pro+ides to enhance your data warehouse en+ironment&

Chapter 1A: Temporary Ta!les

Temporary Ta!les

There may e times when an e.isting production dataase tale does not pro+ide preciselywhat you need& Sometimes) a particular /uery might need summaried or aggregated data&

 t other times) a small numer of rows) from a +ery large tale or data for a specificorganiation) are re/uired to find an answer&

,n a data warehouse with millions of rows) it might take too long to locate) deri+e or mathematically calculate the data needed& This is especially true when it is needed morethan once per day& So) a +iew might not e the est solution or a +iew does not e.ist and youdo not ha+e the pri+ilege to create one and oth a +iew and deri+ed tale take too long& nyof these conditions pre+ent the aility to complete the re/uest&

,n the past) temporary tales ha+e een created and used to help SQL run faster or e moreefficient& They are e.tremely useful for sol+ing prolems that re/uire stored ;temporary;'

results or which re/uire multiple SQL steps& They are also great for holding aggregated or summaried data&

$ost dataases lose speed when they ha+e to:Read e+ery row in a +ery large tale !full tale scan%

4erform se+eral aggregations4erform se+eral data type con+ersions@oin rows together from multiple talesSort data

Page 352: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 352/401

Temporary tales are often useful in a de*normaliation effort& This might e done to makecertain /ueries e.ecute faster& 3ther times it is done to make the SQL easier to write)especially when using tools that generate SQL& =owe+er) these temporary tales are realtales and re/uire manual operations to create) populate) and maintain them&

 s a result) etter name for these temporary tales might e interim or temporal tales& Theye.ist for a specific period of time and when no longer needed) they are dropped to free upthe disk space& "uring the interim time) they pro+ide a +aluale ser+ice& =owe+er) if the datain the original tales changes) the interim tales must e repopulated to reflect that change&This adds a le+el of difficulty or comple.ity regarding their use&

Creating Interim or Temporal Ta!les

The following series of commands pro+ide an e.ample of creating) inserting) and thenentering SQL /ueries on an interim or temporal tale !real tale for short*term use%:

CR0T0 T#L0 $onthWSumWSales

!4roductW," ,NT0I0R

)CalWear S$LL,NT

)@anWsales "0C,$L!11)8%

)-eWsales "0C,$L!11)8%

)$arWsales "0C,$L!11)8%

)prWsales "0C,$L!11)8%

)$ayWsales "0C,$L!11)8%

)@unWsales "0C,$L!11)8%

)@ulWsales "0C,$L!11)8%

)ugWsales "0C,$L!11)8%

)SepWsales "0C,$L!11)8%

)3ctWsales "0C,$L!11)8%)No+Wsales "0C,$L!11)8%

)"ecWsales "0C,$L!11)8% %

5N,Q50 4R,$R ,N"06 !4roductW,") CalWyear%H

This tale reaks -irst Normal -orm !1N-% in that it contains a repeating group for twel+emonthly sales columns in e+ery row& Normally) each row in a tale represents an hour) a day)a week) or a month worth of sales& =owe+er with illions of rows) it re/uires e.tra time toread all the rows and consolidate them as calculated sutotals&

Therefore) the ao+e tale will make summary processing faster& ,n some cases) it will alsomake the SQL easier to write& #oth of these ecome important considerations as the

fre/uency of re/uests and the numer of users needing this data) increases&

The 0mployee) "epartment and Sales tales elow are used to demonstrate temporarytales:

Page 353: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 353/401

%igure 0H10 

%igure 0H19 

%igure 0H1@ 

To populate the interim tale with data for Septemer through "ecemer of the year 8999)the ne.t ,NS0RT F S0L0CT might e used:

FG ,nsert only Septemer thru "ecemer into the tale GF

Page 354: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 354/401

,NS0RT ,NT3 $onthWSumWSales

  !4roductW,") CalWyear) SepWSales) 3ctWsales) No+Wsales) "ecWsales%

  S0L0CT 4roductW,"

  )06TRCT !0R -R3$ SaleWdate%

  )S5$!CS0 !!SaleWdateF199% $3" 199%

  2=0N A T=0N "ailyWSales 0LS0 9 0N"%

  )S5$!CS0 !!SaleWdateF199% $3" 199%

  2=0N 19 T=0N "ailyWSales 0LS0 9 0N"%

  )S5$!CS0 !!SaleWdateF199% $3" 199%

  2=0N 11 T=0N "ailyWSales 0LS0 9 0N"%

  )S5$!CS0 !!SaleWdateF199% $3" 199%

  2=0N 18 T=0N "ailyWSales 0LS0 9 0N"%

  -R3$ SalesWtale

  2=0R0 SaleWdate #0T200N 1999A91 N" 199189

  IR354 # 1)8H

Then) to display the sales for the last /uarter of the year 8999) all that is re/uired is aS0L0CT like the following:

S0L0CT 4roductW," S 4roduct

  )CalWear S CalWr 

  )SepWsales S SeptemerWsales

  )3ctWsales S 3ctoerWsales

  )No+Wsales S No+emerWsales

-R3$ $onthWSumWSales

2=0R0 CalWear M 89993R"0R # 1 H

Rows Returned

Product7I Cal7Yr &eptem!er7sales $cto!er7sales No<em!er7sale

1999 8999 1A9&EA 1A1B7&9 9&99

8999 8999 1ADB&A1 1EEBD8&A9 9&99

999 8999 1AEDA&DE B7A9B&9E 9&99

The pre+ious SQL shows how to create) insert) and access an interim tale& side from the

positi+e aspects of using this techni/ue) there are other considerations& -irst) to pro+idecurrent data) the rows in the tale might need to e updated periodically& 3therwise) usingacti+e data warehouse tales and the summary tale result in different answers to the same/uestion&

 nother issue regarding this techni/ue is that a ;real tale; must e created and later it wille dropped manually& #oth of these actions re/uire updates in the "ata "ictionary !""%&

 dditionally) you must ha+e the pri+ileges to CR0T0 and "R34 a tale as well as a+ailale4ermanent space& $ost data warehouse sites do not allow for this type of loose security and

Page 355: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 355/401

space management& ,t is not normally an acceptale practice to allow all users to createthese temporal tales for this purpose&4otential gains using an ,nterim tale:

$ake the SQL easier to write and run faster   +oid repeated aggregation on the real data rows

4ro+ide 4rimary ,nde. access

"ata is a+ailale to multiple usersThe associated costs of this tale:

,t re/uires separate steps to create and populate the tale originally ,t must e kept updated with new sales data

Re/uires e.tra 40R$ Space for the interim tale Re/uires the tale to e manually dropped when no longer needed Re/uires pri+ileges to e.ecute a CR0T0 and "R34 T#L0 Re/uires "" locking to create and drop tale

The main prolem is that a permanent tale had to e created& This action is manual and isdone within the "" ecause it is a real tale& nother prolem is that the contents of thetale may /uickly ecome out of date the moment a row changes in the original tale&

The iggest single stumling lock is proaly the inaility to create a tale) due to a lack of the proper pri+ileges or 4ermanent space& The only solution is to sumit a change re/uest tothe "ataase dministrator !"#%& Therefore) the process might take a couple of days tocomplete& This can e de+astating when the data is needed immediately& So instead of usinginterim tales) this may e a perfect opportunity to use temporary tales&

Temporary Ta!le Choices

There are three types of temporary tales a+ailale within Teradata& ll of which ha+ead+antages o+er traditional temporary tales&eri<ed ta!les are always local to a single SQL re/uest& They are uilt dynamically usingan additional S0L0CT within the /uery& The rows of the deri+ed tale are stored in spool anddiscarded as soon as the /uery finishes& The "" has no knowledge of deri+ed tales&Therefore) no e.tra pri+ileges are necessary& ,ts space comes from the users spool space&olatile Temporary ta!les are local to a session rather than a specific /uery& This meansthat the tale may e used repeatedly within a user session& That is the ma(or differenceetween +olatile temporary tales !multiple use% and deri+ed tales !single use%& Li+e aderi<edJ a <olatile temporary ta!le is materialiXed in spool space & =owe+er) it is notdiscarded until the session ends or when the user manually drops it& The has no+noledge o, <olatile temporary ta!les& They are often simply called) +olatile talesH noe.tra pri+ileges are re/uired to use them either& Its space comes ,rom the users spoolspace&8lo!al Temporary ta!les are local to a session) like +olatile tales& =owe+er) they areknown in the "" where a permanent definition is kept& 8lo!al temporary ta!les arematerialiXed ithin a session in a ne type o, data!ase area called temporary space&

 lso like +olatile tales) they are discarded at the end of the session or when the user manually re/uests the tale to e dropped& They are o,ten calledJ glo!al ta!les Its spacecomes ,rom a ne type o, space called temporary space

eri<ed Ta!leseri<ed ta!les were introduced into Teradata with <8R8& The creation of the deri+ed tale islocal to the SQL statement and a+ailale only for a single re/uest& =owe+er) a re/uest may

Page 356: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 356/401

contain multiple deri+ed tales& 3nce these tales are defined and populated) they may e (oined or manipulated (ust like any other tale& "eri+ed tales ecome an alternati+e tocreating +iews or the use of interim tales&

"eri+ed tales are +ery useful& =owe+er) since they only e.ist for the duration of a singlere/uest) they may not e a practical solution if the rows are needed for multiple) follow*up/ueries needing the same data& The deri+ed tale is materialied in spool space) used anddropped automatically at the end of the /uery& Since it is entirely in spool) it only re/uires theuser to ha+e enough spool space& Since there is no "" in+ol+ement) special pri+ileges arenot re/uired&

The process of deri+ing a tale is much like deri+ing column data& They are oth donedynamically in an SQL statement& The main difference is that column data is normallyderi+ed in the S0L0CT list) ut deri+ed tales are defined in the -R3$& deri+ed tale iscreated dynamically y referring to it in the -R3$ portion of a S0L0CT) 54"T0 or "0L0T0& Like all tales) it needs a tale name) one or more column names and data rows&

 ll of these re/uirements are estalished in the -R3$ portion of an SQL statement&

The following is the synta. for creating a deri+ed tale:

S0L0CT Kcolumn*name1 ) Kcolumn*name8 )Kcolumn*nameN O O

-R3$ ( &ELECT 3column1name04 O A& 3alias1name4

  O J3column1nameN4 %"$M 3ta!le1name4 )

  3eri<ed1ta!le1name4 O ( 3alias1name04 OJ3alias1nameN4 )

H

,n the ao+e synta.) e+erything after the first -R3$ is used to dynamically name the deri+edtale with its columns and populate it with a S0L0CT& The S0L0CT is in parentheses andlooks like a su/uery& =owe+er) su/ueries are written in the 2=0R0 clause and this is inthe -R3$& This S0L0CT is used to populate the tale like an ,NS0RTFS0L0CT for a realtale) ut without the ,NS0RT&

The deri+ed tale and its columns must ha+e +alid names& ,f desired) the deri+ed talecolumn names can default to the actual column names in the S0L0CT from a real tale&3therwise) they can e alias names estalished using S in the S0L0CT of the deri+edtale) or specified in the parentheses after the name of the deri+ed tale) like in a CR0T0<,02& 5sing this techni/ue is our preference& ,t makes the names easy to find ecause theyare all physically close together and does not re/uire a search through the entire S0L0CTlist to find them&

These columns recei+e their data type from the columns listed in the S0L0CT from a realtale& Their respecti+e data types are estalished as a result of the se/uence that thecolumns appear in the S0L0CT list& ,f a different data type is re/uired) the CST can eused to make the ad(ustment&

The following is a simple e.ample using a deri+ed tale named "T with a column alias called

a+gsal and its data +alue is otained using the <I aggregation:

S0L0CT G

-R3$ (&ELECT A8(salary) %"$M Employee7ta!le) T(a<gsal) H

1 Row Returned

Page 357: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 357/401

a<gsal

7EDB8&1

3nce the deri+ed tale has een materialied and populated) the actual SQL statementreads its rows from the deri+ed tale) (ust like any other tale& lthough this deri+ed taleand its S0L0CT are simplified) it can e any +alid S0L0CT and therefore can use any of theSQL constructs such as: inner and outer (oins) one or more set operators) su/ueries andcorrelated su/ueries) aggregates and 3L4 functions& Like a +iew) it cannot contain an3R"0R #) a 2,T=) or a 2,T= #& =owe+er) these operations can still e re/uested in themain /uery) (ust not in the S0L0CT for the deri+ed tale&

The est thing aout a deri+ed tale is that the user is not re/uired to ha+e CR0T0 T#L0pri+ileges and after its use& deri+ed tale is automatically ;dropped; to ;clean up; after itself& =owe+er) since it is dropped the data rows are not a+ailale for a second S0L0CToperation& 2hen these rows are needed in more than a single S0L0CT) a deri+ed tale maynot e as efficient as a +olatile or gloal temporary tale&

The ne.t e.ample uses the same deri+ed tale named "T to (oin against the 0mployee tale

to find all the employees who make less than the a+erage salary:S0L0CT LastWname

  )Salary

  JA<gsal

-R3$ (&ELECT A8(salary) %"$M Employee7ta!le) T(a<gsal)

  ,NN0R @3,N 0mployeeWtale

  3N a+gsal K salaryH

Row Returned

Last7name &alary A<gsal 7  

Chamers 7BB9&99 7EDB8&1

Smythe E799&99 7EDB8&1

Smith 7B999&99 7EDB8&1

=arrison 799&99 7EDB8&1

Strickling 799&99 7EDB8&1

Now that a+gsal is a column) it can e selected for display as well as eing compared todetermine which rows to return&

This deri+ed tale elow is a it more in+ol+edH it contains two columns and some numer of 

rows created y doing an aggregation with a IR354 # and then does aggregation on theaggregates in the deri+ed tale:

S0L0CT "eri+edWCol1

  )S5$!"eri+edWCol8%

  )<I!"eri+edWCol8%

-R3$ (&ELECT $thT7Col0J &'M($thT7Col9) %"$M $th7T!l

  :;E"E $thT7Col0 3 966 8"$'P BY 0)

Page 358: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 358/401

  My7eri<ed7T!l ( eri<ed7Col0J eri<ed7Col9 )

IR354 # 1H

#oth columns) "eri+edWCol1 and "eri+edWCol8) are named in parentheses following thederi+ed tale name) $yW"eri+edWTl& The -R3$ is also used to populate $yW"eri+edWTl+ia the S0L0CT using the tale called 3thWTl& The deri+ed tale is then used to pro+ide the

aggregates of S5$ and <I on the column called "eri+edWCol8& The tales called 3thWTland 4aymentWTale !later e.ample% do not e.ist in my data tales& They are used here toillustrate the mechanics of more suffocated deri+ed tales only and not e.ecuted to see therows& 4lease continue reading the ne.t paragraphs for a detail e.planation regarding theusage of deri+ed tales&

The data +alue for "eri+edWCol1 is otained from data in the real column called 3thTWCol1&,t is selected as a non*aggregate and specified in the IR354 # of the S0L0CT of thederi+ed taleH it follows normal aggregation rules& The deri+ed tale will contain one row for each uni/ue +alue in 3thTWCol1& Then) the column called "eri+edWCol8 is deri+ed using theS5$ aggregate on column 3thTWCol8&

Therefore) the main S0L0CT in this /uery is from the deri+ed tale to perform a S5$ and an <I on the +alue otained using a S5$ of 3thTWCol8& Like using a +iew) this is a fast) easyway to perform aggregation on aggregates&

This e.ample uses a deri+ed tale to accomplish the same processing seen pre+iously withan interim tale:

S0L0CT 4roductW," S 4roduct) CalWyr 

  )SepWsales S SeptemerWsales

  )3ctWsales S 3ctoerWsales

  )No+Wsales S No+emerWsales

-R3$ (&ELECT Product7I JEQT"ACT(YEA" %"$M &ale7date) A& Cal7Yr 

  J&'M(CA&E ((&ale7date#066) M$ 066)

  :;EN H T;EN aily7&ales  EL&E 6

  EN) A& &ep7sales

  J&'M(CA&E ((&ale7date#066) M$ 066)

  :;EN 06 T;EN aily7&ales

  EL&E 6

  EN) A& $ct7sales

  J&'M(CA&E ((&ale7date#066) M$ 066)

  :;EN 00 T;EN aily7&ales

  EL&E 6

  EN) A& No<7sales

  %"$M &ales7ta!le

  :;E"E &ale7date BET:EEN 0666H60 AN 06600@6

  8"$'P BY 0J9)

  T7Month7&um7&ales

FG The "eri+ed tale ao+e is called "TW$onthWSumWSales and gets its column names

Page 359: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 359/401

from the alias names of the ao+e S0L0CT in parentheses GF

2=0R0 CalWr M 8999

3R"0R # 1 H

Rows Returned

Product7I Cal7Yr &eptem!er7sales $cto!er7sales No<em!er7sale

1999 8999 1A9&EA 1A1B7&9 9

8999 8999 1ADB&A9 1EEBD8&A9 9

999 8999 1AEDA&DE B7A9B&9E 9

The ne.t S0L0CT is rather in+ol+edH it uilds $yW"eri+edWTl as a deri+ed tale:

S0L0CT "eri+edWCol1

  )"eri+edWCol8

  )4aymentWdate

  )4aymentWamountFG The "eri+ed tale definition starts elow GF

-R3$ (&ELECT $thT07Col0J $thT97Col9J $thT07Col@

  %"$M $th7T!l70 A& $T0

  INNE" S$IN $th7T!l79 A& $T9

  $N $T0Col@ ? $T9Col@

 #5 The correlated su!>uery to populate the eri<ed ta!le starts !elo 5#

  :;E"E $T0&ale7date ? (&ELECT MAQ(Purchase7ate)

  %"$M &ales7T!l

  :;E"E $T0$thT07Col@ ? &ales7Product )

  My7eri<ed7T!l ( eri<ed7Col0J eri<ed7Col9J eri<ed7Col@ )

FG The "eri+ed tale definition ends here GF

  R,I=T 35T0R @3,N 4aymentWTl S 4T

  3N "eri+edWCol M 4aymentWCol

FG The correlated su/uery for the main S0L0CT starts elow GF

2=0R0 4aymentW"ate M !S0L0CT $6!4aymentW"ate% -R3$ 4aymentWTl

  2=0R0 4aymentWTl&ccountWNrM4T&ccountWNr%H

The deri+ed tale is created using an ,NN0R @3,N and a Correlated Su/uery& The mainS0L0CT then uses the deri+ed tale as the outer tale to process an 35T0R @3,N& ,t is

 (oined with the 4ayment tale and uses a Correlated Su/uery to make sure that only thelatest payment is accessed for each account&

2hether your re/uirements are straightforward or comple.) deri+ed tales pro+ide an ad hocmethod to create a ;tale; with data rows and use them one time in an SQL statementwithout needing a real tale to store them&

Page 360: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 360/401

olatile Temporary Ta!lesolatile ta!les  were introduced in release <8R of Teradata& They ha<e tocharacteristics in common ith deri<ed ta!les They are materialiXed in spool and areun+non in the & =owe+er) unlike a deri+ed tale) a +olatile tale may e used in morethan one SQL statement throughout the life of a session& This feature allows other follow*up/ueries to utilie the same rows in the temporary tale without re/uiring them to e

estalished again& This aility to use the rows multiple times is their iggest ad+antage o+er deri+ed tales&

  +olatile tale may e dropped manually at any time when it is no longer needed& ,f it is notdropped manually) it will e dropped automatically at the end of the user session& user canmaterialie up to a ma.imum of E7 +olatile tales at a time& 0ach +olatile tale re/uires itsown CR0T0 statement& 'nli+e a real ta!le ith its de,inition stored in the J the<olatile ta!le name and column de,initions are stored only in cache memory o, theParsing Engine& Since the rows of a +olatile tale are stored in spool and do not ha+e ""entries) they do not sur+i+e a system restart& That is why they are called +olatile&

The synta. to create a +olatile tale follows:

CR0T0 $LATILE T#L0 Ktale*name ) P L$8 N$ L$8  O

! Kcolumn*name1 Kdata*type

) Kcolumn*name8 Kdata*type

) Kcolumn*nameN Kdata*type O %

O O 'NI-'E P"IMA"Y INEQ (3column1list4)

O $N C$MMIT P"E&E"E ELETE * "$:&

HThe L$8 option indicates the desire for standard transaction logging of ;efore images; inthe transient (ournal& 2ithout (ournaling) maintenance acti+ities can e much faster&=owe+er) e aware that without (ournaling) there is no transaction reco+ery a+ailale& L3I isthe default) ut unlike real tales it can e turned off) y specifying: N3 L3I&The second tale option regards the retention of rows that are inserted into a +olatile tale&

The default +alue is $N C$MMIT ELETE "$:&  ,t specifies that at the end of atransaction) the tale rows should e deleted& lthough this approach seems unusual) it isactually the default re/uired y the NS, standard& ,t is appropriate in situations where atale is materialied only to produce rows and the rows are not needed after the transactioncompletes& Rememer) in NS, mode) all SQL is considered part of a single transaction untilit fails or the user does a C3$$,T 23RJ command&The $N C$MMIT P"E&E"E "$:& option pro+ides the more normal situation where thetale rows are kept after the end of the transaction& ,f the rows are going to e needed for other /ueries in other transactions) use this option or the tale will e empty& Since eachSQL re/uest is a transaction in Teradata mode) this is the commonly used option to makerows stay in the +olatile tale for continued use&

2ithout "" entries) the following options are N3T a+ailale with +olatile tales:

4ermanent @ournalingReferential ,ntegrityC=0CJ constraintsColumn compressionColumn default +alues

Column titlesNamed inde.es

Page 361: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 361/401

olatile ta!les must ha+e names that are uni/ue within the user's session& They are/ualified y the user*id of the session) either e.plicitly or implicitly& A <olatile ta!le cannote.ist in a data!ase= it can only materialiXe in a userKs session and area&

The fact that a +olatile tale e.ists only to a user's session implies a hidden conse/uence&No other user may access rows in someone else's +olatile tale& -urthermore) since it islocal to a session) the same user cannot access the rows of their own ;+olatile tale; fromanother session) only in the original session& ,nstead) another session must run the samecreate +olatile tale command to otain an instance of it and another S0L0CT to populate itwith the same rows if they are needed in a second session&

 lthough this might sound ad) it pro+ides greater fle.iility& ,t allows for a situation wherethe same ;tale; is used to process different re/uests y storing completely different rows&3n the other hand) it means that a +olatile tale may not e the est solution when multiplesessions or multiple users need access to the same rows on a fre/uent asis&

The following e.amples show how to create) populate) and run /ueries using a +olatile tale:

CR0T0 $LATILE T#L0 ept7Aggreg7<t ) N3 L3I

! "eptWno ,nteger 

)SumWSalary "ecimal!19)8%

)+gWSalary "ecimal!D)8%

)$a.WSalary "ecimal!D)8%

)$inWSalary "ecimal!D)8%

)CntWSalary ,nteger %

$N C$MMIT P"E&E"E "$:&

H

The definition is uilt in the 40's cache memory& This is the only place that it resides) not inthe ""&

The ne.t ,NS0RTFS0L0CT populates the +olatile tale created ao+e with one data row per department that has at least one employee in it:

,NS0RT ,NT3 ept7Aggreg7<t

  S0L0CT "eptWno

  )S5$!Salary%

  )<I!Salary%

  )$6!Salary%

  )$,N!Salary%

  )C35NT!Salary%

  -R3$ 0mployeeWTale

  IR354 # "eptWno H

Now that the +olatile tale e.ists in the cache memory of the 40 and it contains data rows) itis ready for use in a +ariety of SQL statements:

S0L0CT G -R3$ ept7Aggreg7<t

3R"0R # 1H

E Rows Returned

Page 362: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 362/401

ept7no &um7&alary A<g7&alary Ma.7&alary Min7&alary Cn

8B99&9 8B99&9 8B99&9 8B99&9 1

19 E799&99 E799&99 E799&99 E799&99 1

199 7BB9&99 7BB9&99 7BB9&99 7BB9&99 1899 BABBB&BB 77A77&77 7B999&99 71BBB&BB 8

99 79899&99 79899&99 79899&99 79899&99 1

799 17999&99 7B& 7999&99 E999&99

The same rows are still a+ailale for another S0L0CT:

S0L0CT "epartmentWName

  )+gWSalary

  )$a.WSalary

  )$inWSalary

-R3$ ept7Aggreg7<t A& T ,NN0R @3,N "epartmentWTale "

  3N <T&deptWno M "&deptWno

2=0R0 CntWSalary 1 H

8 Rows Returned

epartment7Name A<g7&alary Ma.7&alary Min7&alary

Research and"e+elopment

77A77&77 7B999&99 71BBB&BB

Customer Support 7B& 7999&99 E999&99

2hene+er a single user needs data rows and they are needed more than once in a session)the +olatile tale is a etter solution than the deri+ed tale& Then) as the user logs off) thetale definition and spool space are automatically deleted&

Since no "" entry is a+ailale for a +olatile tale) they will not e seen with a =0L4 5S0Rcommand& The only way to see how many and which +olatile tales e.ist is to use thefollowing command:

=0L4 <3LT,L0 T#L0 H

1 Row Returned

&essionId

Ta!leName

Ta!le Id Protection Creator  Name

Commit$ption

1919 myW+t 19C9C79999 N $,J0L 4

The main disad+antage of a +olatile tale is that it must e created +ia the CR0T0<3LT,L0 T#L0 statement e+ery time a new session is estalished& This situation can eo+ercome using a gloal temporary tale&

Page 363: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 363/401

8lo!al Temporary Ta!les8lo!al Temporary Ta!les were also introduced in release <8R of Teradata& Their taleand column definition is stored in the "") unlike +olatile tales& The first SQL "$L statementto access a gloal temporary tale) typically an ,NS0RTFS0L0CT) materialies the tale&They are often called gloal tales&

Like +olatile tales) gloal tales are local to a session& The materialied instance of thetale is not shareale with other sessions& lso like +olatile tales) the gloal tale instancemay e dropped e.plicitly at any time or it is dropped automatically at the end of the session&=owe+er) the definition remains in the dictionary for future materialied instances of thesame tale& t the same time) the materialied instance or ase definition may e droppedwith an e.plicit "R34 command) like any tale&

The only pri+ilege re/uired to use a gloal tale is the "$L pri+ilege necessary tomaterialie the tale) usually an ,NS0RTFS0L0CT& 3nce it is materialied) no other pri+ileges are checked&

  special type of space called ;Temporary space; is used for gloal temporary tales& Like4ermanent space) Temporary space is preser+ed during a system restart and thus) gloaltemporary tales are ale to sur+i+e a system restart&

These gloal tales are created using the CR0T0 IL3#L T0$43RR T#L0command& 5nlike the +olatile tale) this CR0T0 stores the ase definition of the tale in the"" and is only e.ecuted once per dataase& Like +olatile tales) the tale defaults are toL3I transactions and 3N C3$$,T "0L0T0 R32S& 5p to 8 materialied instances of agloal temporary tale may e.ist for a single user&

3nce the tale is accessed y a "$L command) such as the ,NS0RTFS0L0CT) the tale isconsidered materialied and a row is entered into a "" tale called "#C&Temptales& nadministrator may S0L0CT from this tale to determine the users with gloal talesmaterialied and how many gloal tales e.ist&

"eleting all rows from a gloal tale does not de*materialie the tale& The instance of the

tale must e dropped or the session must e ended for the materialied tale to ediscarded&

The synta. to create a gloal temporary tale follows:

CR0T0 8L$BAL TEMP$"A"Y TABLE Ktale*name P L$8 N$ L$8  O

! Kcolumn*name1 Kdata*type

) Kcolumn*name8 Kdata*type O

O O 'NI-'E P"IMA"Y INEQ (3column1list4)

O $N C$MMIT P"E&E"E ELETE * "$:&

H

8L$BAL Temporary Ta!le E.amples

This series of commands show how to create) insert) and select from a gloal temporarytale:

CR0T0 8L$BAL TEMP$"A"Y T#L0 ept7Aggreg7gt

! "eptWno ,nteger 

 )SumWSalary "ecimal!19)8%

Page 364: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 364/401

 )+gWSalary "ecimal!D)8%

 )$a.WSalary "ecimal!D)8%

 )$inWSalary "ecimal!D)8%

 )CntWSalary ,nteger %

$N C$MMIT P"E&E"E "$:&

H

The ne.t ,NS0RT will create one data row per department that has at least one employee init:

,NS0RT ,NT3 ept7Aggreg7gt

  S0L0CT "eptWno )S5$!Salary% ) <I!Salary% )$6!Salary% )$,N!Salary%

  )C35NT!Salary%

  -R3$ 0mployeeWTale IR354 # "eptWno H

Now that the gloal temporary tale e.ists in the "" and it contains data rows) it is ready for use in a +ariety of SQL statements like the following:

S0L0CT G -R3$ ept7Aggreg7gt

3R"0R # 1H

E Rows Returned

ept7no &um7&alary A<g7&alary Ma.7&alary Min7&alary Cn

8B99&9 8B99&9 8B99&9 8B99&9 1

19 E799&99 E799&99 E799&99 E799&99 1

199 7BB9&99 7BB9&99 7BB9&99 7BB9&99 1

899 BABBB&BB 77A77&77 7B999&99 71BBB&BB 8

99 79899&99 79899&99 79899&99 79899&99 1

799 17999&99 7B& 7999&99 E999&99

,t can immediately e used y other S0L0CT operations:

S0L0CT "epartmentWName

  )+gWSalary

  )$a.WSalary

  )$inWSalary

-R3$ ept7Aggreg7gt A& 8T ,NN0R @3,N "epartmentWTale "

3N IT&deptWno M "&deptWno

2=0R0 CntWSalary 1H

8 Rows Returned

epartment7Name A<g7&alary Ma.7&alary Min7&alary

Research and 77A77&77 7B999&99 71BBB&BB

Page 365: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 365/401

epartment7Name A<g7&alary Ma.7&alary Min7&alary

"e+elopment

Customer Support 7B& 7999&99 E999&99

 t this point) it is proaly o+ious that these e.amples are the same as those used for the+olatile tale e.cept for the fact that the tale name ends with ;gt; instead of ;+t&; <olatiletales and gloal temporary tales are +ery much interchangeale from the user perspecti+e& The iggest ad+antage to using the gloal temporary tale lies in the fact thatthe tale ne+er needs to e created a second time& ll the user needs to do is reference itwith an ,NS0RTFS0L0CT and it is automatically materialied with rows&

Therefore) when multiple users need the same definition) it is etter to store it one time andgi+e all users the ,NS0RT pri+ilege on it& ,t is the standard definition a+ailale to all userswithout re/uiring each user to run a CR0T0 statement and o+ercomes the maindisad+antage of a +olatile tale& =owe+er) no user can access or distur rows elonging toanother user& They can only access their own rows due to each user session owning adifferent instance of the tale&

Since the gloal temporary tale's definition is stored in the "") it may e altered using the LT0R command& ,t can change any attriutes of the tale) like real tales& dditionally) for e.tra fle.iility) a materialied instance of the tale may e altered without affecting the asedefinition or other user's materialied instance& Talk aout fle.iility&

This ad+antage means that a user is not restricted to ha+ing an identical definition as allother users& #y using the LT0R T0$43RR T#L0 statement) the user can fine*tune thetale for their specific needs) session y session&

Since a gloal temporary tale can e altered and is not in spool space) this means thatwithin an instance) it can take ad+antage of the following operations:

 dd F "rop columns  dd F "rop attriutes Create F "rop indices

Collect Statistics

 s an e.ample) if someone did not wish to use the L3I option for his or her instance) thene.t LT0R could e used:

 LT0R TEMP$"A"Y T#L0 ept7Aggreg7gt N3 L3IH

Therefore) care should e taken to insure that not all users ha+e LT0R pri+ileges on thease tale definition in the ""& 3therwise) accidentally omitting the word ;temporary; altersthe ase definition and no one has the L3I option as seen elow:

 LT0R T#L0 ept7Aggreg7gt N3 L3IH

Likewise) the same consideration should e used when defining and collecting Statistics onthe stored definition +ersus the materialied instance& The following defines which statisticsto collect on the tale definition:

C3LL0CT STT,ST,CS 3N ept7Aggreg7gt inde. !"eptWno%H

=owe+er) when this is e.ecuted there are no rows in the tale and therefore no rows toe+aluate and no statistics to store& So) why other The reason is that once an instance is

Page 366: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 366/401

materialied all a user needs to do is collect statistics at the tale le+el after inserting their rows into their temporary instance of the tale&

The following C3LL0CT specifies the importance of the word T0$43RR to denote theinstance and not the ase definition:

C3LL0CT TEMP$"A"Y STT,ST,CS on ept7Aggreg7gtH

The ao+e statement collects all statistics for rows in the +olatile tale) as defined y thease tale& =owe+er) a user might wish to collect statistics on a column not originally definedfor the tale) such as $a.WSalary& To accomplish this collection operation) the user coulde.ecute the ne.t statement:

C3LL0CT TEMP$"A"Y STT,ST,CS on ept7Aggreg7gt C$L'MN Ma.7&alaryH

 s a reminder) each instance can only e accessed y a single user and furthermore) onlywithin a single session for that user& Like the +olatile tale) the same user cannot accessrows from their own temporary tale from a different session&

 lso like a +olatile tale) a gloal tale releases its temporary space and the instance whenthe user logs off& ,f the user wishes to manually drop the instance) use the following

command:"R34 TEMP$"A"Y T#L0 ept7Aggreg7gt H

 gain) the word T0$43RR is +ery important ecause without it:

"R34 T#L0 ept7Aggreg7gt H

2ill drop the ase definition and cause prolems for other users& 4ri+ileges should eestalished to pre+ent a user from accidentally dropping a gloal tale definition&

2ith that eing said) there might come a time when it is desired to drop the ase definition& ,f the ao+e "R34 T#L0 is e.ecuted) it will work unless a user has a materialied instance&3ne materialied instance is enough to cause the statement to fail& s an alternati+e) an LLoption can e added) as seen in the ne.t statement) in an attempt to drop the definition:

"R34 T#L0 ept7Aggreg7gt ALL H

This works as long as a user is not in the middle of a transaction& 3therwise) the only optionis to wait until the user's transaction completes and then e.ecute the "R34 again&

The ao+e format for a Iloal tale indicates the aility to define a primary inde. as either uni/ue or non*uni/ue& dditionally) since the definition is in the data dictionary) placing a5N,Q50 constraint on one or more columns would also make the first uni/ue column a 54,&This logic is the same for a real tale&

8eneral Practices ,or Temporary use Ta!les

The following are guidelines to consider when determining which type of ;temporary; tale touse& $ost of the criteria are ased on the numer of users needing access to the data& Thesecond issue is related to the fre/uency of use&

$ultiple user accessto a tale:

Temporalor interimtale!short*term real

Page 367: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 367/401

tale%

Single user access toa tale)

 

* Single ad hoc SQLuse tale:

"eri+edtale

* $ultiple SQL usetale:

<olatile or Iloaltemporarytale

* Standardied)multiple SQL usetale:

Iloaltemporarytale

5se these guidelines to decide which type of tale to use ased on the needs of the user&

Chapter 89: Trigger Processing

Triggers

  trigger is an e+ent dri+en maintenance operation& The e+ent is caused y a modification toone or more columns of a row in a tale& The original modification re/uest) the trigger and allsuse/uent triggers constitute a single transaction& This means that the SQL and alltriggered statements must work successfully) or else) all fail and rollack all changed rowsfrom the Transient @ournal&

Triggers are an e.cellent way to automate many dataase modifications that pre+iouslyre/uired manual inter+ention y the user or "#& Since triggers occur automatically) theyremo+e the urden from a person's memory to make the suse/uent updates in one or moreother tales& Therefore) they can e used as a laor sa+ings de+ice and impro+e dataintegrity at the same time) two enefits in one&

Triggers can e particularly useful when Referential ,ntegrity !R,% is defined& Teradataincorporates the 4re+ent logic as its strategy for handling any SQL re/uest that attempts tomodify a column with new data that +iolates R,& Triggers can e estalished to implementeither the Cascade or Nullify strategies&

Triggers are a new form of o(ect in the Teradata dataase& They are designated with a typeof ;I; seen with a =0L4 "T#S0 re/uest& $y guess is that the de+elopers could not use;T; ecause of tales and the ;R,; reminded them of referential integrity) so ;I; was the ne.tcharacter in TR,II0R& The ""L statements used with triggers are: CR0T0) "R34)

Page 368: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 368/401

R04LC0) LT0R) =0L4 and S=32& These statements manage trigger usage andmaintenance& The appropriate dataase pri+ileges are needed to use any of thesecommands&

Terminology

Triggering &tatement

The user's initial SQL maintenance re/uest that causes a row to change in a tale and thencauses a trigger to fire !e.ecute%&

,t can e: ,NS0RT)54"T0)"0L0T0),NS0RTFS0L0CT

,t cannot e: S0L0CT

Triggered &tatement

,t is the SQL that is automatically e.ecuted as a result of a triggering statement&

,t can e: ,NS0RT) 54"T0)"0L0T0),NS0RTFS0L0CT)

 #3RTFR3LL#CJ)060C

,t cannot e: #0I,NF0N"TRNSCT,3N)C3$$,T)C=0CJ43,NT)S0L0CT

Logic %lo

The operations performed y a trigger are defined in the "ata "ictionary !""% and stored asan SQL o(ect& 2hene+er a user issues any SQL re/uest that modifies a row) a column or tale that has a trigger defined on it) the trigger SQL is eligile to also e.ecute&

,t ecomes the ;memory; for all suse/uent update operations without a person needing torememer to make the appropriate changes on one or more other tales&

The original user SQL is the triggering statement on the Su(ect tale& The suse/uent)automatic update to a different tale is the triggered statement&

Page 369: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 369/401

C"EATE T"I88E" &ynta.

"o Trigger 

The first synta. shown elow is a row trigger& ,t can ;fire; multiple times for each triggeringstatement) once for e+ery row changed in the tale& 2hen using the R32 type of trigger) theR0-0R0NC,NI statement pro+ides names for the efore image of a row +ia the key phrase

3L" S and also the after image of a row +ia using N02 S&

4rior to Teradata <8R7) a row trigger could perform any +alid "$L statement e.cept aS0L0CT& Since <8R7) it is a more NS, standard implementation and can only perform an,NS0RT&

The asic format and synta. to create a row trigger:

CR0T0 TR,II0R KTrigger*name

  KTR,II0R CT,3N P#0-3R0 -T0R ,NST0" 3-

Page 370: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 370/401

3R"0R Kse/uence*numer O

  KTR,II0R,NI CT,3N P,NS0RT 54"T0 "0L0T0 ,NS0RTFS0L0CT

3- !Kcolumn*name) &&& % O 3N Ksu(ect*tale

R0-0R0NC,NI 3L" S Kefore*imaged*row

  N02 S Kafter*image*row

  -3R 0C= R32

  2=0N !optional condition% O

  ! KTR,II0R0" CT,3N P ,NS0RT ,NS0RTFS0L0CT H %

H

 dditional discussion and e.amples are presented to enhance understanding of trigger useafter a discussion of a Statement trigger&

&tatement Trigger 

The second synta. elow is for a STT0$0NT trigger& ,t will only fire once for each

triggering statement& 2hen using the STT0$0NT type of trigger) the R0-0R0NC,NI willuse 3L"WT#L0 for all efore image rows and N02WT#L0 for all after image rows&

The asic format and synta. to create a statement trigger:

CR0T0 TR,II0R KTrigger*name

  KTR,II0R CT,3N P#0-3R0 -T0R ,NST0" 3-

3R"0R Kse/uence*numer O

  KTR,II0R,NI CT,3N P,NS0RT 54"T0 "0L0T0 ,NS0RTFS0L0CT

3- !Kcolumn*name) &&& % O 3N Ksu(ect*tale

R0-0R0NC,NI 3L"WT#L0 S Kefore*image

  N02WT#L0 S Kafter*image  -3R 0C= STT0$0NT

  2=0N !optional condition% O

  ! KTR,II0R0" CT,3N P ,NS0RT ,NS0RTFS0L0CT 54"T0 "0L0T0

  #3RTFR3LL#CJ 060C H % H

To CR0T0 a trigger) a uni/ue name must e chosen within a dataase for the new o(ect&Then) chose a trigger action from the three types to dictate when the trigger will e.ecute)they are: #0-3R0) -T0R) and ,NST0" 3-& The implication here regards when thetrigger fires& ,t either fires #0-3R0 the user re/uest) -T0R the user re/uest or ,NST0"3- the user re/uest&

The optional 3R"0R designation is used to se/uence the firing of triggers& This is only aconsideration when more than one trigger is ased on the same trigger action !#0-3R0)

 -T0R or ,NST0" 3-%& -or instance) if there is one #0-3R0 and one -T0R trigger) thenlogically the #0-3R0 fires first and the -T0R fires last& -or more information on 3R"0R)see the Se/uencing Triggers section later in the chapter&

Ne.t) determine the action that is to cause the trigger to e.ecute& There are four types of SQL triggering statements that can cause a trigger to fire) they are: ,NS0RT),NS0RTFS0L0CT) 54"T0) and "0L0T0&

Page 371: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 371/401

2hen the triggering statement is an 54"T0) the optional 3- portion is proaly needed& ,tnames one or more specific column!s% to monitor for a change in the data& ,f data) in allcolumns named in the 3-) is changed the trigger will fire& 3therwise) if the data is changed inonly one of the columns) the trigger does not fire& ,t is all or nothing regarding the columnseing monitored for a change& 2hen the 3- is not used) the +alue in e+ery column mustchange in order for the trigger to fire&

The tale name specified y the 3N is referred to as the su(ect tale& ,t is the tale to echanged y the triggering statement !user re/uest%& trigger can only ha+e one su(ecttale&

 lthough there are oth 3L" S and N02 S references) they are only e used together when an 54"T0 is the triggering statement& The 54"T0 must ha+e an e.isting row tomodify& Therefore) a efore image and a modified after image oth e.ist&

2hen the triggering statement is an ,NS0RT) there is only a N02 S reference nameecause there is only a new row and not an old row& Con+ersely) when the triggeringstatement is a "0L0T0) there is only an 3L" S reference name ecause the row no longer e.ists&

The optional 2=0N designator pro+ides a last conditional test to make efore actuallye.ecuting the trigger& -or instance) it might check the time of day or perform a su/uery!only place a S0L0CT is allowed% to check for a specific +alue) such as an ,N or N3T ,N& san e.ample) a test might e performed to determine the amount of work in+ol+ed using aC35NT and if too many rows are in+ol+ed) delay the triggering statement until later& Thetrigger will fire only if the 2=0N test compares true&

Lastly) determine the TR,II0R0" CT,3N& ,t is an SQL triggered statement that wille.ecute as a result of the triggering statement& There are si. SQL statements that can e atriggered statement) they are: ,NS0RT) ,NS0RTFS0L0CT) 54"T0) "0L0T0) 060C and

 #3RTFR3LL#CJ& Rememer that a trigger is part of a transaction and cannot egin anew transaction&

BE%$"EZ Trigger 

The #0-3R0 trigger is e.ecuted prior to the maintenance re/uested y the user's clientapplication& 3nce the trigger has successfully completed) the actual modification of therow!s% in the su(ect tale is done for the user&

The following creates a #0-3R0 trigger on the 0mployee tale to pro+ide a Cascade formof R, y making sure that the "epartment tale contains the department in which the newemployee works:

CR0T0 TR,II0R R,WCascadeWTrig

  #0-3R0 ,NS0RT 3N 0mployeeWtale

  R0-0R0NC,NI N02 S aftrow

  -3R 0C= R32

2=0N ! aftrow&deptWno N3T ,N !S0L0CT "eptWno -R3$ <alidW"eptWtale%%

!,NS0RT ,NT3 "epartmentWtale

  <L50S !aftrow&deptWno) 'New "epartment')N5LL)N5LL%H% H

This is a row trigger ecause it contains -3R 0C= R32& ,t is e.ecuted once for each rowinserted into the 0mployee tale and each triggered ,NS0RT only inserts a single row if thedepartment for the new employee is not a +alid department +erified against the department

Page 372: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 372/401

tale& This re/uest is not allowed if the su/uery in the 2=0N references the su(ect tale&Therefore) the <alidW"eptWtale is re/uired to allow that test&

3ther than checking another tale) a #0-3R0 trigger might e useful for making anad(ustment in another tale efore making the final modification in the su(ect tale& ,n other words) if the update might cause a R, error) the trigger can prepare the other tale toconform to an R, constraint efore the original update gets re(ected& -or instance) if a"epartment were eing deleted) the trigger could change the department numer for allemployees to N5LL efore the deletion of the department row& This is an e.ample of theNullify Strategy for R,&

A%TE"Z Trigger 

The -T0R trigger is e.ecuted or fired suse/uent to the original update re/uested y theuser's client application& 3nce the trigger has successfully completed) the user re/uest partof the transaction is finished&

The following creates an -T0R trigger on the 4arts tale to insert an audit row into the4rice Log tale if the price is changed& =owe+er) the trigger only fires if the increase is

greater than 19U:CR0T0 TR,II0R 5pdateWTrig

 -T0R 54"T0 3- !price% 3N parts

  R0-0R0NC,NI 3L" S eforerow

  N02 S afterrow

  -3R 0C= R32

:;EN ( (a,terroprice 1 !e,oreroprice) # !e,oreroprice 4 06)

! ,NS0RT ,NT3 priceWlog +alues !afterrow&partWnum) eforerow&price)

  afterrow&price) date%H % H

This is also a row type of trigger& Therefore) it will e e.ecuted once for each and e+ery rowthat is affected y the original update SQL re/uest&

=ere a 2=0N determines whether or not the trigger fires& -or small price increases) thetrigger does not fire) ut instead) only for a price change of more than 19U& 2ithout a 2=0Ntest) the trigger fires e+ery time the triggering statement makes a change&

 n -T0R trigger is helpful to make an ad(ustment in one tale ased on a change made tothe su(ect tale& -or instance) if a new manager were assigned to a department in thedepartment tale) all the rows for employees are updated automatically to reflect the samechange in the employee tale& This is an e.ample of the Cascade Strategy for R,&

IN&TEA $%Z Trigger 

The ,NST0" 3- trigger pro+ides the aility to e.ecute the trigger and not do the user'sclient application re/uest at all& 3nce the trigger has successfully completed) the transactionis finished&

The following ,NST0" 3- trigger is created on the parts tale to insert an audit row into thedelay tale indicating that an 54"T0 on the parts tale should ha+e taken place& =owe+er)ecause it was going to impact more than 19 rows in the su(ect tale) it was not performed:

CR0T0 TR,II0R "elay5pd

Page 373: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 373/401

,NST0" 3- 54"T0 3- !price% 3N parts

  R0-0R0NC,NI 3L"WT#L0 S oldta

  N02WT#L0 S newta

  -3R 0C= STT0$0NT

2=0N ! 19 K !S0L0CT C35NT!partWnum% -R3$ oldta

  2=0R0 partWnum M oldta&partWnum% %

! ,NS0RT ,NT3 "elayWTa

  S0L0CT "T0) T,$0) '5pd') newta&partWnum) newta&price

  -R3$ newta 2=0R0 newta&partWnum M partWnum H % H

Since the update on the parts tale was not performed) it proaly needs to e made atanother time& This actual update ecomes someone's responsiility& This is a time when thefle.iility to not make the change adds responsiility to manually make the change later&=owe+er) the rows in the delay tale can e used +ia a (oin to actually make the update&

Cascading Triggers

  cascading trigger results when a triggering statement fires a trigger) which in turn firesanother trigger& The situation is such that the tale eing updated y the first trigger also hasa trigger associated with it and ecomes the new su(ect tale& Then the second trigger updates a tale that has a trigger associated with it& So) each triggered statement in turnecomes a triggering statement&

The only thing a trigger cannot do is to change the su(ect tale on which the trigger isdefined& =owe+er) a suse/uent trigger may come ack and update the original su(ecttale& Caution should e e.ercised here so that the triggers do not cascade indefinitely& Thisconstitutes an infinite loop and will cascade until they run out of either 4ermanent or Transient @ournal space) or the transaction is aorted&

Page 374: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 374/401

Cascading Trigger e.ample:

,n this cascade e.ample) there are three tales: CasTlW1) CasTlW8 and CasTlW& 0achtale is defined with two columns called: Col1 and Col8& t the eginning of the process) allthree tales are empty&

 ll three tales use asically the same CR0T0 T#L0 to uild the initial definitionsH onlythe names ha+e een changed&

CR0T0 T#L0 CasTlW1

 !Col1 smallint) Col8 smallint%H

CR0T0 T#L0 CasTlW8

 !Col1 smallint) Col8 smallint%H

CR0T0 T#L0 CasTlW

 !Col1 smallint) Col8 smallint%H

Page 375: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 375/401

Page 376: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 376/401

Rememer the one thing to a+oid when using cascading triggers& "o not create a trigger oneither CasTlW8 or CasTlW that will insert a row into CasTlW1& This causes an indefiniteloop of the ,NS0RT operations that will continue until aorted&

&e>uencing Triggers

 ll of the pre+iously discussed triggers were independent from each other ecause the areon different tales and ha+e a different CT,3N& Therefore) the se/uence in which they arefired does not matter& =owe+er) sometimes the se/uence does matter& 2hen this is thecase) another mechanism must e used to guarantee that the triggers are fired in the proper se/uence to insure that all modifications are made in the correct 3R"0R&

The 3R"0R option allows for the definition of a se/uence numer to e associated witheach trigger& <alid +alues are 1 through 8)DED& ll triggers with an 3R"0R of 1) fire eforethe first 3R"0R 8 trigger& ll the 3R"0R 8 triggers fire efore the first and so on untilthere are no more triggers associated with the initial triggering statement&

This 3R"0R process continues until there are no more triggers) or until a triggered action

fails& Rememer) that triggers are always part of a transaction and if part of a transactionfails) it stops and e+ery operation to that point must R3LL#CJ& 2hen 3R"0R is notspecified) it defaults to a +alue of 8)DED& Triggers with the same 3R"0R +alue firerandomly until the last one with that same +alue finishes&

 s an e.ample) instead of using the cascading triggers seen pre+iously) it might e desiraleto ha+e oth triggers defined on CasTlW1& That way) no ,NS0RT need e performed onCasTlW8) only on CasTlW1) as seen with the two triggers created elow:

CR0T0 TR,II0R ,NSTrig1

  -T0R ,NS0RT 3N CasTlW1 3R"0R 199

  R0-0R0NC,NI N02 S afterrow

  -3R 0C= R32

! ,NS0RT ,NT3 CasTlW8 +alues !afterrow&col1X1) eforerow&col8G8% H

CR0T0 TR,II0R ,NSTrig8

  -T0R ,NS0RT 3N CasTlW1 3R"0R 899

  R0-0R0NC,NI N02 S afterrow

  -3R 0C= R32

! ,NS0RT ,NT3 CasTlW +alues !afterrow&col1X8) eforerow&col8G7% H

Since oth of the ao+e triggers are -T0R ,NS0RT) they oth ha+e the same trigger action&,n this e.ample) it was decided that ,NSTrig1 should fire efore ,NSTrig8 ecause its +alue inthe 3R"0R is less& The result will e identical if the 3R"0R is not specified for ,NSTrig8ecause the +alue of 199 is less than 8)DED& 5sing the 3R"0R allows this le+el of control)

ut it is optional and only needed to control se/uencing& 2ithout the 3R"0R) they are oth8)DED and fire randomly&

Chapter 81: &tored Procedures

Page 377: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 377/401

Teradata &tored Procedures

Compatiility: NS,

,n <ersion 8 Release 7) Teradata pro+ides Stored 4rocedural Language !S4L% to createStored 4rocedures& These procedures allow the comination of oth SQL and S4L control

statements to manage the deli+ery and e.ecution of the SQL&

Teradata used always had a scripting language in its utilities) such as #T0Q) to manageloops) conditional tests and processing on the host computer& To differentiate SQL and thescripting language) most of the utilities use a dot !&% command and the Teradata Call Le+el,nterface !CL,%&

Later) more standard tools were introduced to access rows stored within Teradata& ,nstead of using the Call Le+el ,nterface directly) they call the 3pen "ata #ase Computing !3"#C%software for connecti+ity across a network&

The call structure for the 3"#C is standard& $ost dataase +endors pro+ide an 3"#Ce.ecutale for their dataase to con+ert the 3"#C calls into calls for the proprietary CL,&The ad+antage of this techni/ue ecomes apparent in that more tools are made a+ailale to

all users to access any dataase that has an 3"#C connection& =owe+er) ecause thesetools are interacti+e and 3"#C ased) they do not normally ha+e a scripting language&

3ne of the ad+antages to stored procedures is that they are stored and e.ecuted within theTeradata dataase and not as a separate utility on a different computer& Therefore) the S4Lcommands are a+ailale for e.ecution from all tools and not (ust those with their ownscripting language&

Stored procedures constitute a ma(or departure from the way ;normal; SQL works withinTeradata) like a macro& The following chart lists the differences etween macros and storedprocedures&

%igure 9010 

2riting a stored procedure is more like writing a program than writing a macro& The macrocontains only SQL and maye dot commands that are only for use in #T0Q& Normally aS0L0CT results in rows eing returned to the user& stored procedure does not return rowsto the user like a macro& ,nstead) the selected column or columns must e used within theprocedure&

  stored procedure contains SQL to access data from within Teradata& =owe+er) it mustcontain S4L to control the e.ecution of the SQL& stored procedure is a it like writing a

script in the Support 0n+ironment front*end for $ultiLoad) T4ump or -ast0.port& The ma(or difference with stored procedures is that the language is much more comprehensi+e) allowsthe S0L0CT and is NS, standard&

Like a macro) stored procedures allow parameter +alues to e passed to it at e.ecution time&5nlike a macro that allows only input +alues) a stored procedure also pro+ides outputcapailities& stored procedure only returns output +alues to a user client as outputparameters) not as rows&

Page 378: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 378/401

2e normally think of the client as eing the re/uestor and Teradata eing the ser+er& 2henusing stored procedures) another layer is added& 2hen a procedure is called) it is a ser+er tothe user program& =owe+er) it normally interfaces with Teradata on the ehalf of the client&The only way to do that is to ecome a client too& So) a procedure plays oth roles& This is a*tiered en+ironment where: Tier 1 is the user as a client) Tier 8 is the procedure as first aser+er and then as a client and Tier is Teradata as a ser+er& The procedure acts as aser+erFclient in that it is first a ser+er to the user and then a client to Teradata in order toretrie+e one or more rows to ser+ice the user re/uest&

The processing flow of a procedure is more like a program& ,t is a procedural set of commands) where SQL is a non*procedural language& s mentioned earlier) it does notreturn rows to the user& Therefore) the use of a S0L0CT) 54"T0 or "0L0T0 statementthat processes multiple rows will need to e managed within the stored procedure& ,n other words) you cannot code a simple procedure with S0L0CT G -R3$ Ktale*name& procedure is not a macro and a macro is not a stored procedure&

The intent of this chapter is to show and e.plain the commands as well as the techni/ue for a successful implementation of procedures& ,t pro+ides a asis to understand and egin touse stored procedures& The synta. for S4L is +ery fle.ile and powerful& So) each commandwill e discussed indi+idually with an e.ample demonstrating it& The e.amples will increase

in comple.ity and functionality as more S4L commands are introduced&

 lthough ""L is not allowed within a procedure) ""L must e used to implement a storedprocedure& The ""L is used to CR0T0 a procedure& dditionally) you will need a recentrelease of Queryman and the 3"#C in order for the CR0T0 4R3C0"5R0 statement to erecognied and sent to Teradata&

C"EATE P"$CE'"E

  stored procedure is created like all Teradata o(ects& =owe+er) it is stored as ane.ecutale piece of code& To e e.ecutale) it must e compiled as part of the CR0T0re/uest& 3nce compiled) the S4L is stored in a user dataase as an o(ect& ,t is a new kindof o(ect and seen as a ;4; when using a =0L4 5S0R or =0L4 "T#S0 re/uest&

The following is the asic synta. to CR0T0 a procedure:

CR0T0 4R3C0"5R0 Kdataase*name&OKprocedure*name

! Kparameter*list O %

Kprocedure*ody

H

The Kparameter*list is optional& 2hen used) it allows parameter +alues to e sent to theprocedure& They also allow for parameter +alues to e passed ack to the client& $ost of thetime) a procedure will use parameters&

The Kprocedure*ody contains the S4L coding necessary to accomplish the processingdesired of the stored procedure&

&tored Procedural Language (&PL) &tatements

Page 379: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 379/401

2ithin the create re/uest of a procedure) called the procedure ody) there will normally e"ata $anipulation Language !"$L% and S4L& 5sing "ata "efinition Language !""L% and"ata Control Language !"CL% is not currently permitted within a procedure&

The "$L has already een co+ered in this ook& This chapter primarily concentrates on theS4L& The only e.ception will e a discussion on S0L0CT) 54"T0 and "0L0T0 regardingcursors and the new S0L0CT*,NT3 for setting initial +alues of +ariales in a procedure&

The Kprocedure*ody may contain any or all of the following S4L commands:#0I,N F 0N" > "efines scope and functionality of the procedure odyCLL Y 0.ecutes a procedure from a procedure"0CLR0 Y 3ptional) estalishes local +ariales or handler routines for use

within the procedure-3R F 0N" -3R Y llows for a cursor to process commands for each row fetched

from Teradata ,- F 0N" ,- * 4ro+ides for a conditional test of a +ariale ,T0RT0 * Skips rest of the statements after the iterate statement and continues

with the iteration of the logicL0<0 Y llows for an e.it from a loop

L334 F 0N" L334 Y "efines the processing logic to repeat unconditionally4R,NT Y ids in testing and deugging of a new procedureS0T Y ssigns a +alue to a +ariale or parameter 2=,L0 F 0N" 2=,L0 Y 0stalishes a conditional test prior to doing a logic loop

These commands ha+e een listed ao+e in alphaetic se/uence& They are normally writtenin a se/uence to accomplish a specific task& 0ach of these is discussed elow in more detailwith e.amples to demonstrate their functionality&

The synta. of the Kprocedure*ody must contain a #0I,N and 0N" comination statementformatted as:

Klael*name:O #0I,N

  Klocal*+ariale*declaration O

  Kcondition*handler*declaration O

  Kstatement*list O

0N" Klael*name O

H

BE8IN # EN &tatements

The #0I,N and 0N" specifications are oth re/uired and they define the ody of theprocedure& ll other S4L commands will e contained within the oundaries delineated ythese two statements& gain) they are oth re/uired and ecause of the dependency oneach other) they are referred to as a compound statement

The following is the synta. of the #0I,N and 0N" commands:

Klael*name: O#0I,N

0N" Klael*name O H

3ptionally) a #0I,N may specify a lael name to identify the S4L section within theprocedure& 2hen a lael name is desired) it connects to the #0I,N +ia a colon !:%& The 0N"will only use a lael name if one is defined on the #0I,N& lael name is optional whene+er 

Page 380: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 380/401

there is a single section of S4L& 2hen multiple sections !more than one #0I,N and 0N"statements% are used) the interior sections must ha+e a lael name&

The ne.t tale is used in the ne.t e.amples:

%igure 9019 

%igure 901@ 

The following demonstrates a simple procedure with a single section used to ,NS0RT a rowwith all null +alues into the Customer tale:

CR0T0 4R3C0"5R0 -irstW4rocedure ! %

BE8IN

  ,NS0RT ,NT3 CustomerWtale 2,T= "0-5LT <L50SH

ENH

 fter the e.ecution of the ao+e procedure) the ne.t S0L0CT returns:

S0L0CT G -R3$ C5ST3$0RWT#L0H

E Rows ReturnedCustomer7num!er Customer7name Phone7num!er  

11111111 #illy's #estChoice

*187

1111 cme 4roducts *1111

1817 C0 Consulting *1818

DBAEBB 6Z 4luming 7D*BA7

BD87E "ataases N*5 88*1918

Notice that a separate S0L0CT !outside the procedure% is needed to see the row of null+alues instead of returning them from the procedure& The only output to the client from thee.ecution of this procedure is a resultant status code& ,t indicates either a successfulcompletion or a failure in the procedure&$ore discussion will appear in this chapter to e.plain why this is the case& -or now) suffice itto say that a stored procedure can't return rows to the client as noted in -igure 81*1&

Page 381: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 381/401

The following demonstrates a techni/ue to nesting one section within another using a laelname on the inner section:

CR0T0 4R3C0"5R0 -irstW4rocedure ! %

BE8IN

  ,NS0RT ,NT3 CustomerWtale 2,T= "0-5LT <L50SH

  &econd&ection/BE8IN

  "0L0T0 -R3$ 3rderWtale 2=0R0 CustomerWnumer is N5LLH

  EN &econd&ection=

EN=

,n oth of these e.amples) the indentation is optional and used y us to assist inunderstanding how the coding works& The first section does not use the optional lael for the#0I,N and 0N"& ,t contains an ,NS0RT into the Customer tale& Then) another #0I,N andan 0N" called SecondSection is used& This S4L section contains a "0L0T0 from the order tale& The 0N" for SecondSection comes efore the 0N" for the first #0I,N and specifiesthe lael name SecondSection as defined in the #0I,N& ,t is nested within the first #0I,Nand last 0N" as compound statements&

The normal flow is from top to ottom& So) the customer ,NS0RT is performed first) then theorder "0L0T0 is performed& lthough this same processing occurs without a nested#0I,N F 0N" for SecondSection) it introduces this techni/ue for use with other commandsco+ered elow and the aility to allow repeated processing of one or more sections& ,t maynot always e desirale to repeat all the commands) only specific ones& The procedure muste written to manage all desired processing&

Like all CR0T0 statements) the procedure name may e /ualified to re/uest its creation ina particular dataase& The parameter list is optional as in a macro& =owe+er) theparentheses are not optional and must e coded) e+en without parameters& 2hen used) theparameters are normally included to make the procedure more fle.ile and pro+idecommunications with the outside world regarding each e.ecution& The procedure ody

contains S4L to manage the e.ecution of the SQL& The setup and use of parameters andS4L is co+ered progressi+ely in this chapter to facilitate learning how to use S4L&

Esta!lishing aria!les and ata alues

  stored procedure can e written to pro+ide additional functionality y naming local+ariales to store and manipulate +alues& The +ariales recei+e their +alues either y einge.plicitly assigned internally or passed from the client that calls the procedure& S0Tstatement is used to assign a +alue to a +ariale within a procedure& The +alue may e aliteral or an e/uation& =owe+er) efore using a +ariale name) the name and the data typemust e defined& "0CLR0 statement is used to estalish the +ariale& #oth of thesecommands are co+ered ne.t&

ECLA"E &tatement to e,ine aria!les

The "0CLR0 is primarily used to estalish a local +ariale name for use within the storedprocedure& The +ariale is called a local ecause the name is only a+ailale within theprocedure&

The synta. for defining one or more +ariales is:

Page 382: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 382/401

"0CLR0 K+ariale*name*list Kdata*type "0-5LT Kinitial*+alue O H

The +ariale name list may contain one or more +ariale names& =owe+er) only a single datatype may e defined within an indi+idual "0CLR0 statement& So) if three +ariales areneeded and each one is a different data type) three "0CLR0 statements are re/uired&=owe+er) if all three +ariales are of the same data type) only a single "0CLR0 is needed&

 t the same time) it is permissile to use one "0CLR0 for each +ariale regardless of itsdata type& This might e the case when all three +ariales need to start with an differentinitial +alue in each one using the "0-5LT&

Two +ariales in the same procedure may not ha+e the same name& Names must e uni/uewithin procedures (ust as they must e uni/ue within a macro or dataase& dditionally) a+ariale name cannot e any of these reser+ed Status +ariale names:

SQLC3"0 SQLSTT0  CT,<,TWC35NT

The data type declared must e +alid within Teradata) like in a CR0T0 T#L0 re/uest&

3ptionally) a "0-5LT +alue may e specified& 2hen this is done) e+ery time the procedure

is e.ecuted) the +ariale is automatically e set to the +alue specified& 3therwise) it willcontain a N5LL +alue& The "0-5LT +alue) if specified) applies to all +ariales specified in asingle "0CLR0 statement&

The scope or +alidity of a local +ariale is the #0I,NF0N" lock& ccess to the +alue in alocal +ariale is not directly a+ailale from outside of the procedure& local +ariale may eused within SQL& 2hen it is specified in an SQL statement) it must e prefi.ed with a colon!:%& The colon indicates that sustitution is to occur& t e.ecution time) the +alue stored in the+ariale is sustituted into the SQL in place of the name& Then) the SQL statement ise.ecuted&

The ne.t procedure defines +ar1 as a local +ariale and assigns an initial +alue using a"0-5LT and then sustitutes the +alue into the 2=0R0 clause of a "0L0T0:

CR0T0 4R3C0"5R0 SecondW4rocedure ! %

 #0I,N

  ECLA"E <ar0 INTE8E" E%A'LT 00000000=

  "0L0T0 -R3$ CustomerWtale 2=0R0 CustomerWnumer M /<ar0H

0N"H

This e.ample is only a uilding lock approach to writing stored procedures& This procedureis not fle.ile enough to delete any other row from the tale& Therefore) it is a single useprocedure& procedure is most eneficial when it is used multiple times y multiple users&#y incorporating other S4L and SQL) it will e+ol+e into a useful procedure&

&ET to Assign a ata alue as a aria!le

The S0T statement is an assignment statement& 3nce the +ariale name and data type ha+eeen defined) a +alue needs to e assigned& s seen ao+e) the "0-5LT can estalish aninitial +alue& 3therwise) a +alue can e assigned or S0T within the procedure& Then) it mayretain the initial +alue throughout the life of the procedure) or may e modified at any timeusing a S0T command&

Page 383: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 383/401

The synta. for the S0T statement follows:

S0T Kassignment*target M Kassignment*source H

The assignment target can e either a local +ariale or a parameter& 4arameters are co+eredlater&

The assignment source can e any of the following: a literal +alue) a local +ariale) a status+ariale) a parameter) an SQL CS0 e.pression) a cursor) a column) an alias name) or amathematical e.pression&

The following is an alternate SecondW4rocedure used to S0T the +alue instead of using"0-5LT:

CR0T0 4R3C0"5R0 SecondW4rocedure ! %

 #0I,N

  "0CLR0 +ar1 ,NT0I0R H

  &ET <ar0 ? 00000000 H

  "0L0T0 -R3$ CustomerWtale 2=0R0 CustomerWnumer M /<ar0H

0N"H0+en the S0T y itself is still limited) the ne.t section  pro+ides the est techni/ue for assigning data +alues to a procedure with +alues passed as parameters&

&tatus aria!les

These status +ariales are pro+ided within the procedure ody to determine the outcome of operations re/uested: SQLSTT0

SQLC3"0

 CT,<,TWC35NT

C=R !%

S$LL,NT

"0C,$L !1B)

9%

  successful completion will assign the +alue of ero to each of the SQLSTT0 andSQLC3"0 +ariales& Since SQLSTT0 is a C=R field) it will e ]99999^ for comparisonpurposes& 3ther +alues should e referenced in the <8R7 Reference manual to determinewhat occurred for deug or correction purposes&

There is another reser+ed name for use in determining that an SQL error occurred& ,ts nameis SQL06C04T,3N and is handy in checking for any non*ero outcome& ,t ecomes theunknown or unspecified outcome) ut is still considered an error condition& Checking for oneor more specific outcomes is the purpose of SQLSTT0&

 gain) these are all ;read only; +ariales and cannot e used in the S0T assignmentstatement as the assignment target&

Assigning a ata alue as a Parameter 

Like macros) stored procedures may recei+e information passed from the client software&This aility pro+ides much more fle.iility and enhances the power of stored procedures&

5nlike macros) a stored procedure can return a parameter +alue to the calling user or routine& macro can only return the output rows from a S0L0CT or status code to indicatethe success or failure of the macro& This parameter output capaility allows the stored

Page 384: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 384/401

procedure a way to offer functionality different than a macro& "epending on the functionalityneeded) either a macro or a stored procedure might e written&

2hen using parameters in a stored procedure) the synta. for a parameter list is comprisedof these three elements:

Kparameter*usage Kparameter*name Kdata*type

2here each element is defined as: Kparameter*usage can e one of these:

o ,N only pro+ides input from the caller !default%

o 35T only pro+ides output to the caller o ,N35T allows oth input and output for the caller 

Kparameter*name is any +alid Teradata SQL name Kdata*type is any +alid Teradata data type

The following is an alternati+e to and a etter +ersion of SecondW4rocedure that passes the+alue for +ar1 instead of using a "0CLR0 or S0T:

CR0T0 4R3C0"5R0 SecondW4rocedure !IN <ar0 INTE8E" %

 #0I,N  "0L0T0 -R3$ CustomerWtale 2=0R0 CustomerWnumer M /<ar0H

 0N"HThe +alue of +ar1 dynamically comes from the client at e.ecution time& ,t is no longer fi.edy the "0CLR0 or the S0T commands& The fle.iility now e.ists within SecondW4rocedureto delete any row from the tale& -urthermore) there is no re/uirement to change theprocedure e+ery time a different row need s to e deleted& The CLL statement for thisprocedure appears in the ne.t section along with a discussion on its use and the passing of parameter +alues&

Considerations for parameter definition:   parameter is +alid throughout the entire stored procedure ,f a parameter is referenced within an SQL statement) it must e prefi.ed

with a colon !:% to tell the optimier that it is a +ariale name and not ano(ect name

  parameter name cannot e any of these names since they are reser+ed for status +ariale names:

o SQLC3"0o SQLSTT0o  CT,<,TWC35NT

The "0-5LT clause cannot e specified for parameters to estalish aninitial +alue

,N parameters cannot e part of the assignment target for any S4L or SQLstatement

35T parameters cannot e part of the assignment source for any S4L or 

SQL statement

Additional &PL &tatements

This section of the ook discusses and demonstrates the S4L commands allowed within theody of the stored procedure& The first thing to notice is that they are not co+ered elow inalphaetic se/uenceH like the list ao+e&

Page 385: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 385/401

2e struggled with this departure& =owe+er) it is done in this manner to gradually uild up tothe more in+ol+ed capailities of the commands) like using a -3R loop& 2e elie+e you wille grateful for this approach y the end of the chapter&

CALL &tatement

The CLL is used to e.ecute a stored procedure& The CLL statement is normally e.ecutedeither y a client program or interacti+ely y a user& dditionally) a stored procedure isallowed to call another stored procedure&

The synta. to CLL a stored procedure:

CLL Kdataase*name&OKstored*procedure*name ! Kparameter*list O % H

The procedure name can e /ualified with a dataase name to guarantee the correctprocedure is used& parameter list is only used when the procedure is e.pecting ,Nparameter +alues passed to it& The list must match the e.act numer of parameters in theprocedure& Rememer) e+en if you are not passing parameter +alues in the parameter list)you must still code the ! % open parenthesis and close parenthesis to call the procedure&

The following CLL e.ecutes the first procedure shown ao+e:CLL -irstW4rocedure ! %H

Since the -irstW4rocedure does not define any parameters) none are passed to it& =owe+er)SecondW4rocedure has e+ol+ed to the point of e.pecting a parameter the +alue at run timeto identify the row to delete& The ne.t CLL e.ecutes the SecondW4rocedure and passes the+alue of 11111111:

CLL SecondW4rocedure!11111111%H

Now) the procedure can e called again and a different row can e deleted using:

CLL SecondW4rocedure!1111%H

This is where a stored procedure is most eneficial& 3ne procedure performs an operationthat is needed more than once& The est situation for creating a stored procedure e.istswhen the e.ecution of the same operation is needed more than once and y more than oneuser&

5sing a procedure makes the operation +ery consistent ecause the statements are notrewrittenH they are stored in Teradata& ,t is +ery efficient ecause the statements are nottransmitted across the networkH they are stored& ,t is +ery easy ecause the only re/uest isto call the procedure&

Considerations when e.ecuting the CLL: 5ser must ha+e 060C5T0 4R3C0"5R0 pri+ilege on the stored procedure

o(ect or on the containing dataase Cannot e specified in a multi*statement transaction Numer of arguments must match the numer of parameters in the stored

procedure   +alue e.pression as a call argument must not reference tales Can e the only statement in a $CR3 Can return at most) one row response ,f a +alue e.pression is used as a call argument !colon preceded identifiers%

must refer to +ariales associated with a 5S,NI clause for the re/uester issuing the CLL

Page 386: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 386/401

T,TL0) -3R$T) and N$0" phrases can e specified with the callarguments +ia an SQL CST function

 n ,N and ,N35T argument must e a +alue e.pression  n 35T argument must ha+e a placeholder !35T parameter name% The +alues placed into the ,N35T and 35T parameters are returned to

client

  +alue e.pression of N5LL can e used to initialie one or more parametersto a N5LL

I% # EN I% &tatement

 n ,- statement can e used within a procedure to e+aluate the result of a comparison& ,tcan check the outcome of an operation or compare the contents of a +ariale& ,t has a T=0Nportion for a TR50 comparison and an optional 0LS0 when -LS0& dditionally) there is anoptional 0LS0,- to nest or imed another comparison within the ,- processing& The ,-statement is delineated y an 0N" used to specify the end of the conditional processing&

The synta. of the ,- statement follows:

,- Kcondition*testT=0N Kstatement*list

0LS0 Kstatement*list O

0LS0,- Kcondition T=0N Kstatement*list 0LS0 Kstatement*list O O

0N" ,-H

The ne.t e.ample performs three ,- statement tests with literals to compare the +alues of the two input parameters:

CR0T0 4R3C0"5R0 TestW4roc

  !,N +ar1 #T0,NT) ,N +ar8 #T0,NT) 35T $sg C=R!89% %

#0I,N

I% <ar0 ? <ar9 T;EN S0T $sg M 'They are e/ual'H EN I%=

I% <ar0 3 <ar9 T;EN S0T $sg M '<ariale 1 less'H EN I%=

I% <ar0 4 <ar9 T;EN S0T $sg M '<ariale 1 greater'H EN I%=

0N"H

 lthough this works) it is not the most efficient way to code it& The ao+e procedure performsall three tests) e+en if the first test is TR50& This is due to the e.ecution se/uence from topto ottom& Therefore) one of the tests will always ;pass; with a TR50 and the other two willalways ;fail; with a -LS0 result) regardless of the +alues passed&

The following e.ample uses the ,- statement to make the same tests as ao+e) ut it ismore efficient using the 0LS0,- and 0LS0 portions in a single ,-) not three:

CR0T0 4R3C0"5R0 TestW4roc

  !,N +ar1 #T0,NT) ,N +ar8 #T0,NT) 35T $sg C=R!89% %

#0I,N

I% <ar0 ? <ar9 T;EN S0T $sg M 'They are e/ual'H

  EL&EI% <ar0 3 <ar9 T;EN S0T $sg M '<ariale 1 less'H

Page 387: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 387/401

  EL&E S0T $sg M ' <ariale 1 greater'H

  EN I%H

0N"H

2hen called with two +alues for +ar1 and +ar8) the procedure tests the +alues using the ,-for all possiilities: e/ual) less than and greater than& 2hen the e/ual test condition is

found to e TR50) the T=0N portion is used and the comparison is complete& ,f the+ariales are not e/ual) it then does the 0LS0,- test for +ar1 eing less than +ar8& ,f this testis TR50) it does the second S0T in the T=0N and now it is complete& =owe+er) if oth of these tests fail) the final 0LS0 is used to set a +alue for the message +ariale to indicate that+ar1 is less than +ar8&

The ao+e e.ample also demonstrates the usage of 35T for a parameter& The +alue placedinto the $sg +ariale will e returned to the calling client program& 5sing 35T and ,N35T isthe only way for a procedure to return data to a client&

The ne.t CLL statement demonstrates the use of TestW4roc y passing e/ual +alues to itand reser+es an area for the output message !msg%:

CLL TestW4roc!0J0Jmsg%H

Msg 7 

They are e/ual

The following CLL statement demonstrates the use of TestW4roc using the smaller numer first:

CLL TestW4roc !0J9Jmsg%H

Msg 7 

<ariale 1 less

The ne.t CLL statement demonstrates the use of TestW4roc using the smaller numer second:

CLL TestW4roc !9J0Jmsg%H

Msg 7 

<ariale 1 greater 

The client is responsile for pro+iding the correct numer of parameters to the CLL and inthe correct order& Since Queryman is used for these e.amples) the name of the 35Tparameter must e used in the CLL to properly connect the two statements !within theCLL and the CR0T0 4R3C0"5R0%&

L$$P # EN L$$P &tatements

The L334 and 0N" L334 define an unconditional loop& This means that the SQL and S4Lcontained in the logic loops or repeats indefinitely& Since looping indefinitely is not a goodthing) there must e a way to stop the loop when the processing is completed&

The synta. for the L334 F 0N" L334 follows:

Klael name:OL334

Page 388: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 388/401

  Kstatement*listH

0N" L334 Klael name O H

The lael name is optional unless putting a loop within a loop& =owe+er) when the laelname appears on the L334 statement) it must also appear on the 0N" L334 to connectthem together and define the statements to repeat&

The statement list in this synta. format contains S4L and "$L statements&

Since writing an indefinite loop is proaly a ad thing to do) an e.ample does not appear here& ,nstead) the L334 e.ample is comined with the L0<0 command) co+ered ne.t&

LEAE &tatement

The L0<0 is primarily used in con(unction with a looping or repeating set of logic ased onone of the looping S4L statements& The L0<0 pro+ides a way to e.it or lea+e the loop&Therefore) it will only e coded within a #0I,N) -3R) L334 or 2=,L0 section of repeatinglogic&

The synta. for L0<0 follows:L0<0 lael name O H

The following comines the L334 and L0<0 statements to estalish a conditional loop:

CR0T0 4R3C0"5R0 ,nserterW-i+e ! %

L3340R:#0I,N

  "0CLR0 Cntr ,NT0I0R "0-5LT 9H

  Loopit/L$$P

  S0T Cntr M Cntr X 1H

  ,- Cntr T=0N LEAE LoopitH

  0N" ,-H  ,NS0RT ,NT3 $yWLogWTl <L50S !:Cntr) C5RR0NTWT,$0%H

  EN L$$P Loopit H

0N" L3340RH

The ao+e procedure called ,nserterW-i+e incorporates many of the pre+iously discussedS4L commands& ,t shows all of the pieces needed to process and control a loop& -irst) the"0CLR0 estalishes a +ariale called Cntr and sets its initial +alue to 9 using the"0-5LT option& Second) it enters the loop and increments Cntr y adding 1 on eachrepetition of the loop& Ne.t) it tests the +alue in Cntr to see if it is greater than & 2hen it is)the loop is e.ited& 3therwise) the loop performs the ,NS0RT to store a row with the +alues of Cntr and the current time as columns into the $yWLogWTl tale&

The code allows the loop to repeat and ,NS0RT rows& This is ecause as soon as the ,-test determines that Cntr has reached E !1 greater than after the last addition%) the T=0Nperforms the L0<0 statement to e.it the loop& The L0<0 pre+ents the ,NS0RT from eingperformed indefinitely&

Page 389: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 389/401

:;ILE # EN :;ILE &tatement

The 2=,L0 and 0N" 2=,L0 are used to estalish a conditional loop& s long as thecondition is TR50) the loop of logic continues& 3nce the condition is no longer TR50) thelogic is e.ited&

 s seen ao+e) when using the L334 statement) the ,- and L0<0 statements can e usedto control the loop y adding a conditional test& The conditional test is uilt into the 2=,L0statement and tested each time the loop egins to repeat& So) at the top of the loop) whenthe test is TR50 the loop logic is performed& =owe+er) when the test fails at the top of theloop) the logic is skipped and not performed&

The synta. for the 2=,L0 F 0N" 2=,L0 follows:

Klael*name:O2=,L0 Kcondition*test

  "3

  Kstatement*listH

0N" 2=,L0 Klael*name O H

The statement list contains S4L and "$L statements&

The lael name is optional unless putting a loop within a loop& 2hen the lael name appearson the 2=,L0) it must also appear on the 0N" 2=,L0&

The following uses the 2=,L0 statement instead of the L334 and L0<0 to perform thee.act same conditional loop processing seen ao+e:

CR0T0 4R3C0"5R0 ,nserterW-i+e ! %

L3340R:#0I,N

  "0CLR0 Cntr ,NT0I0R "0-5LT 9H

  Loopit/:;ILE Cntr 3 D

  $  S0T Cntr M Cntr X 1H

  ,NS0RT ,NT3 $yWLogWTl <L50S !:Cntr) C5RR0NTWT,$0%H

  EN L$$P Loopit H

0N" L3340RH

The 2=,L0 statement ao+e tests Cntr for a +alue less than & 2hen it is) the loop ise.ecuted& The L334 and L0<0 e.ample used an ,- to test for Cntr greater than &Rememer) the 2=,L0 tests efore the loop and the ,- tests within the loop& #oth of thesee.amples inserted fi+e rows into the log tale&

%$" # EN %$" &tatementsThe -3R and 0N" -3R statements may also e used to perform loop control& =owe+er) itsoperation is consideraly different from oth L334 and 2=,L0& ,t is the most in+ol+ed andre/uires some additional logic and names that must e estalished when writing a procedurewith it& Therefore) it is eing presented after the other looping techni/ues&

2hen using SQL within a procedure) it is restricted to accessing one row only& This meansthat the SQL must use a 2=0R0 clause and reference a column that is defined as either a54, or a 5S, inde.& =owe+er) when using a -3R loop multiple rows are allowed to e

Page 390: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 390/401

accessed& The reason for this distinction is that a single row does not use spool space& Theresults are returned directly to the client& $ultiple rows must use spool space and spool muste managed&

,n order for a client to retrie+e more than one row from spool) it is the responsiility of theclient to manage the spooled rows and re/uest each row indi+idually when desired) not allrows at once& The cursor indicates to the dataase which row to return from spoolH again)one row at a time&

,f you ha+e use cursor) are you re/uired to pay a synta. !sin ta.% 3J) we'll get ack toeing serious&

  rief discussion on cursors is warranted for anyone not familiar with the Call Le+el,nterface !CL,% or the SQL 4reprocessor& ny program that interfaces with a dataase mustre/uest each indi+idual row from the dataase& 3nce the rows are returned as records andthe columns as fields) the client program can process the data directly or present it to theuser for display& This is true for #T0Q as well as Queryman clients& #T0Q uilds a reportformat and Queryman uilds a spreadsheet format& 0ither way) the client software isresponsile for uilding the output format) not Teradata&

The client program performs a standard "0CLR0 C5RS3R command& The program isalso responsile to -0TC= each row ased on the cursor location !row pointer%& Thestandard -0TC= command must tell the dataase !Teradata% which row to retrie+e fromspool& Therefore) the -0TC= must e in a loop and the cursor must e incremented on eachrepetition of the loop to retrie+e the ne.t row&

2hen using SQL within #T0Q or Queryman) they manage the return of no rows) one row or more than one row& ll the user needs to do is pro+ide the "$L statement!s%& They use a-0TC= command to tell the dataase to send a row from spool& stored procedure may ecalled from oth of these clients) ut rows are not returned to the clients& Rememer) storedprocedures do not return rows to the user& ,t is now the responsiility of the stored procedureto -0TC= the rows& The -0TC= operation re/uires a cursor to identify the ne.t row toreturn&

Stored procedures must use this same techni/ue& =owe+er) the user is not responsile tocode the actual CL, commands& ,nstead) the -3R and 0N" -3R tell the procedure tore/uest a cursor and loop through the logic with a -0TC= occurring automatically& ,t makesour life easier Y which is a good thing?

The synta. for the -3R and 0N" -3R is elow:

Klael*name:O-3R Kfor*loop*+ariale

  S Kcursor*name C5RS3R -3R O Kcursor*specification

  "3

  Kstatement*listH

0N" -3R Klael*name O H

The lael name on the -3R is optional& =owe+er) if it is used on the -3R) it must also eused on the 0N" -3R statement for identification&

The -3R loop +ariale is used to estalish a name to identify the current row& The row ispointed to using the +alue stored in the cursor& The writer of the procedure uses the cursor name to fully /ualify column references in the procedure&

Page 391: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 391/401

The cursor name may e used in the 2=0R0 clause or in the SQL to indicate the currentrow in spool& ,t is an alias name for the -3R loop pointer +ariale& The name used in the/ualification is the name of the cursor declared in the cursor specification of the -3Rstatement&

The cursor specification consists of a S0L0CT statement that returns at least one columnfrom one or more rows& Like creating +iews and deri+ed tales) all calculations and literals inthe S0L0CT list must ha+e an alias to constitute a +alid name&

The statement list is one or more SQL or S4L statements used to further process the currentrow from the cursor specification& ,f the statement list contains a positioned 54"T0 or "0L0T0 statement) the cursor is treated as ;updateale; !allowed only in NS, mode%&

 n updateale cursor allows for the +alue in the cursor to e changed y the user& ,n other words) if the cursor were pointing at row 18) the user could set it ack to 1 and reprocess thesame rows again& 3therwise) the cursor will only increment from the first row to the last row)one row at a time&

The statement list cannot contain a transactional control statement if the cursor isupdateale& 0.amples of transactional control statements:

C3$$,T for NS, $ode #0I,N TRNSCT,3N for Teradata $ode

The ne.t procedure uses a cursor to ,NS0RT rows into a LogTl after the S0L0CT retrie+esthem from $yWTale:

CR0T0 4R3C0"5R0 $ulitiWRowW,nserter ! %

#0I,N

 %$" cur7ptr A& myptr 

  C'"&$" %$" S0L0CT Col1) col7 -R3$ $yWTale

  $

  ,NS ,NT3 LogTl <L50S !:cur7ptrcol0J /cur7ptrcol) "T0%H

 EN %$"H

0N" H

There are se+eral things to note when e+aluating the processing of the -3R command in aprocedure& -irst) the -3R names the cursor and an alias for the cursor& These names area+ailale for reference within the SQL appearing after the "3 portion of the -3R& Second)the S0L0CT in the C5RS3R -3R is part of the -3R and does not ha+e a semicolon& Lastly)the cursor named curWptr is used in the ,NS0RT !,NS% to /ualify the column names in theretrie+al of the ne.t set of +alues from spool&

The S0L0CT retrie+es its rows from the tale and puts them into spool& Lastly) all SQL after the "3 uses a semi*colon to designate where one statement ends and the ne.t one egins&

Triggers use a techni/ue similar to this as the efore image and the after image for changedrows& The difference here is that the image in spool does not change) it is the -3R thatestalishes the name for the pointer and the S0L0CT that makes the rows a+ailale for usein the procedure&

This is not a complicated -3R e.ample& dditionally) it does not contain an updatealecursor& ,t is our recommendation that if you chose to pursue either of these types of procedures) you use the reference manual as your guide&

Page 392: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 392/401

ITE"ATE &tatement

The ,T0RT0 statement is used to skip all statements after the ,T0RT0 statement& ,t loopsack and repeats all logic from the lael name specified in a loop ack to the ,T0RT0statement& The lael name must e associated with either a 2=,L0) -3R) or L334statement within which the ,T0RT0 statement is located& =owe+er) the lael name may not

e associated with a #0I,N*0N" lock of the procedure ody&

The synta. for the ,T0RT0 statement:

,T0RT0 Klael*name H

The ne.t procedure e.ample delays for a numer of loops that is entered as an inputparameter:

CR0T0 4R3C0"5R0 4awsW4roc !,N35T parmW+al ,NT0I0R%

#0I,N

Looper/:;ILE parmW+al M 1

  "3 S0T parmW+al M parmW+al * 1H

  ,- parmW+al 8 T=0N ITE"ATE Looper H 0N" ,-H  ,NS0RT $yWTl !:parmW+al) C5RR0NTWT,$0ST$4 %H

  ,- SQLSTT0 '99999'

  T=0N parmW+al M SQLC3"0H

  L0<0H

  0N" ,-H

 0N" 2=,L0 LooperH

0N"H

The ,T0RT0 causes only the S0T command to e.ecute until the parmW+al decrements to 8&Then) it fails the ,- test and instead of repeating) falls through to the ,NS0RT& fter that) itloops ack to the 2=,L0 test and since it is e/ual to 1) it continues through for the last time&3nce again) it fails the ,- test) so the iteration loop is not used and again the ,NS0RT inperformed& Notice also that the SQLSTT0 and SQLC3"0 status +ariales are used tomake sure that the ,NS0RT works& ,f it fails) the SQL status code is sent ack to the user asan aid to the deug process&

P"INT &tatement

The 4R,NT statement is used for testing and deugging of procedures& ,ts output +alues areprinted in the "#S ,F3 2indow !screen %& No output is generated unless the procedure iscreated with 4R,NT option enaled& ,t is not a con+enient mode of deug) ut if all else fails)it might e the only techni/ue a+ailale&

The output is generated in the following format:

Kuser*name Ksession*id Kd*name&Ksp*name \Kline*numer Ktimestamp Kuser*specified*

string

The synta. for the 4R,NT statement follows:

4R,NT Kstring*literal) Kidentifier H

Page 393: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 393/401

The string literal is used to identify each printed +alue& The 4R,NT output might e mingledwith output from other procedures and utilities running under Teradata&

The identifier is the local +ariale or parameter +alue needed to help deug the procedure&

Since it is so difficult to get to the output of the 4R,NT command) an 35T parameter isproaly an easier way to otain deug information) as seen in the pre+ious proceduree.ample&

E.ception ;andling

 t times) things may happen within stored procedures that are out of the ordinary& The status+ariales can e a ma(or help in determining what happened& =owe+er) at times) the sameerror handling logic might e needed multiple times within the same procedure& 2hen this isthe case) a =andler routine may e written to ;handle; the condition& This is an alternati+e tocoding the same ,- statements multiple times&

ECLA"E ;ANLE" &tatement

The "0CLR0 is also used to estalish a =andler as well as a +ariale& =andler is asection of logic that e.ecutes automatically ased on error conditions that may occur duringthe e.ecution of a stored procedure&

This is important ecause the procedure is e.ecuting without interaction from the user& ,tdoes not return until it is finished& So) rather than ha+ing an error occur and returning a codeto the user to manually determine the ne.t step) the proper action is coded as part of theprocedure& ,t is programmed to ;handle; the error condition and perform the necessaryprocessing& Therefore) it is easier for the user and pro+ides less opportunity for humanerrors and inconsistent results&

The synta. for "0CLR0 =N"L0R:

"0CLR0 Khandler*type =N"L0R

  -3R Kcondition*+alue*list Khandler*action

H

The =andler type is one of these: C3NT,N50 Y llows for the e.ecution of handler logic within the procedure

and then returns to the ne.t se/uential statement within the procedure after the one that caused the error condition

06,T Y llows for the e.ecution of handler logic within the procedure andthen returns to the caller !e.its procedure%

The Condition <alue list is a comparison using one or more of the status +ariales&

The =andler action is the user logic written using S4L and "$L necessary to handle thecondition&

The ne.t procedure contains two handler routines) the first one is a C3NT,N50 type and thesecond is an 06,T:

CR0T0 4R3C0"5R0 SampW=dlr ! %

#0I,N

Page 394: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 394/401

ECLA"E C$NTIN'E ;ANLE"

  %$" &-L&TATE K0696KJ &-L&TATE KD9066K

  IN&E"T INT$ My7Err7T!l AL'E& (/&-L&TATEJ KError ;andledK)=

ECLA"E EQIT ;ANLE"

  %$" &-LEQCEPTI$N

  IN&E"T INT$ My7Err7T!l (/&-L&TATEJ K'n+non ErrorK)H

Kstatement*list

0N"H

0+ery time an SQL error occurs that is a 71989 or 8199) a row is inserted into $yWerrWtlwith the error code and ;0rror =andled; and continues to e.ecute& =owe+er) if any other error occurs) the SQL06C04T,3N picks it up and inserts the error code and ;5nknown0rror; into $yWerrWtl& #ut) since it is an 06,T) the procedure ends& Iranted) inserting a rowis not much of a way to handle an error& Therefore) something more sustantial is proalyneeded for your =andler routines& This is (ust a /uick e.ample of the techni/ue in+ol+ed inwriting handler routines&

ML &tatements

These "$L statements are allowed in a stored procedure: ,NS0RT !using 54, or 5S,%

54"T0 !using 54, or 5S,%"0L0T0 !using 54, or 5S,%S0L0CT*,NT3 !using 54, or 5S,%"0L0T0 using cursor !for multiple rows in -3R statement%

54"T0 using cursor !for multiple rows in -3R statement%S0L0CT using cursor !for multiple rows in -3R statement%Nested CLL statements

$ost of the "$L is written the same as when used for interacti+e processing& =owe+er) thecursor processing in a -3R was demonstrated using the -3R statement& The CLLstatement is also demonstrated pre+iously in this chapter&

$ost of the SQL is pretty standard& =owe+er) the S0L0CT*,NT3 is a ma(or departure fromnormal SQL& ,t is used to select a single row !54, or 5S,% from a tale and assign the+alue!s% in the specified columns to the respecti+e target +ariales&

The synta. for the S0L0CT*,NT3 is:

P S0L0CT S0L Kcolumn*list ,NT3 Kassignment*target*list

-R3$ Ktale*name

2=0R0 Kcomparison Kother*clauses O

H

The numer of columns or e.pressions in the S0L0CT list must match the numer of +ariales or parameters in the assignment target list& The assignment target list may onlycontain parameters that are defined as 35T or ,N35T parameters) and local +ariales&

Page 395: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 395/401

The following modifies the earlier procedure named 4awsW4roc to eliminate the ,Nparameter and use the S0L0CT*,NT3 to retrie+e a single +alue from the tale called$yWLoopCtl and stores it in Stopper that is used to determine the numer of times for theloop to e.ecute:

CR0T0 4R3C0"5R0 4awsW4roc ! %

L3340R:#0I,N

 "0CLR0 Cntr) Stopper ,NT0I0R "0-5LT 9 H

 &ELECT Cnt7Col INT$ &topper %"$M My7LoopCtl=

 $yLoop:L334

  S0T Cntr M Cntr X 1H

  ,- Cntr &topper  T=0N L0<0 LoopitH 0N" ,-H

  ,NS0RT ,NT3 $yWLogWTl <L50S !:Cntr) T,$0%H

  0N" L334 $yLoop H

0N" L3340RH

,n order to use this techni/ue) $yWLoopCtl tale needs to contain one row only& That rowmust ha+e a column called CntWCol& Then) prior to calling the procedure) the row must eupdated in the $yWLoopCtl tale to change CntWCol with a +alue to control the desirednumer of times the loop is to e performed& Now) when it is retrie+ed y the S0L0CT*,NT3)the loop works that many times&

4otential Teradata error codes when using S0L0CT*,NT3:DE8D is reported if S0L0CT attempts to return more than one rowDE8 is reported if S0L0CT does not return any rows

'sing Column and Alias Names

There are considerations when using column and alias names within a stored procedure:Columns in the cursor specification of a -3R statement may e assigned an alias

 n e.pression used in the cursor specification must e assigned an alias  columnFalias name must e uni/ue in a -3R statement  columnFalias name can e the same as the -3R*loop +ariale and cursor 

names in a -3R statement  columnFalias must e referenced in the ody of the -3R iteration statement y

/ualifying it with the associated -3R*loop +ariale nameScope of a columnFalias of a -3R statement is the ody of the statement

Comments and &tored Procedures

Comments are allowed in procedures and on procedures as seen elow&

Commenting in a &tored Procedure

Stored procedures allow for comments along with the SQL and S4L statements& 0ither or oth the NS, comment ! Y single line% or the Teradata comment ! FG GF multiple lines %techni/ues may e used& gain) it is easier using the Teradata method for multiple linecomments and the NS, method easier for single line comments&

Page 396: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 396/401

The ne.t e.ample shows a comment inside of TestW4roc:

CR0T0 4R3C0"5R0 TestW4roc

  !,N +ar1 #T0,NT) ,N +ar8 #T0,NT) 35T $sg C=R!89% %

#0I,N

 #5 Teradata commentJ ithin slash1asteris+ [ asteris+1slash

  The test compares <alues in <ar0 and <ar9 loo+ing ,or all three possi!ilitiesJe>ualJ

less than and greater than

5#

,- +ar1 M +ar8 T=0N S0T $sg M 'They are e/ual'H

  0LS0,- +ar1 K +ar8 T=0N S0T $sg M '<ariale 1 less'H

  0LS0 S0T $sg M ' <ariale 1 greater'H

  0N" ,-H

  ,NS0RT ,NT3 CustomerWtale "0-5LT <L50SH

11 AN&I CommentJ preceded !y dashes11 Based on the comparisonJ a message is returned to the client

0N"H

Commenting on a &tored Procedure

Like other Teradata R"#$S o(ects) comments may also e added to the o(ect& 2hencomments are present) a =0L4 "T#S0 or 5S0R command displays them along withthe name and kind of o(ect& ,n addition) comments may also e stored on the parameters of a stored procedure& These comments can assist in the e.ecution of the procedure&

The synta. for the C3$$0NT 3N for a stored procedure is:

C3$$0NT 3N 4R3C0"5R0 Kprocedure*name 'Kcomment*here'

H

This C3$$0NT places a comment on the procedure called TestW4roc) used ao+e:

C3$$0NT 3N 4R3C0"5R0 TestW4roc

  '4rocedure tests 8 input +alues and returns result' H

The synta. for commenting on a parameter in a stored procedure is the same as a columncomment for in tale or +iew using C3$$0NT 3N:

C3$$0NT 3N C3L5$N Kprocedure*name&Kargument*name 'Kcomment*here'

H

The ne.t C3$$0NT places a comment on the parameters in the TestW4roc:

C3$$0NT 3N C3L5$N testWproc&+ar1

  'This is the first parameter into this test procedure' H

C3$$0NT 3N C3L5$N testWproc&+ar8

  'This is the second parameter into this test procedure' H

C3$$0NT 3N C3L5$N testWproc&msg

Page 397: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 397/401

  'This is the result parameter out of this test procedure' H

$n1line ;ELP ,or &tored Procedures

3n*line help is a+ailale for stored procedures as it is for other Teradata constructs& ,t may

e used to determine information aout an e.isting procedure or the creation of a newprocedure&

;ELP on a &tored Procedure

To aid in the usage of a stored procedure) on*line help has een added at the workstation& ,tdisplays either the numer of parameters and their names used in a call statement or theattriutes of the parameters&

To see the comment on a procedure) the =0L4 5S0R or =0L4 "T#S0 commands areused to look for an o(ect with a ;Jind; listed as ;4; !output wrapped for +iewing ease%:

=0L4 5S0R mikel H

Ta!le#ie#Macro name 2ind Comment 7 Protection

TestW4roc 4 4roceduretests 8 input+alues andreturns result

-

Creator Name Commit$ption

TransactionLog

$,J01 N

The synta. of the =0L4 4R3C0"5R0 is:=0L4 4R3C0"5R0 Kstored*procedure*name

TTR,#5T0S TTR TTRSO

H

This =0L4 command re/uests assistance in using the stored procedure called testWproc andits arguments !output wrapped for +iewing%:

=0L4 4R3C0"5R0 TestW4roc H

Rows Returned

Page 398: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 398/401

Parameter Name

Type Comment 7 

Nulla!le

+ar1 ,1 This is thefirst

parameter into thistestprocedure

+ar8 ,1 This is thesecondparameter into thistestprocedure

$sg C- This is theresultparameter out of thistestprocedure

%ormat Title Ma.Length

ecimalTotaligits

ecimal%ractionaligits

−!%A 1

−!%A 1

6!89% 89

"angeLo

"ange;igh

'pperCase Ta!le#ie e,ault<alue

Char Type

N 4 9

N 4 9

N 4 1

Parameter Type

,

,3

This display is important to show: the names) data types and formats of the parameters) if default +alues e.ist for their use and what it is) and whether it is an input or outputparameter&

This =0L4 is similar to the ao+e) e.cept that it re/uests the TTR !output wrapped for +iewing ease%:

Page 399: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 399/401

=0L4 4R3C0"5R0 TestW4roc TTR H

1 Row Returned

Transaction &emantics PrintMode

Plat,orm Character  &et

T0R"T N 5N,6$4*RS

 SC,,

e,ault Character ataType Collation &PL Te.t

LT,N SC,,

This last display is important for knowing: which mode !#T0T +s NS,% and which operatingsystem en+ironment!5N,6 +s NT% is applicale) and whether or not deug printing isenaled&

2hen the TTR,#5T0S portion is used) it returns: The creation*time attriutes of a stored procedure Session mode Creator's character set

Creator's character data type Creator's character collation Ser+er operating en+ironment 4R,NT attriute

S4L attriute

;ELP on &tored Procedure Language (&PL)

To aid in the coding of stored procedures) 3n*line =elp) at the workstation has een addedto assist with the writing of procedural commands& ,t is similar to the =0L4 ]SQL&^ =owe+er) itis for S4L instead of SQL&

The =0L4 ]S4L^ pro+ides a list of all the a+ailale S4L commands& To see a specificcommand) the construct ao+e is one of these:

#0I,N Y 0N" CR0T04R3C0"5R0

"0CLR0 "0CLR0=N"L0R

-3R ,-

,T0RT0 L0<0

L334 4R,NTR04LC04R3C0"5R0

S0L0CT*,NT3

S0T 2=,L0

The synta. of the =0L4 is:

=0L4 'S4L Kconstruct O'

H

Page 400: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 400/401

The ne.t =0L4 command returns format help for the "0CLR0 statement:

=0L4 'S4L "0CLR0' H

$n1Line ;elp 7 

"0CLR0 +ariale*name*list data*type

  "0-5LT P literal N5LL O H

+ariale*name*list ::M identifier P &&&) identifier O

"EPLACE P"$CE'"E

Like +iews and macro o(ects in Teradata) to modify a procedure) it is replaced with another procedure in its entirety&

The following is the asic synta. format to R04LC0 a procedure:

404LC0 4R3C0"5R0 Kprocedure*name ! Kparameter*list O %

Kprocedure*odyH

"$P P"$CE'"E

The "R34 4R3C0"5R0 is used to remo+e the definition for a stored procedure o(ect fromthe ""& The user must ha+e "R34 4R3C0"5R0 pri+ilege on the stored procedure or onthe dataase containing it&

The synta. for "R34 4R3C0"5R0 is:

"R34 4R3C0"5R0 Kd*name&OKstored*procedure*name

H

"ENAME P"$CE'"E

The R0N$0 4R3C0"5R0 can e used to rename a stored procedure dataase o(ectname to a new name& The user must ha+e "R34 4R3C0"5R0 pri+ilege on the storedprocedure or on the dataase containing it and also CR0T0 4R3C0"5R0 pri+ilege on thesame dataase& stored procedure cannot e renamed across dataases) only within thesame dataase&

The synta. for R0N$0 4R3C0"5R0 is:

R0N$0 4R3C0"5R0

  Kd*name&OKold*stored*procedure*name P T3 S

  Kd*name&OKnew*stored*procedure*name

H

Page 401: Teradata SQL Quick Reference

8/10/2019 Teradata SQL Quick Reference

http://slidepdf.com/reader/full/teradata-sql-quick-reference 401/401

&;$: P"$CE'"E

The S=32 4R3C0"5R0 command has een added to the Teradata R"#$S& ,t returns theS4L source te.t of a stored procedure if the stored procedure is created with S4L option&

S=32 4R3C0"5R0 Kd*name&OKstored*procedure*name

H

The user may ha+e any pri+ilege on the containing dataase for the command to work& ,norder for this command to work) the S4L storage option must e enaled&

$ther Ne 9"0 %eatures

The user may now use a CS0 statement inside of a stored procedure& This is in addition tousing an ,- F 0N" ,-&

The other new capaility is an 5NT,L F 0N" 5NT,L for determining loop control& ,t is similar to the 2=,L0 F 0N" 2=,L0 with the e.ception that the comparison is ased on ending the

loop when a condition e.ists&

Considerations :hen 'sing &tored Procedures

There are some considerations to take into account when using stored procedures& They arelisted elow and some of these may e eliminated in later releases:

""L and "CL statements are not supported !first release%

L3CJ,NI modifier cannot e used with a nested CLL statement2hen created in Teradata mode) a procedure cannot e e.ecuted in NS, mode

and +ice +ersa2hen created on $4*RS ser+er en+ironment) it cannot e e.ecuted on NT

en+ironment and +ice +ersaTransactional control statements +alid in NS, mode !R3LL#CJ) #3RT) andC3$$,T% are not allowed with updateale cursor 

SQLSTT0) SQLC3"0) CT,<,TWC35NT) are local status +ariales and arenot e.ported to the calling procedure with nested CLL statements

They cannot e in+oked from triggersThe numer of parameters cannot e.ceed 1987The numer of nested calls is limited to 1

They cannot call themsel+es directly andFor indirectly5pdateale cursors are not allowed in Teradata mode