Top Banner
Keywords ABORT ABORTSESSION ABS ABSOLUTE ACCESS_LOCK ACCOUNT ACOS ACOSH ADA ADD ADD_MONTHS ADMIN
114
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: A Guide to Teradata Keywords

Keywords

ABORT

ABORTSESSION

ABS

ABSOLUTE

ACCESS_LOCK

ACCOUNT

ACOS

ACOSH

ADA

ADD

ADD_MONTHS

ADMIN

Page 2: A Guide to Teradata Keywords

AFTER

AG

AGGREGATE

ALIAS

ALL

ALLOCATE

Page 3: A Guide to Teradata Keywords

ALLOCATION

ALLPARAMS

ALTER

ALWAYS

AMP

Page 4: A Guide to Teradata Keywords

ANALYSIS

AND

ANSIDATE

ANY

ARCHIVE

ARGLPAREN

Page 5: A Guide to Teradata Keywords

AS

ASC

ASCII

ASIN

ASINH

ASSERTION

ASSIGNMENT

Page 6: A Guide to Teradata Keywords

ATAN

ATAN2

ATANH

ATOMIC

ATTR

ATTRIBUTES

ATTRS

AUTHORIZATION

AVERAGE

AVG

Page 7: A Guide to Teradata Keywords

BEFORE

BEGIN

BIGINT

BLOB

BOOLEAN

BOTH

BT

BY

Page 8: A Guide to Teradata Keywords

BYTE

BYTEINT

CARDINALITY

CASCADE

CASE_N

CASESPECIFIC

CAST

CEIL

CEILING

Page 9: A Guide to Teradata Keywords

CHANGERATE

CHAR_LENGTH

CHAR2HEXINT

CHARACTER_LENGTH

CHARSET_COLL

CHECKPOINT

Page 10: A Guide to Teradata Keywords

CHECKSUM

CLOB

CLUSTER

CM

COALESCE

COLLATION

COLUMNSPERINDEX

COLUMNSPERJOININDEX

Page 11: A Guide to Teradata Keywords

COMMAND_FUNCTION

COMMENT

COMMIT

COMPILE

COMPRESS

Page 12: A Guide to Teradata Keywords

CONNECT

CONSTRAINT

CONSTRUCTOR

CONSUME

CONTINUE

CORR

COS

COSH

COUNT

Page 13: A Guide to Teradata Keywords

COVAR_POP

COVAR_SAMP

CPUTIME

CPUTIMENORM

CREATE

CSUM

Page 14: A Guide to Teradata Keywords

CUBE

CURRENT_DATE

CURRENT_ROLE

CURRENT_TIME

Page 15: A Guide to Teradata Keywords

CURRENT_TIMESTAMP

CURRENT_USER

CURSOR

CYCLE

DATABLOCKSIZE

DATEFORM

Page 16: A Guide to Teradata Keywords

DBC

DECIMAL

DECLARE

DEFAULT

DEFERRED

DEFINER

DEGREES

DELETE

Page 17: A Guide to Teradata Keywords

DESC

DIAGNOSTIC

DIAGNOSTICS

DISABLED

DISPATCH

DISTINCT

DO

Page 18: A Guide to Teradata Keywords

DOUBLE

DR

DROP

ELAPSEDSEC

ELAPSEDTIME

ENABLED

END-EXEC

ESCAPE

EXCEPT

Page 19: A Guide to Teradata Keywords

EXCLUDE

EXCLUSIVE

EXEC

EXECUTE

EXISTS

EXIT

EXP

EXPIRE

EXTRACT

Page 20: A Guide to Teradata Keywords

FALLBACK

FASTEXPORT

FETCH

FLOAT

FLOOR

FORMAT

FOUND

FREESPACE

GIVE

Page 21: A Guide to Teradata Keywords

GOTO

GRAPHIC

GROUPING

HANDLER

HASHAMP

HASHBAKAMP

HASHBUCKET

Page 22: A Guide to Teradata Keywords

HASHROW

IDENTITY

IFP

IN

INCREMENT

INDEXESPERTABLE

Page 23: A Guide to Teradata Keywords

INDEXMAINTMODE

INITIATE

INSERT

INSTANTIABLE

INTEGER

INTEGERDATE

INVOKER

IOCOUNT

Page 24: A Guide to Teradata Keywords

JIS_COLL

JOURNAL

KANJI1

KANJISJIS

KURTOSIS

LATIN

LN

LOCAL

LOCK

Page 25: A Guide to Teradata Keywords

LOCKEDUSEREXPIRE

LOG

LOOP

LOWER

MACRO

MAP

MAVG

Page 26: A Guide to Teradata Keywords

MAX

MAXCHAR

MAXVALUE

MDIFF

Page 27: A Guide to Teradata Keywords

MERGE

MIN

MINCHAR

MINVALUE

MLOAD

Page 28: A Guide to Teradata Keywords

MOD

MSUM

MULTINATIONAL

MULTISET

NAME

NAMED

NAMES

Page 29: A Guide to Teradata Keywords

NATURAL

NEW_TABLENONOPTCOSTNONOPTINIT

NOWAIT

NULL

NULLABLE

NULLIF

NULLIFZEROOCTET_LENGTH

Page 30: A Guide to Teradata Keywords

ORDER

OVER

PARAMID

PARTITION

PARTITION#L1PARTITION#L10PARTITION#L11PARTITION#L12PARTITION#L13PARTITION#L14PARTITION#L15PARTITION#L2PARTITION#L3PARTITION#L4PARTITION#L5PARTITION#L6PARTITION#L7PARTITION#L8PARTITION#L9

Page 31: A Guide to Teradata Keywords

PARTITIONED

PASSWORD

PERCENT_RANK

PERM

PERMANENT

PLACING

POSITION

PRECEDING

Page 32: A Guide to Teradata Keywords

PRECISION

PREPARE

PROFILE

Page 33: A Guide to Teradata Keywords

QUALIFIED

QUALIFY

Page 34: A Guide to Teradata Keywords

QUANTILE

QUERY_BAND

QUEUE

RADIANS

RANDOM

RANDOMIZED

Page 35: A Guide to Teradata Keywords

RANGE

RANGE#L1

RANGE#L10RANGE#L11RANGE#L12RANGE#L13RANGE#L14RANGE#L15RANGE#L2RANGE#L3RANGE#L4RANGE#L5RANGE#L6RANGE#L7RANGE#L8RANGE#L9

Page 36: A Guide to Teradata Keywords

RANGE_N

RANK

REAL

RECURSIVE

REGR_AVGX

Page 37: A Guide to Teradata Keywords

REGR_AVGY

REGR_COUNT

REGR_INTERCEPT

Page 38: A Guide to Teradata Keywords

REGR_R2

REGR_SLOPE

REGR_SXX

REGR_SXY

REGR_SYY

Page 39: A Guide to Teradata Keywords

RELATIVE

RELEASE

REPLACE

RESTART

RESTORE

RESTRICT

RESTRICTWORDS

RESULT

Page 40: A Guide to Teradata Keywords

REVALIDATE

REVOKE

ROLE

ROLLBACK

ROLLFORWARD

ROLLUP

ROUTINE_CATALOG

Page 41: A Guide to Teradata Keywords

ROW

ROW_COUNT

ROW_NUMBER

ROWID

ROWS

Page 42: A Guide to Teradata Keywords

RU

SAMPLE

SAMPLEID

SAMPLES

SCALE

SCHEMA

SCHEMA_NAME

SCROLL

SEARCHSPACE

Page 43: A Guide to Teradata Keywords

SECOND

SECTION

SECURITY

SEED

SESSION

SETRESRATE

SETSESSRATE

SHOW

SIN

SINH

SKEW

SMALLINTSOME

SOUNDEX

Page 44: A Guide to Teradata Keywords

SPL

SPOOL

SQLDATA

SQLEXCEPTION

SQLSTATE

SQLTEXT

SQLWARNING

SQRTSTDDEV_POPSTDDEV_SAMP

SUBSTRSUMTANH

TBL_CS

Page 45: A Guide to Teradata Keywords

TD_GENERAL

TD_INTERNALTEMPORARY

THRESHOLD

TIES

TIME

TOP

TPA

Page 46: A Guide to Teradata Keywords

TRAILING

TRANSACTION_ACTIVE

TRANSFORM

TRANSLATE

TRANSLATE_CHK

Page 47: A Guide to Teradata Keywords

TRIGGER

TRIM

TYPE

UC

UDTCASTAS

UDTMETHOD

UDTTYPE

UDTUSAGE

UESCAPE

UNBOUNDED

Page 48: A Guide to Teradata Keywords

UNCOMMITTED

UNICODE

UNION

UNIQUE

UNKNOWN

UNNEST

UNTIL

UPD

UPDATE

Page 49: A Guide to Teradata Keywords

UPPER

UPPERCASE

USAGE

USER

USER_DEFINED_TYPE_CATALOG

USER_DEFINED_TYPE_CODE

USER_DEFINED_TYPE_NAME

USER_DEFINED_TYPE_SCHEMA

VALUE

VALUES

Page 50: A Guide to Teradata Keywords

VAR_POP

VAR_SAMP

VARBYTE

VARCHAR

VARGRAPHIC

VARYING

VIEW

VOLATILE

WAIT

Page 51: A Guide to Teradata Keywords

WARNING

WHENEVER

WHERE

WHILE

WIDTH_BUCKET

WINDOW

WITHWITHOUT

WORK

WRITE

YEAR

Page 52: A Guide to Teradata Keywords

ZEROIFNULL

ZONE

Page 53: A Guide to Teradata Keywords

Description

ABORT is a restore option. This option causes an all-AMP restore to abort with error messages if an AMP is offline and the restore includes a nonfallback table. It does not affect a specific AMP restore.

ABORTSESSION function abort queries submitted by a set of users that have been running longer than 10 minutes and have been skewed by more than 10% for 5 minutes.We need Monitor privileges for using this function.

Computes the absolute value of an argument.The returned angle is in the range 0 to π radians, inclusive.sel ABS(-12) Result: 12

FETCH ABSOLUTE(n) fetches the nth row of the response set relative to:• The first row of the set, if n is a positive number.• The last row of the set, if n is a negative number.n can be a host_variable_name or an integer_constant.The data types for the host variable can be any 8-byte numeric data type with zero scale.An integer_constant can be up to 31 digits.

ACCESS_LOCK is a reserved Teradata Database keyword. Teradata Database reserved word that cannot be used as an identifier to name host variables, correlations, local variables in stored procedures, objects, such as databases, tables, columns, or stored procedures, or parameters, such as macro or stored procedure parameters, because Teradata Database already uses the word and might misinterpret it.

It is a keyword used in CREATE PROFILE statement to describe the profile parameters.ACCOUNT is a keyword allowing you to specify the account for a user with this profile.If no account is defined in the profile assigned to a user, the system uses the setting defined for the user.

Returns the arccosine of an argument.The values of argument must be between -1 and 1, inclusive.sel ACOS(-0.5) Result:2.09

It is inverse hyperbolic cosine of arg. The inverse hyperbolic cosine is the value whose hyperbolic cosine is a number so that:acosh(cosh(arg)) = arg

ADA is a non-reserved SQL 2003 keyword. It’s a ANSI SQL-2003 nonreserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 nonreserved word cannot be used as an identifier. If the Teradata Database Status is Non-Reserved or empty, the word is permitted as an identifier, but discouraged because of the possible confusion that may result.

ADD keyword is used to add or change the specified column and its specified attributes. The ADD keyword either changes the definition of an existing column or adds a new column to the table. If the named column already exists, ADD indicates that its attributes are to be changed.

The ADD_MONTHS function Adds an integer number of months to a DATE or TIMESTAMP expression and normalizes the result.The result of the SELECT statement in this example is a date in February, 1996. The result would be February 31, 1996 if that were a valid date, but because February 31 is not a valid date, ADD_MONTHS normalizes the answer.That answer, because the DAY value in the source date is greater than the last DAY value for the target month, is the last valid DAY value for the target month.SELECT ADD_MONTHS ('1995-12-31', 2);The result of this example is 1996-02-29.Note that 1996 was a leap year. If the interval were 14 months rather than 2, the result would be '1997-02-28'.RulesADD_MONTHS observes the following rules:• If either argument of ADD_MONTHS is NULL, then the result is NULL.• If the result is not in the range ‘0000-01-01’ to ‘9999-12-31’, then an error is reported.• Results of an ADD_MONTHS function that are nonvalid dates are normalized to ensure that all reported dates are valid.

The ADMIN clause is like ROLE, but the named roles are added to the new role WITH ADMIN OPTION, giving them the right to grant membership in this role to others.

Page 54: A Guide to Teradata Keywords

An after-image journal stores a snapshot of a row value after a change has been committed. Then if a hardware failure occurs, you can use the after-image journal to roll forward any changes made to the data tables that write to that journal since the last full system backup. To protect against the loss of data in the event of a site disaster, many applications require that data archives be kept off-site at all times. Ideally, users dump the database to tape daily and store the tape off-site.Daily archives may not be practical for very large databases. To solve this problem, you can activate after-change journals and take a daily archive of the journal itself, which provides archived copies of all changes made since the last full database archive.

CREATE MULTISET TABLE inv, FALLBACK,NO BEFORE JOURNAL,NO AFTER JOURNAL(item INTEGER CHECK ((item >=10) AND (item <= 20) ))PRIMARY INDEX (item);

AG is short form of Allocation group. The Priority Scheduler can define up to 200 Allocations Groups (AGs). Multiple Performance Groups can use the same AG, but all PGs that use an AG must be in the same Resource Partition. A PG can reference multiple AGs over time.

The catalog pg_aggregate stores information about aggregate functions. An aggregate function is a function that operates on a set of values (typically one column from each row that matches a query condition) and returns a single value computed from all these values. Typical aggregate functions are sum, count, and max. Each entry in pg_aggregate is an extension of an entry in pg_proc. The pg_proc entry carries the aggregate’s name, input and output data types, and other information that is similar to ordinary functions. Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group.

A temporary name can be given to tables and complex table references to be used for references to the derived table in the rest of the query. This is called a table alias.To create a table alias, writeFROM table_reference AS aliasorFROM table_reference aliasThe AS key word is noise. alias can be any identifier

Since ALL is used in UNION ALL operations, We should not use ALL as a variable name.

SELECT * FROM Flights WHERE origin = 'LAX'UNION ALLSELECT * FROM Flights_1StopUNION ALLSELECT * FROM Flights_2Stops;

Also, SQL recognizes the quantifiers ANY (or SOME) and ALL. A quantifier allows one or more expressions to be compared with one or more values. If the expression is like - x LIKE ALL ('A%','%B','%C%') then It meant x LIKE 'A%'AND x LIKE '%B'AND x LIKE '%C%'

In MVS, debug output is written to the DDNAME OUTPUT, and DB2 trace output is written to the DDNAME TRACE.

Allocating OUTPUTWhen allocating the OUTPUT file, a DDNAME of OUTPUT must be used. For example, in TSO:ALLOCATE DD(OUTPUT) SYSOUT(A) RECFM(VBA) LRECL(85) BLKSIZE(6124)or in batch://OUTPUT DD SYSOUT=A,DCB=(RECFM=VBA,LRECL=85,BLKSIZE=6124)Allocating TRACE When allocating the TRACE file, a DDNAME of TRACE must be used. For example, in TSO:ALLOCATE DD(TRACE) SYSOUT(A) RECFM(VBA) LRECL(85) BLKSIZE(6124)

Page 55: A Guide to Teradata Keywords

RANDOMIZED ALLOCATION specifies whether rows are sampled randomly across AMPS (RANDOMIZED ALLOCATION) or proportionate to the number of qualified rows per AMP (proportional allocation). The proportional allocation option does not provide a simple random sample of the entire population. It provides a random sample stratified by AMPs, but it is much faster, especially for very large samples. Proportional is the default. You select it implicitly by not specifying RANDOMIZED ALLOCATION.SELECT city, state, sampleidFROM storesSAMPLE RANDOMIZED ALLOCATIONWHEN state = 'WI' THEN 0.25, 0.5WHEN state = 'CA' THEN 0.25, 0.25ENDORDER BY 3;

ALLPARAMS is report_option in the diagnostic help profile.ALLPARAMS report all of the values specified by all of the following options:• COST• INIT• INTERNAL• NONOPTINIT• NONOPTCOST• OPTIONS

DIAGNOSTIC HELP ALLPARAMS;

ALTER is a data definition statement. Ut changes, for example, a table, column, referential constraint, trigger, index.One eg: ALTER PROCEDURE direct the stored procedure compiler to recompile a stored procedure created in an earlier version of Teradata Database without executing SHOW PROCEDURE and REPLACE PROCEDURE statements.

ALTER PROCEDURE spAP2 COMPILE;

To create a table with an identity column, We must explicitly specify one column in the table definition as either GENERATED ALWAYS AS IDENTITY or GENERATED BY DEFAULT AS IDENTITY. You can only define one identity column per table. The data type for an identity column is user-defined, but must be an exact numeric type drawn from the following list:• BIGINT• BYTEINT• DECIMAL(n,0)• INTEGER• NUMERIC(n,0)• SMALLINTThe identity column values are always system-generated.We cannot insert values into, nor can we update, an identity column defined as GENERATED ALWAYS AS IDENTITY.

Access module processor is a Teradata Database management software .The AMP performs database functions to retrieve and update data on the vdisks.

Page 56: A Guide to Teradata Keywords

INITIATE INDEX ANALYSIS : Analyzes a query workload and generates a set of recommended secondary and single-tablejoin indexes for optimizing its processing.INITIATE INDEX ANALYSIS ON table_1FOR MyWorkloadIN MyQCDAS table_1Index;

INITIATE PARTITION ANALYSIS: Analyzes a given workload to make recommendations for partitioned primary indexes. INITIATE PARTITION ANALYSIS also considers the potential performance benefits of partitioning one or more tables in a given workload. The resulting recommendations, if any, are stored in the PartitionRecommendations table in the specified Query Capture Database.

INITIATE PARTITION ANALYSISFOR myworkloadIN myqcdAS myppirecs;

AND is a logical operator.AND Truth TableThe following table illustrates the AND logic used in evaluating search conditions.Keep in mind that a logical result of UNKNOWN resolves to FALSE.

x FALSE x UNKNOWN x TRUE y FALSE FALSE FALSE FALSEy UNKNOWN FALSE UNKNOWN UNKNOWNy TRUE FALSE UNKNOWN TRUE

While creating the User, dateform parameter is specified. If the DATEFORM = ANSIDATE, then it sets the DATEFORM option to import and export DATE values as CHARACTER(10).Results in a 'YYYY-MM-DD' date format for date columns created and for date constants in character form.

If we need to change the DATEFORM setting back to ANSIDATE from the INTEGERDATE,then we can run the following SET SESSION DATEFORM statement:SET SESSION DATEFORM = ANSIDATE;SQL recognizes the quantifiers ANY (or SOME) and ALL. A quantifier allows one or more expressions to be compared with one or more values.If the expession is like - x LIKE ANY ('A%','%B','%C%') , then It meant x LIKE 'A%' OR x LIKE '%B' OR x LIKE '%C%'

The following statement selects from the employee table the row of any employee whose job title includes the characters “Pres” or begins with the characters “Man”:SELECT *FROM EmployeeWHERE JobTitle LIKE ANY ('%Pres%', 'Man%');

LOGGING ONLINE ARCHIVE ON specifies the intent to perform online archive logging by creating a synchrony point for a specified list of database or table sets and to capture subsequent updates5 made to the specified tables until online archive logging is turned off.The following example starts online archive logging on table1.The system places a table-level read lock on table1 before it begins logging. The system then releases this table-level READ lock after the transaction completes.LOGGING ONLINE ARCHIVE ON FOR databasea.table1;Note that the database_name.table_name specification in the LOGGING ONLINE ARCHIVE ON SQL request is not delimited by parentheses.

ARGLPAREN is a reserved teradata database keyword and cannot be used in SQL queries. Teradata Database reserved word that cannot be used as an identifier to name host variables, correlations, local variables in stored procedures, objects, such as databases, tables, columns, or stored procedures, or parameters, such as macro or stored procedure parameters, because Teradata Database already uses the word and might misinterpret it.

Page 57: A Guide to Teradata Keywords

To alias a column, use an AS and any legal Teradata name after the real column name requested or math formula using the following technique:Sel SALARY/12 AS monthly_salary FROM Pay_Table;Once the alias name has been assigned, it is literally the name of the column for the life of the SQL statement.

ASC specifies ascending order; For the ORDER BY clause, ASC is the default.The following statement measures the queue depth of a queue table named shopping_cart:SELECT COUNT(*)FROM shopping_cart;Assuming the column named cart_qits contains QITS values, the following statement returns the shopping_cart queue table in FIFO order:SELECT *FROM shopping_cartORDER BY cart_qits ASC;

If we do not define a client character set as the default for a client in the DBC.Hosts table, the automatic default is the character set native to that client.During a session, the user can find out which client character set is in effect with the SQL HELP SESSION statement1, and can specify a different (but active) client character in various ways, depending on the particular client software. With the BTEQ client software, you can use the .SET SESSION CHARSET command. For example:

.SET SESSION CHARSET ASCIIThe .SET SESSION command can be entered interactively in the user logon string or at any time during a BTEQ session, or embedded in a BTEQ script file (batch job) or application program.

Returns the arcsine of an argument.The values of arg must be between -1 and 1, inclusive.The returned angle is in the range -π/2 to π/2 radians, inclusive.sel SIN(1) result:0.84

It is s Inverse hyperbolic sine of arg. The inverse hyperbolic sine is the value whose hyperbolic sine is a number so that:asinh(sinh(arg)) = arg

ASSERTION is a non reserved SQL 2003 ANSI keyword. The usage of ASSERTION should be avoided.

An assertion that can be proven unequivocally to be either true or false. In a relational table, or relation variable, all rows are assumed to be true propositions by default, because if they were false, they would have been prevented from entry in the database by the various integrity constraints, both implicit and explicit, defined on that database. Each proposition (tuple) in a relation is an instantiation of its relation variable predicate that evaluates to TRUE.

We can make a user-defined cast implicitly invokable by including the AS ASSIGNMENT clause in its CREATE CAST statement. When we define a cast operation in this way, the system implicitly invokes the cast for all assignment operations.

Note that an assignment operation is defined to be any of the following operations:• INSERT• UPDATE• parameter passingWe can disable this functionality by means of the DisableImplCastForSysFuncOp DBSControl flag.

The following CREATE CAST statement creates a cast operation that converts the source data type euro to the target data type VARCHAR(20) using the method euroString. The casting routine is defined so it is implicitly invoked on an assignment operation assuming the necessary conditions are met for the assignment

CREATE CAST (euro AS VARCHAR(20))WITH METHOD SYSUDTLIB.euroString( ) FOR euroAS ASSIGNMENT

Page 58: A Guide to Teradata Keywords

AVG is the abbreviation for AVERAGE.Same definition as AVG

Returns the arctangent of (x). The arctangent is the angle whose tangent is arg. The returned angle is in the range ?/2 to p?/2 radians, inclusive.

Returns the arctangent of the specified (x,y) coordinates. The arctangent is the angle from the x-axis to a line contained the origin(0,0) and a point with coordinates (x,y).

The returned angle is between ??and p?radians, excluding ?. A positive result represents a counterclockwise angle from the x-axis where a negative result represents a clockwise angle. The ATAN2(x,y) equals ATAN(y/x), except that x can be 0 in ATAN2(x,y) and x cannot be 0 in ATAN(y/x) since this will result in a divide by zero error. If both x and y are 0, an error is returned. It is a inverse hyperbolic tangent of arg. The inverse hyperbolic tangent is the value whose hyperbolic tangent is a number so that:atanh(tanh(arg)) = arg

BEGIN ATOMIC is a keyword introducing multiple triggered action statements.If we begin the triggered SQL statement clause with BEGIN ATOMIC, then we must also terminate it with the END keyword.FOR EACH ROWBEGIN ATOMICCALL insert_doc_journal( new_row.docnum );END;

It is a keyword indicating that the stored procedure creation-time attributes from the column SPObjectCodeRows in DBC.TVM are to be displayed rather than the attribute and format information for the procedure parameters.

PASSWORD[ATTRIBUTES] - a keyword allowing you to define password security attributes.The default value is NULL for password attributes that are not defined in the profile for a user. This causes the system to use thesystem setting. Password security attributes defined in a profile take effect the next time a user logs on.

a keyword indicating that the stored procedure creation-time attributes from the column SPObjectCodeRows in DBC.TVM are to be displayed rather than the attribute and format information for the procedure parameters.

CREATE AUTHORIZATION/ REPLACE AUTHORIZATION creates the definition for an authorization object. Authorization definitions make an association between a database user and an OS server user identification, allowing an external routine to run in secure mode using the context,privileges, and access control accrued to the specified OS user.CREATE AUTHORIZATION sales AS INVOKERDOMAIN ‘eastsales’USER ‘sam johnson’PASSWORD ‘tercesym’;

Returns the arithmetic average of all values in the specified expression for each row in the group.

The value_expression must not be a column reference to a view column that is derived from a function.AVG is valid only for numeric data.Nulls are not included in the result computation.

SELECT Region, AVG(sales)FROM sales_tblGROUP BY RegionORDER BY Region;Region Average (sales)------ ---------------North 21840.17East 55061.32Midwest 15535.73

Page 59: A Guide to Teradata Keywords

BEFORE is specified in the trigger creation. When BEFORE is mentioned, then the triggered action executes before the completion of the triggering event.As specified in ANSI SQL standard, a BEFORE trigger cannot have data changing statements in the triggered action.

BEGIN and END is used to denote the start and end of statements. Few of the cases are belowBEGIN QUERY LOGGING…BEGIN TRANSACTION…BEGIN DELARE CONDITION HANDLER

Represents a signed, binary integer value from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.BIGINT values are stored as eight bytes with the least significant byte first.In the following table definition, column Total is a BIGINT data type:CREATE TABLE RelevantNumbers(Id CHAR(9),LastSummary INTEGER,Total BIGINT);

Binary Large Objects.This allow you to store and retrieve BLOBS into Teradata by breaking the BLOB into 30K chunks and storing each Chunk as a row in a table.

A bivalent, or Boolean, logic has exactly two truth values: TRUE and FALSE. Higher-valued logics have three or more truth values. For example, SQL uses a 3VL having the following three truth values: TRUE, FALSE, and UNKNOWN.

This will specify how to trim the specified trim character or byte from string_expression.BOTH represents Trim both trailing and leading characters or bytes.If the Names table includes the columns first_name and last_name, which contain thefollowing information:first_name (CHAR(12)) has a value of 'Mary 'last_name (CHAR(12)) has a value of 'Jones 'then this statement:SELECT TRIM (BOTH FROM last_name) || ', ' || TRIM(BOTH FROM first_name)FROM names ;returns the following string (note that the seven trailing blanks at the end of string Jones, and the eight trailing blanks at the end of string Mary are not included in the result):'Jones, Mary'

BT is BEGIN TRANSACTION. It allows you to manage transactions. A session executing under ANSI transaction semantics allows neither the BEGIN TRANSACTION statement, the END TRANSACTION statement, nor the two phase commit protocol. When an application submits these statements in ANSI mode, the database software generates an error. Eg: BEGIN TRANSACTION;DELETE FROM EmployeeWHERE Name = ‘Smith T’;UPDATE DepartmentSET EmpCount=EmpCount-1WHERE DeptNo=500;END TRANSACTION;

BY is used in ORDER BY CLAUSE.ORDER BY clause specifies how results data are to be sorted.

The following example produces a list of employees, sorted by years of work experience.SELECT name, jobtitle, yrsexpFROM employeeORDER BY yrsexp;

Page 60: A Guide to Teradata Keywords

For explicit casting of a datatype, We use the keyword CAST. Eg : SELECT CAST (NULL AS DATE);

Teradata supports two data types for holding binary data: BYTE. VARBYTE. BYTE is for fixed length binary strings. VARBYTE is for variable length binary strings. These data types are used for storing binary objects such as digital images, executable objects, flat files, etc.It is a fixed length Binary string Default: (1) Max: 64,000 bytesBYTE columns are not covertible to other data types.

BYTEINT represents a signed binary integer value in the range -128 to 127.BYTEINT is stored as one byte.In the following table definition, column EdLev is a BYTEINT data type:CREATE TABLE Education(Id CHAR(9),LastName CHAR(26),EdLev BYTEINT FORMAT 'Z9'CHECK (EdLev BETWEEN 0 AND 22) NOT NULL);

Cardinality is a property of a join that describes how many rows in one table match rows in another table. Cardinality is expressed as the minimum and maximum number of rows in a column at one end of a join, that have matching rows in the column at the other end of the join. The minimum and the maximum number of row matches can be equal to 0, 1, or N.

Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.

Evaluates a list of conditions and returns the position of the first condition that evaluates toTRUE, provided that no prior condition in the list evaluates to UNKNOWN.

Teradata is by default case insensitive. But there are certain scenarios that you might face, where you want the WHERE clause to check only for the pattern in the specified case. This is how you achieve it: by adding a predicate to the constraint (CASESPECIFIC)Ex: SELECT CURRENT_DATEWHEREUPPER('hello') = 'hello' (CASESPECIFIC); --will not return the current_date

SELECT CURRENT_DATEWHERELOWER('HELLO') = 'hello' (CASESPECIFIC); --will return the current_date

The ceiling function rounds the result of the expression up to the nearest integer, which is the exact number of presence bits required to account for both single-valued and multivalued compression information for the given table.CEILING is used to compute the value.

Returns the smallest integer that is not less than the input argument

SELECT CEILING(15.7);

Page 61: A Guide to Teradata Keywords

Every column appearing in an UPDATE SET clause is automatically assigned a change rating ranging from 0 to 9, representing the frequency at which it is updated (see Database Design for more information about change ratings).The system assigns columns with a very high update frequency a change rating of 9, while columns that are never updated are assigned a change rating of 0.Columns with a change rating greater then this user-specified ChangeRate parameter are not considered during index analysis for potential indexes. In other words, the ChangeRate value is a threshold for determining whether to use columns for an index analysis or not. If the specified ChangeRate parameter is 9, the change rating system is not used to disqualify columns from index analysis.The default is 5.The valid range is 0 to 9, where 0 means the column is not updated and 9 means the column is highly volatile with respect to the specified workload.INITIATE INDEX ANALYSIS ON table_1FOR MyWorkloadIN MyQCDAS table_1IndexSET ChangeRate=4;

CHAR_LENGTH / CHARACTER_LENGTH returns the length of a string either in logical characters or in bytes.To suppress trailing pad characters from the character count for a data value, use the TRIM function on the argument to CHARACTER_LENGTH. For example:SELECT CHARACTER_LENGTH( TRIM( TRAILING FROM Name ) )FROM Employee;

CHAR2HEXINT returns the hexadecimal representation for a character string. Use CHAR2HEXINT on character strings or character string expressions.The following statement and results illustrate how CHAR2HEXINT operates on constantstrings:SELECT CHAR2HEXINT('123');Char2HexInt('123')-----------------------003100320033

CHAR_LENGTH / CHARACTER_LENGTH returns the length of a string either in logical characters or in bytes.To suppress trailing pad characters from the character count for a data value, use the TRIM function on the argument to CHARACTER_LENGTH. For example:SELECT CHARACTER_LENGTH( TRIM( TRAILING FROM Name ) )FROM Employee;

The CHARSET_COLL collation performs binary ordering based on the current client character set. Strings are compared byte-by-byte. When one comparison string is shorter than the other, it is padded with the pad character defined for the character data type before the comparison is made. When comparisons are not case specific, the following process occurs:1 Lowercase letters are mapped to their uppercase counterparts.2 The strings are compared.If the strings are identical,then the equality relation holds.If the strings are not equal,then first pair of bytes that is not equal determines the collating sequence.3.End of process.

CHECKPOINT is a function that writes records to a restart log table that you can use to restart in case of a hardware or software system failure.

Page 62: A Guide to Teradata Keywords

A checksum is a computed value used to ensure that the data stored on a block of data is transmitted to and from storage without error. A sampling algorithm generates the checksum for a block of data which is then stored separately from the data on disk.When the data is read back from disk, the Teradata Database file system recomputes the checksum based on the data read in and compares this value with the checksum that was previously calculated when the data was originally written out to disk. If the two values do not match, this indicates data corruption.CHECKSUM = DEFAULT/CHECKSUM = NONE/CHECKSUM = LOW/CHECKSUM = MEDIUM/CHECKSUM = HIGH/CHECKSUM = ALL

CLOB, short for "Character Large OBject", is a data type used to store and retrieve large amounts of text data in character format. It can be a large text file: HTML, RTF or other character-based file. CLOBs can be up 2 GB in size.

USR_HTML_DESCRIPTION CLOB(10240) CHARACTER SET LATIN

CLUSTER— to cluster a table according to an index. When a table is clustered, it is physically reordered based on the index information. Clustering is a one-time operation: when the table is subsequently updated, the changes are not clustered. That is, no attempt is made to store new or updated rows according to their index order. Syntax : CLUSTER tablename [ USING indexname ]CLUSTER Eg. Cluster the table employees on the basis of its index employees_ind:CLUSTER employees USING employees_ind;

CM is short for Create Macro. Defines a set of statements that are frequently used or that perform a complex operation. The statements in the macro body are submitted when the macro is invoked by a subsequent EXECUTE statement.

It returns the first NOT NULL value from the string of attributes. Often used in place of non-ANCII Zeroifnull.COALESCE(Col1,0) = return col1 if not NULL, 0 if NULL. Can contain more then 2 return values COALESCE(Col1,Col2,col3, 0) Returns first of attributes that is not null.The COLLATION option defines the name for a collation that determines the ordering of data characters during comparison operations and when sorting data in response to a SELECT query that includes an ORDER BY or WITH … BY clause. If the name is not specified, then the collation for the session defaults to that of the logon client system..We can override the COLLATION attribute during any session by running a SET SESSION COLLATION statement.COLLATION can be defined as an attribute of the user.

The maximum number of composite secondary index columns to be considered for index recommendation by the Index Wizard.The default is 4.The valid range is 1 to 64.Syntax: INITIATE INDEX ANALYSISON table_name [ … , table_name][, ColumnsPerIndex = value]

The maximum number of referenced columns in a single-table join index to be considered for index analysis by the Index Wizard.The default is 8.The valid range is 1 to 16.It is used in initiate index analysis which analyzes a query workload and generates a set of recommended secondary and single-table join indexes for optimizing its processing.

Page 63: A Guide to Teradata Keywords

It is an identifying text string for the executed SQL statement representing the staement information item in the diagnostics area.Data type: VARCHAR(128) CHARACTER SET LATINDefault: null. Some of the command functions are GRANT ROLE,INSERT,MODIFY DATABASE,RENAME MACRO etc.The following example illustrates the usage of the statement information item field COMMAND_FUNCTION in a GET DIAGNOSTICS statement in Teradata session mode. When the procedure finishes executing, When the GET DIAGNOSTICS statement is submitted and Stmt has the string 'INSERT'.CREATE PROCEDURE getdiag3 (OUT Stmt CHARACTER(40))BEGINDECLARE CONTINUE HANDLER FOR SQLSTATE '23505'GET DIAGNOSTICSStmt = COMMAND_FUNCTION;INSERT INTO Tab1 VALUES(100);INSERT INTO Tab1 VALUES(100);END;BTEQ> CREATE SET TABLE tab1 (c1 INTEGER);BTEQ> CALL getdiag3(Stmt);

COMMENT— used to define or change the comment of an object. COMMENT stores a comment about a database object. To modify a comment, issue a new COMMENT command for the same object. Only one comment string is stored for each object. To remove a comment, write NULL in place of the text string. Comments are automatically dropped when the object is dropped. Eg. Attach a comment to the table mytable:COMMENT ON TABLE mytable IS ’This is my table.’;Remove it again:COMMENT ON TABLE mytable IS NULL;

COMMIT WORK ; COMMIT terminates the current ANSI SQL transaction, commits all changes made within it, and drops the Transient Journal for the transaction.The following UPDATE initiates the transaction and COMMIT WORK terminates it:

UPDATE parts SET part_num = 20555WHERE location = ‘seoul’;COMMIT WORK;

The INSERT request in the following example opens the transaction. COMMIT closes thetransaction.INSERT INTO employee (name, empno)VALUES ('Sinclair P', 101)WHERE dept = '400';COMMIT;The COMPILE option is intended to be used by DBAs to recompile functions that have been moved to a platform, system, or restored database other than the one in which they were created.Specify the COMPILE option to recompile an existing function. If its source code is present, then the system recompiles it, generates the object, recreates the .dll or .so file, and distributes it to all nodes of the system. The object is replaced with the recompiled version.If the function was created with the object only (that is, there is no source code present to be recompiled), the function object is used to recreate the .dll or .so file and distribute it to all nodes of the system.If the function is restored from a different platform to a new platform whose objects are not compatible, the COMPILE option fails. When this happens, you must recreate the function with the correct object or source code.The follwing SQL request will recompile the WriteMQ UDF:ALTER FUNCTION WriteMQ COMPILE;

COMPRESS phrase compresses specified values and nulls in one or more columns of a table to zero space. When the data in a column matches a value specified in the COMPRESS phrase, then that value is stored only once in the table header regardless of how many times it occurs as a field value for the column, thus saving disk storage space.COMPRESS without any arguments will compress the NULL values.The following example shows a numeric column specified with a COMPRESS phrase:CREATE TABLE ID(IDNum INTEGER,Post INTEGER COMPRESS (44, 45, 63));

Page 64: A Guide to Teradata Keywords

Returns the hyperbolic cosine of (x) where x is any real number.

CONNECT is a privilege. It allows the user to connect to the specified database. This privilege is checked at connection startup (in addition to checking any restrictions imposed by pg_hba.conf). Eg. GRANT CONNECT ON DATABASE

There are three main types of constraints:• CHECK• Referential• UNIQUEWe can add. Modify or drop a constraint.Egs:ALTER TABLE table_1ADD CONSTRAINT primary_1 PRIMARY KEY (field_1, field_2);

ALTER TABLE table_1DROP CONSTRAINT check_1;

A constructor method initializes an instance of a structured UDT.A structured UDT can have more than one constructor method, each one providing different initialization options.The following example creates the definition for a constructor method named address for the UDT named address. The external routine for this method is stored on the server at the location specified in the EXTERNAL NAME clause.CREATE CONSTRUCTOR METHOD address( VARCHAR(20), CHARACTER(5) )RETURNS addressFOR addressEXTERNAL NAME'SO!C:\structured_lib\addr_cons.obj!F!addr_constructor';

SELECT AND CONSUME returns data from the row with the oldest insertion timestamp in the specified queue table and deletes the row from the queue table.

The following statement returns all the columns of the row with the oldest value in the cart_qits column of the shopping_cart table:SELECT AND CONSUME TOP 1 * FROM shopping_cart;

CONTINUE is a type of conditon handler being requested. DECLARE CONTINUE HANDLERFOR SQLSTATE value '23505'BEGINSET p1='FAILED TO INSERT ROW';END;

CORR is a aggregate function used with SQL. It returns the Pearson product moment correlation coefficient of its arguments for all non-null data point pairs. Its syntax is CORR ( value_expression_1, value_expression_2 ) where value_expression_2 and value_expression_1 are numeric expressions to be correlated with a second numeric expression.

Takes an angle in radians (x) and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1, inclusive where x is any valid number expression that expresses an angle in radians.

COUNT is an aggregate function which is used to return a column value that is the total number of qualified rows in a group. For eg. Count (*) - Counts the total number of rows in the group of rows on which COUNT operates. And COUNT (DISTINCT value_expression) returns the total number of rows in the group for which value_expression is unique and not null

Page 65: A Guide to Teradata Keywords

COVAR_POP is an aggregate function and its prupose is to return the population covariance of its arguments for all non-null data point pairs. Syntax : COVAR_POP ( value_expression_1, value_expression_2 ) ., where value_expression_2, value_expression_1 are numeric expressions to be paired with a second numeric expression to determine their covariance. The expressions cannot contain any ordered analytical or aggregate functions.

Sample covariance.COVAR_SAMP (value_expression1, value_expression2)Value_expression is a column expression to be paired with a second column expression to determine their covariance. Returns the sample covariance of its arguments for all non-null data point pairs. Is the sum of the products of deviations for each non-null data point pair. The formula for COVAR_SAMP(x,y) is as follows: COVAR_SAMP(x,y) = SUM((x - AVG(x)) * (y - AVG(y)))/COUNT(x) - 1

It is a limit option in the BEGIN QUERY LOGGING. If we do not specify a threshold value for n, then the system uses the default CPUTIME value of 0.05 CPU seconds.The THRESHOLD value is expressed in units of 0.01 second.For example, if you specify 500, then the value used to make the determination is 5 CPU seconds.

It is a limit option in BEGIN QUERY LOGGING. This option is used to set ranges and to summarize counts of the number of requests that fall into a normalized CPU time interval.This option is designed for use with coexistence systems to aid in managing mixed nodes moreefficiently.The SUMMARY value is expressed in units of 0.01 second.

CREATE is a privilege. For databases, allows new schemas to be created within the database. For schemas, allows new objects to be created within the schema. To rename an existing object, you must own the object and have this privilege for the containing schema. For tablespaces, allows tables, indexes, and temporary files to be created within the tablespace, and allows databases to be created that have the tablespace as their default tablespace. (Note that revoking this privilege will not alter the placement of existing objects.)

The Cumulative Sum function (CSUM) computes a running or cumulative total of a column’s value.CSUM(colname, sort_item1, sort_item2,…)SELECT salesdate, sales, CSUM(sales, salesdate)FROM daily_salesWHERE salesdatesalesdate sales Csum98/01/01 150 15098/01/02 200 35098/01/03 250 60098/01/05 350 95098/01/10 550 1500

Page 66: A Guide to Teradata Keywords

The CUBE function can be thought of as a superset of the ROLLUP functions. It returns the same result set as ROLLUP, but it also provides additional information. Instead producing a 'hierarchy' of results, CUBE looks at all permutations of the specified dimensions.

Produce a 'cube' report showing employee salaries across the dimensions of department and manager.

SELECT department_number AS Deptno,manager_employee_number AS Mngr,SUM(salary_amount) AS SumSalFROM employeeWHERE department_number < 402GROUP BY CUBE (department_number,manager_employee_number)ORDER BY 1,2;

Deptno Mngr SumSal ? ? 591925.00 (all depts, all managers) ? 801 286750.00 (all depts, one manager) ? 1003 207725.00 ? 1019 58700.00 ? 1025 38750.00 100 ? 100000.00 (one dept, all managers) 100 801 100000.00 (one dept, one manager) 201 ? 73450.00 (one dept, all managers) 201 801 34700.00

It returns the current system date.Requesting the Current System DateThe following statement requests the current system date:SELECT CURRENT_DATE;The system responds with something like the following:Date--------01/12/28

It returs the current role of the current authorized user.CURRENT_ROLE is not supported in the FastLoad and MultiLoad utilities.You can identify the current role for the current authorized user with the following statement:SELECT CURRENT_ROLE;The system responds with something like the following:Current_Role------------------------------Buyers_role

CURRENT_TIME returns the current system time and current session Time Zone displacement.The fields in CURRENT_TIME are:• HOUR• MINUTE• SECOND• TIMEZONE_HOUR• TIMEZONE_MINUTEThe following statement requests the current system time and current session Time Zonedisplacement:SELECT CURRENT_TIME;The system responds with something like the following:Current Time(0)---------------15:53:34+00:00

Page 67: A Guide to Teradata Keywords

CURRENT_TIMESTAMP returns the current system timestamp and current session Time Zone displacement.The fields in CURRENT_TIMESTAMP are:• YEAR• MONTH• DAY• HOUR• MINUTE• SECOND• TIMEZONE_HOUR• TIMEZONE_MINUTEThe following statement requests the system timestamp and session Time Zone displacement:SELECT CURRENT_TIMESTAMP;The system responds with something like the following:Current TimeStamp(6)--------------------------------2001-11-27 15:53:34.910000+00:00

CURRENT_USER provides the user name of the current authorized user.If you are accessing the Teradata Database through a proxy connection, CURRENT_USERreturns the proxy user name. Otherwise, it functions exactly like the USER built-in function and returns the session user name.You can identify the current authorized user with the following statement:SELECT CURRENT_USER;The system responds with something like the following:Current_User------------------------------BO-JSMITH

A cursor is a pointer that the application program uses to move through a result table. We declare a cursor for a SELECT statement, and then open the named cursor. The act of opening the cursor executes the SQL statement.Then We use the FETCH... INTO... statement to individually fetch and write the rows into host variables. The application can then use the host variables to do computations.

DECLARE rect_cursor CURSOR WITHOUT RETURN FORSELECT rect_col, background_color, idFROM table1 FOR UPDATE;While creating sequence number column, if the CYCLE is specified as NO, then the seuence number will not be repeated once it attains the max value.

CREATE TABLE canary (c_id DECIMAL(18,0) GENERATED ALWAYS AS IDENTITY(NO CYCLE),UNIQUE PRIMARY INDEX (canary_id);

DATABLOCKSIZE sets the maximum data block size for blocks that contain multiple rows. The data block is the physical I/O unit for the Teradata file system.Larger block sizes enhance full table scan operations by selecting more rows in a single I/O.Smaller block sizes are best for transaction-oriented tables to minimize overhead by retrieving only what is needed. The maximum data block size is 127.5 Kbytes (130,560 bytes).A row that is larger than the DATABLOCKSIZE setting is stored in its own data block. Rowsare not split across data blocks. If DATABLOCKSIZE is not specified, then the default size is used.

DATABLOCKSIZE = 6144 BYTES.. This statement will be a part of the alter table or create table statements.

We can change the format in which DATE data is imported or exported in your current session.DATE data can be set to be treated either using the ANSI date format (DATEFORM=ANSIDATE) or using the Teradata date format (DATEFORM=INTEGERDATE).

Page 68: A Guide to Teradata Keywords

DECLARE is used in two cases, one as DECLARE CONDITION HANDLING and another one as DELARE CURSOR.

DBC Stands for Database Computer.The first teradata system was DBC/1012 where 1012 is nothing but 1 Terabyte (10 to the power of 12) DBC is first user of teradata.

DECIMAL [(n[,m])] means the decimal data type can be defined optionally:• Without specifying the precision value n or scale value m.• Specifying precision (n) only.• Specifying both values (n,m).• You cannot specify scale without first defining precision.

USING (europe_sales DECIMAL(9,2))INSERT INTO tab1 VALUES (:europe_sales, 1);

Default is a keyword which is used to set the variables to get the default values by using it in the DDL statements. For example, In the CREATE PROFILE statement,DEFAULT DATABASE is a keyword allowing us to specify the default database for a user with this profile.If no default database is defined in the profile assigned to a user, the system uses the setting defined for the user.

CREATE PROFILE human_resources ASDEFAULT DATABASE = personnel;

Specify this mode with a required AS DEFERRED clause. Transfers LOBs sequentially from client-to-server in 64 Kbyte fragments. After the Teradata Database receives each LOB fragment, it sends an acknowledgement to the application, which then either sends the next LOB fragment or, if all the data has been sent, terminates the request.You can only transmit single rows in deferred mode. There is no limit on the size of the request. In this mode, the server requests the application to transmit the LOB after validating, but before completing, the SQL request. The server returns a failure if an SQL statement that contains a deferred LOB is performed on every AMP in the system (usually, but notalways, excluding single AMP systems). Note that this refers only to all-AMP requests. The server also prevents overlapping deferred LOB requests within one query. If there are multiple LOBs identified as being transferred in deferred mode, the server might not request them in the order in which they are specified in the USING clause.

The following example passes the CLOB values for column b in deferred chunks:USING (a INTEGER,b CLOB AS DEFERRED)INSERT INTO mytable VALUES (:a, :b);

DEFINER is a keyword that associates an external routine with an operating system server user to the database that contains the external routine. If you specify DEFINER, then database_name must be the containing database for the external routine.You can specify either a DEFINER or an INVOKER, but not both.

CREATE AUTHORIZATION sales_processing AS DEFINERDOMAIN ‘DistrictA’USER ‘salesmng’PASSWORD ‘mysecret’;DEGREES takes a value specified in radians and converts it to degrees. RADIANS takes a value specified in degrees and converts it to radians.The Default title for DEGREES(arg) is (5.72957795130823E001*arg)DEGREES and RADIANS are useful when working with trigonometric functions such as SIN and COS, which expect arguments to be specified in radians, and inverse trigonometric functions such as ASIN and ACOS, which return values specified in radians.Eg: DEGREES(1.0) - result 5.72957795130823E 001

The DELETE command deletes the contents of either the saved or restored journal areas. Allows DELETE of a row from the specified table. (In practice, any nontrivial DELETE command will require SELECT privilege as well, since it must reference table columns to determine which rows to delete.)

Page 69: A Guide to Teradata Keywords

used for Sort Direction.DESC nothing but descending order. It is used in ORDER BY clause.

Teradata also provides diagnostic statements that support the Teradata Index Wizard and the cost-based and sample-based components of the target level emulation facility used to emulate a production environment on a test system:• DIAGNOSTIC HELP PROFILE• DIAGNOSTIC SET PROFILE• DIAGNOSTIC COSTPRINT• DIAGNOSTIC DUMP COSTS• DIAGNOSTIC HELP COSTS• DIAGNOSTIC SET COSTS• DIAGNOSTIC DUMP SAMPLES• DIAGNOSTIC HELP SAMPLES• DIAGNOSTIC SET SAMPLES• DIAGNOSTIC “Validate Index”

GET DIAGNOSTICS retrieves information about successful, exception, or completion conditions from the Diagnostics Area.The following example illustrates the usage of the statement information item fieldROW_COUNT in a GET DIAGNOSTICS statement. During the execution of the procedure,the GET DIAGNOSTICS statement sets the rowcount parameter to zero. The CALL statementreturns OParam = 0 and rowcount = 0.CREATE PROCEDURE getdiag1 (OUT OParam INTEGER,INOUT rowcount INTEGER)BEGINSELECT c1 INTO OParam FROM tab1; -- Returns warning NODATA FOUNDGET DIAGNOSTICS rowcount = ROW_COUNT;IF (rowcount = 0) THENSET OParam = 0;END IF;END;BTEQ> CREATE SET TABLE tab1 (c1 INTEGER);BTEQ> CALL getdiag1(OParam, NULL);

ALTER TRIGGER <dbname.triggername> DISABLED.DISABLED specifies that that the named trigger or all triggers on the named table are to be disabled.Disabled triggers continue to exist as database objects, but cannot execute. For a trigger to execute, it must first be enabled.

DISPATCH is a non reserved keyword according to SQL 2003 status. It is not in teradata status. But even, usage of DISPATCH as a variable name can be avoided.

The DISTINCT operator will consolidate duplicate output rows to a single occurrence.DISTINCT appears directly after SELECT, and before the first named column. It may appear to apply only to the first column, but in fact, DISTINCT applies to all columns named in the query

SELECT DISTINCT department_number ,job_code FROM employee WHERE department_number = 501; Query returns the rows for Distinct combination of department_number and job_code.

DO is the code for the term DROP PROFILE. It is a System level privileges which is granted by DBC or another user who already has the privilege. When you create a profile, you automatically receive creator privileges (implicit privileges granted through ownership do not apply). This gives you the DROP PROFILE privilege on a profile.

Page 70: A Guide to Teradata Keywords

FLOAT is a datatype represent values in sign/magnitude form ranging from 2.226 x 10-308 to 1.797 x 10308.FLOAT is synonymous with REAL and DOUBLE PRECISION.CREATE TABLE Salaries(Id CHAR(9),SalaryFactor FLOAT BETWEEN .1 AND 1E1 );

DR is the code for DROP ROLE. It is a System level privileges which is granted by DBC or another user who already has the privilege. When you create a role, you automatically receive creator privileges (implicit privileges via ownership do not apply). This gives you the DROP ROLE privilege and the WITH ADMIN OPTION privilege.

DROP is a DDL coommand. Can be used to drop a database object. Syntax : DROP TABLE <tablename>;

It is an option in BEGIN QUERY LOGGING. This option is used to set ranges and to summarize counts of the number of requests that fall into anelapsed time interval.The SUMMARY value is expressed in units of 1.00 seconds.This is the default.

It is an option in BEGIN QUERY LOGGING. This option is used to set ranges and to summarize counts of the number of requests that fall into anelapsed time interval.The SUMMARY value is expressed in units of 0.01 second, so it provides finer granularity for elapsed time than ELAPSEDSEC.

ALTER TRIGGER <dbname.triggername> ENABLED.ENABLED specifies that the named trigger or all triggers on the named table are to be enabled. Enabled triggers function as active database objects and follow normal trigger protocol.

END-EXEC terminates an SQL statement in an embedded SQL client COBOL application program.• END-EXEC is mandatory for all SQL statements embedded in a client COBOL application program. The statement terminator for SQL embedded within C and PL/I applications is the SEMICOLON character.• You cannot use END-EXEC with interactive SQL statements.

The "_" and "%" symbols are used as 'wildcards' in the string expression of the LIKE construct. However, what if one of the wildcard symbols is in the expression you are evaluating. For example, to search for the substring "95%", you must define an ESCAPE character to instruct the Parser to treat the '%' as a non-wildcard character.Characters following the escape character are not treated as wildcards.

SELECT tablenameFROM dbc.tablesWHERE tablename LIKE '_Z_%' ESCAPE 'Z';

The defined escape character is the letter 'Z'. The first "_" (underscore) seen represents a wildcard - i.e., any single arbitrary character. The "Z_" sequence tells the Parser that the second "_" (underscore) is treated as a character, not as a wildcard.

Result is those rows returned by the first SELECT except for those also selected by the second SELECT.MINUS is the same as EXCEPT.SELECT statement_2EXCEPTSELECT statement_3;

Page 71: A Guide to Teradata Keywords

EXEC is same as EXECUTE

This keyword can be used in many cases. One is as an option in ARCHIVE statement.EXCLUDE is to prevent specific databases from being archived.EXCLUDE TABLES to prevent specific tables from being archived.For restoring also, EXCLUDE TABLES is used.The EXCLUDE TABLES option allows us to delete all objects in the target database excluding the indicated tables.

Its is one of locking mode.Lock is put on a database or table when the object is undergoing structural changes or being restored by a host utility. Prohibits access to the object by any other user.

EXECUTE keyword is used to perform a macro, or a function or a procedure. EXEC can also be used.We need to have EXCEUTE privilege to execute an object.

EXISTS tests a specified table (normally a derived table) for the existence of at least one row (that is, it tests whether the table in question is non-empty). EXISTS is supported as the predicate of the search condition in a WHERE clause.The function of the EXISTS predicate is to test the result of subquery. If execution of the subquery returns response rows then the where condition is considered satisfied. Note that use of the NOT qualifier for the EXISTS predicate reverses the sense of the test. Execution of the subquery does not, in fact, return any response rows. Instead, it returns a boolean result to indicate whether responses would or would not have been returned had they been requested.

To select rows of t1 whose values in column x1 are equal to the value in column x2 of t2, one ofthe following queries can be used:SELECT * FROM t1 WHERE x1 IN(SELECT x2 FROM t2);SELECT * FROM t1 WHERE EXISTS(SELECT * FROM t2 WHERE t1.x1=t2.x2);

EXIT handlers deal with conditions that are serious enough to terminate the procedure.When a condition is raised, an EXIT handler does the following:1 Executes the handler action.2 Implicitly exits the BEGIN … END compound statement in which the handler is declared.3 The stored procedure execution continues with the remaining statements outside the compound statement. If the procedure contains no other statement, the procedure terminates and control passes to the caller.

CREATE PROCEDURE spSample6()BEGINDECLARE hNumber INTEGER;DECLARE EXIT HANDLERFOR SQLSTATE ’42000’INSERT INTO Proc_Error_Table(:SQLSTATE, CURRENT_TIMESTAMP, ’spSample6’,’Failed to Insert Row’);Raises e (the base of natural logarithms) to the power of the argument, where e = 2.71828182845905.sel exp(1) Result:2.72EXPIRE = n staement si specified while creating the profile.It represents the number of days to elapse before the password expires. A value of 0 for n indicates the password never expires.The purpose of the extract fuction is to extract a single specified full ANSI SQL-2003 field from any DateTime or Interval value, converting it to an exact numeric value.The following returns 12 as an integer.SELECT EXTRACT (DAY FROM '1996-12-12');This example returns an error because the character literal does not evaluate to a valid date.SELECT EXTRACT (DAY FROM '1996-02-30');

Page 72: A Guide to Teradata Keywords

NOT FOUND is a condition handler condition , indicates a generic completion condition when no data is found.

A fallback table is a duplicate copy of a primary table. Each fallback row in a fallback table is stored on an AMP different from the one to which the primary row hashes. This storagetechnique maintains availability should the system lose an AMP and its associated disk storagein a cluster. In that event, the system would access data in the fallback rows.Syntax:CREATE TABLE department, FALLBACK(department_number SMALLINT)UNIQUE PRIMARY INDEX (department_number);

FastExport is a Client Utility.This utility proides a means of reading large volumes of data from Teradata Database.It is used in SQL request as

HELP 'FASTEXPORT'. This provides online help to the mentioned requested utility.

FETCH is used only using cursors. FETCH... INTO... statement to individually fetch and write the rows into host variables. The application can then use the host variables to do computations.

FETCH cursor1 INTO cvar1, p_amt;

FLOAT is a datatype represent values in sign/magnitude form ranging from 2.226 x 10-308 to 1.797 x 10308.FLOAT is synonymous with REAL and DOUBLE PRECISION.CREATE TABLE Salaries(Id CHAR(9),SalaryFactor FLOAT BETWEEN .1 AND 1E1 );

Returns the largest integer equal to or less than the input argument.

SELECT FLOOR(-6.5);

FORMAT controls the display of expressions and column data and conversions between data types.SELECT SUM(Salary) (FORMAT '$$99,999.99')FROM Employee;is:SUM(Salary)-----------$851,100.00FORMAT phrases, by themselves, cannot cause conversion of character to numeric data, or numeric to character data. An error message is returned if a FORMAT phrase implies data conversion.

We can specify the default value for free space left on a cylinder during certain operations on a table-by-table basis via the FREESPACE option in the CREATE TABLE and ALTER TABLE statements.

The following ALTER TABLE statement changes the freespace to 5 percent:ALTER TABLE employee,FREESPACE = 5 PERCENT;

GIVE transfers ownership of a database or user space to another user. Also transfers all databases and users owned by the transferred database or user.The following statement transfers ownership of the finance database from user administrator to user Chin.GIVE Finance TO Chin;

Page 73: A Guide to Teradata Keywords

GOTO label; Jumps to the specified label.IF SQLCODE = -651 THEN GOTO 100

It is a datatype. The GRAPHIC types are equivalent to the type CHARACTER CHARACTER SET GRAPHIC, which is the form to use for all new development.

GROUPING is an aggregate function which returns a value that indicates whether a specified column in the result row was excluded from the grouping set of a GROUP BY clause. Syntax : GROUPING expression ( ); where 'expression' is a column in the result row that might have been excluded from a grouped query containing CUBE, ROLLUP, or GROUPING SET. The argument must be an item of a GROUP BY clause.

It is the keyword introducing the condition handler declaration.CONTINUE or EXIT are the type of the condition handler being requested.DECLARE EXIT HANDLERFOR sqlstate '42000'BEGINOPEN emp_cursor;SET p1='FAILED TO INSERT ROW';END;

Returns the identification number of the primary AMP corresponding to the specified hash bucket number. If no hash bucket number is specified, HASHAMP returns one less than the maximum number of AMPs in the system.The expression argument must evaluate to an INTEGER type where the valid range of values depends on the system setting for the hash bucket size.The following query returns the distribution of the hash buckets among the primary AMPs.SELECT B, HASHAMP (B)FROM TORDER BY 1;

Returns the identification number of the fallback AMP corresponding to the specified hash bucket. If no hash bucket is specified, HASHBAKAMP returns one less than the maximum number of AMPs in the system.The expression argument must evaluate to INTEGER data type where the valid range of values depends on the system setting for the hash bucket size.This query returns the distribution of the hash buckets among the fallback AMPs.SELECT B, HASHBAKAMP (B)FROM TORDER BY 1;

Returns the hash bucket number that corresponds to a specified row hash value. If no row hash value is specified, HASHBUCKET returns the highest hash bucket number.HASHBUCKET returns an INTEGER data type.If you call HASHBUCKET without an argument, it returns the maximum hash bucket.SELECT HASHBUCKET();If you call a HASHBUCKET function with an argument of NULL, the function returns NULL.SELECT HASHBUCKET(NULL);The following example returns the number of rows in each hash bucket where C1 and C2 areto be the primary index of T.SELECT HASHBUCKET (HASHROW (C1,C2)), COUNT (*)FROM TGROUP BY 1ORDER BY 1;

Page 74: A Guide to Teradata Keywords

Returns the hexadecimal row hash value for an expression or sequence of expressions. If no expression is specified, HASHROW returns the maximum hash code value.HASHROW is particularly useful for identifying the statistical properties of the current primary index, or to evaluate these properties for other columns to determine their suitability as a future primary index.The following example returns the average number of rows per row hash, where columns date_field and time_field constitute the primary index of the table eventlog.SELECT COUNT(*) / COUNT(DISTINCT HASHROW (date_field,time_field))FROM eventlog;If columns datefld and timefld qualify for a unique index, this example returns the average number of rows with the same hash synonym.

This functionality is provided by Teradata for generating Sequence numbers without user’s intervention or writing SQL for it. Identity column is nothing different than the traditional sequence generator object, but defined on Table as column while creating Table. Definition of IDENTITY column is given as follows: CREATE SET TABLE Customer(Cust_Num INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 1000INCREMENT BY 1MINVALUE 1MAXVALUE 5000000NO CYCLE),Cust_Name Varchar(30))UNIQUE PRIMARY INDEX (Cust_Num );Advantages: - It is always UNIQUE. No user intervention requiredDisadvantages: - Sequence number generation is not always incremental order. There can be GAPS in sequences. Sequence number SEED value can not be changed.DISPLAY IFP is a TDP command.It specifies the status of PEs allocated to the TDP.It will also explain • Whether a PE is disabled • Whether a channel is down

Returns true if a specified value matches any value in a subquery or a list.

SELECT *FROM Table1WHERE Column1 IN (Valu1, Value2, …)

This is used for increasing the automatic sequence generation.The (possibly negative) interval on which to increment system-generated numbers. The default is 1.The value can be any whole number less than or equal to the value of DBSControl field IdCol Batch Size except 0.

CREATE MULTISET TABLE test01 (a1 INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1INCREMENT BY 20MAXVALUE 1000),a2 INTEGER);

It is a boundary_option value in INITAE INDEX ANALYSIS staement.This represents the maximum number of new indexes, including secondary and join indexes, that can be recommended per table.The default is 16.The system limit is 32.aThe valid range is 1 to 32.

INITIATE INDEX ANALYSIS ON table_1FOR MyWorkloadIN MyQCDAS table_1IndexSET IndexesPerTable = 2;

Page 75: A Guide to Teradata Keywords

It is a boundary_option value in INITAE INDEX ANALYSIS staement. This controls how estimated index maintenance costs are used duringanalysis. The following values are supported:Code Description0 Maintenance costs are not estimated. The feature is disabled.1 Maintenance costs are estimated only as supplemental information for the final index recommendations. This is the default.2 Maintenance costs are used to evaluate and choose between candidate indexes and are also included with the final recommendations.

INITIATE INDEX ANALYSIS statement analyzes a query workload and generates a set of recommended secondary and single-table join indexes for optimizing its processing.

INSERT is a DML command. This is used to insert the records in to the database object.INSERT INTO t VALUES (’AAAA’, 1);

It is an optional keyword specification used in the CREATE TYPE statemnt , that makes it possible to create a constructor method for the type, enabling you to instantiate a value having that type. INSTANTIABLE is the default and only valid specification.The Teradata Database does not support a NOT INSTANTIABLE option.

Represents a signed, binary integer value from -2,147,483,648 to 2,147,483,647.INTEGER values are stored as four bytes with the least significant byte first.In the following table definition, column TelNo is an INTEGER data type:CREATE TABLE Contact(Id CHAR(9),LastName CHAR(26),TelNo INTEGER);

suppose the session dateform is INTEGERDATE, and the default DATE format of the system is set to 'yyyymmdd' through the tdlocaledef utility.Consider the following table, where the start_date column uses the default DATE format and the end_date column uses the format 'YYYY/MM/DD':CREATE TABLE date_log(id INTEGER,start_date DATE,end_date DATE FORMAT 'YYYY/MM/DD');The following INSERT statement works because the character strings match the formats of the corresponding DATE columns and Teradata Database can successfully perform implicit character-to-DATE conversion:INSERT INTO date_log (1099, '20030122', '2003/01/23');

It is a keyword that associates an operating system user to the database user who invokes the external routine.If you specify INVOKER, then database_name must be the logondatabase for the user.You can assign only one INVOKER authorization name per database.You can specify either a DEFINER or an INVOKER, but not both. This is a Syntax element for the CREATE AUTHORIZATION statement which creates the definition for an authorization object.

This example creates an INVOKER authorization object with the name sales for the domaineastsales, the user name sam johnson, and the user password tercesym.CREATE AUTHORIZATION sales AS INVOKERDOMAIN ‘eastsales’USER ‘sam johnson’

IOCOUNT is a limit option in BEGIN QUERY LOGGING. This is used to set ranges and to summarize counts of the number of requests that fall into an I/O interval.

Page 76: A Guide to Teradata Keywords

Japanese Industrial Standards (JIS).The collation sequence is as follows.1 Characters and symbols from the JIS X 0201 standard (in JIX X 0201 order)2 Ideographs, characters, and symbols from the JIS X 0208 standard (in JIS X 0208 order)3 Ideographs, characters, and symbols from the JIS 0212 standard (in JIS X 0212 order)4 IBM Kanji ideographs not present in JIS X 0208 and JIS X 0212 (in KanjiEBCDIC order)5 User-defined ideographs (in U+ order)6 Any remaining characters in UNICODE (in U+ order)

A journal is a record of some kind of activity. Teradata Database supports several kinds of journaling. The system does some journaling on its own, while you can specify whether to perform other journaling. Types of Jounal: Down Amp Recovery Journal, Transient Journal,Permanent Journal.Users activate permanent journaling by including the JOURNAL option in the CREATE or MODIFY statements for users or databases.

KANJI1 is one of four server character sets that Teradata Database uses to support Japanese characters. For Kanji1 character data, the ASCII collation provides a collation similar to that of the client, assuming the session character set is KanjiSJIS_0S, KanjiEUC_0U, or something very similar. However, ASCII collation does not sort like the client if the data is stored onthe server using the ShiftJIS or Unicode server character sets.

KanjiSJIS is one of four server character sets that Teradata Database uses to support Japanese characters. For character data stored on the server as KanjiSJIS or Unicode, the best way to order the session character set is to use the CHARSET_COLL collation. For character data stored on the server as either KanjiSJIS or Unicode, the CHARSET_COLL collation provides the collation that is closest to sorting on the client.

Kurtosis is the fourth moment of a distribution. It is a measure of the relative peakedness orflatness compared with the normal, Gaussian distribution.The normal distribution has a kurtosis of 0.Positive kurtosis indicates a relative peakedness of the distribution, while negative kurtosisindicates a relative flatness.

LATIN is a internal server character set which teradata database uses. Standard language support provides Teradata Database internal coding for the entire set ofprintable characters from the ISO 8859-1 (Latin1) and ISO 8859-15 (Latin9) standard,including diacritical marks such as ä, ñ, Ÿ, OE, and oe, though the Z with caron in Latin9 is notsupported. ASCII control characters are also supported for the standard language set.

Computes the natural logarithm of the argument.Select Ln(2) Result:0.69Specifies that the command takes effect for only the current transaction. After COMMIT or ROLLBACK, the session-level setting takes effect again. Note that SET LOCAL will appear to have no effect if it is executed outside a BEGIN block, since the transaction will end immediately.

When we do multiple transactions on the same object we need to have nonsharable lock.Teradata Lock Manager controls locks on objects.

Locking Levels• Database• Table• Row hash

Locking ModesExclusive-Only on a database or table when the object is undergoing structural changes or being restored by a host utility. Prohibits access to the object by any other user.Write-Locked placed on object when INSERT, UPDATE, or DELETE request. Restricts access by other requests, except those that specify an access lock.Read-Lock put on object when SELECT request is placed. Restricts access by requests that require exclusive or write locks.Access-An access lock is shareable, permitting the user to read an object that may be already or concurrently locked for read or write.

Page 77: A Guide to Teradata Keywords

While creating a profile, We can mention the number of minutes to elapse before unlocking a locked user using LOCKEDUSEREXPIRE = n. Special values of n are 0 (Unlocks the user immediately.) and -1(Locks the user indefinitely.)CREATE PROFILE human_resources ASDEFAULT DATABASE = personnel,PASSWORD =(EXPIRE = 90,MAXLOGONATTEMPTS = 10,LOCKEDUSEREXPIRE = -1);

Computes the base 10 logarithm of an argument.select Log(2) Result:0.30

LOOP is a keyword introducing an iteration statement that repeats the execution of one or more statements embedded within the defined loop.Returns a character string identical to character_string_expression, except that all uppercase letters are replaced by their lowercase equivalents.LOWER (character_string_expression)The following example compares the strings on a case blind basis.SELECT idFROM namesWHERE LOWER(charfield_1) = LOWER(charfield_2);

one or more SQL statements that can be executed by performing a single statement. Each time the macro is performed, one or more rows of data may be returned.

CREATE MACRO-incorporate a frequently used SQL statement or series of statements into a macro.EXECUTE-run a macro.DROP MACRO-delete a macro.

Frequency for EXECExecutes the procedure or query once for each source-target table map for which it is specified. Using MAP renders the results invalid for any subsequent maps that have the same source table. For example, if a source table is being synchronized with more than one target table, the results would only be valid for the first source-target map. MAP is the default.

The Moving Average (MAVG) function permits the calculation of a moving average on a specified column, based on a defined number of rows known as the query width.MAVG(colname, n, sort_item1, sort_item2, …)n = the defined width of the query, I.e. how many preceding rows are used to compute avgSELECT salesdate, itemid, sales, MAVG(sales, 7, salesdate)FROM daily_sales;salesdate itemid sales MAvg98/01/01 10 150.00 150.0098/01/02 10 200.00 175.0098/01/03 10 250.00 200.0098/01/05 10 350.00 237.5098/01/10 10 550.00 300.0098/01/21 10 150.00 275.0098/01/25 10 200.00 264.29

Page 78: A Guide to Teradata Keywords

MAX is an aggregate function which will return the maximum column value for the specified column.MAX is valid for character data as well as numeric data. When used with a character expression, MAX returns the highest sort order. Nulls are not included in the result computation.If value_expression is a column expression, the column must refer to at least one column in the table from which data is selected.The value_expression must not specify a column reference to a view column that is derived from a function.SELECT MAX(Name)FROM Employee;Maximum(Name)-------------Zorn J

While Creating profile, to set the maximum characters for the password atrribute, this keyword is used. It refers the maximum number of characters in a password string. The valid range for n is 1 to 30.

It is the maximum value to which a system-generated numeric series can increment. MAXVALUE applies only to system-generated numbers Can be any whole number with a value greater than the value specified for START WITH. The default is the maximum number for the data type defined for the column. When cycling is not enabled, the sum of the specified values for START WITH and INCREMENT BY must be less than MAXVALUE. If they are not, then the system generates only one number before the maximum limit is exceeded.

CREATE TABLE t (idnum INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 1000INCREMENT BY 10MINVALUE 0MAXVALUE 300000),phone INTEGER)UNIQUE PRIMARY INDEX(idnum);

The Moving Difference (MDIFF) function permits a calculation of a moving difference of a specified column, based on a defined query width (n).MDIFF(colname, n, sort_item1, sort_item2, …)n = the defined width of the query, I.e. how many rows back for the subtrahend

salesdate itemid sales MDiff98/01/01 10 150 ?98/01/02 10 200 ?98/01/03 10 250 ?98/01/05 10 350 20098/01/10 10 550 35098/01/21 10 150 -100

Page 79: A Guide to Teradata Keywords

Merges a source row set into a target table based on whether any target rows satisfy a specified matching condition with the source row.WHEn MATCHED THEN UPDATE, WHEN NOT MATCHED THEN INSERT.CREATE TABLE t1 (a1 INTEGER,b1 INTEGER,c1 INTEGER);CREATE TABLE t2 (a2 INTEGER,b2 INTEGER,c2 INTEGER);MERGE INTO t1USING t2ON a1 = 10WHEN MATCHED THENUPDATE SET c1 = c2WHEN NOT MATCHED THENINSERT (b2, c2, a2);

Returns a column value that is the minimum value for value_expression for a group.MINIMUM is valid for character data as well as numeric data. MINIMUM returns the lowest sort order of a character expression.The computation does not include nulls.If value_expression specifies a column expression, the expression must refer to at least one column in the table from which data is selected.If value_expression specifies a column reference, the column must not be a view column that is derived from a function.SELECT MINIMUM(Name)FROM Employee;Minimum(Name)-------------Aarons A

While Creating profile, to set the minimum characters for the password atrribute, this keyword is used. It refers the minimum number of characters in a password string. The valid range for n is 1 to 30.

It is the minimum value to which a system-generated numeric series can decrement. MINVALUE applies only to system-generated numbers.The value can be any whole number with an absolute value less than the value specified for START WITH. The default is the minimum number for the data type defined for the column. When cycling is not enabled, the sum of the specified values for START WITH and INCREMENT BY must be greater than MINVALUE. If they are not, then the system generates only one number before the minimum limit is exceeded.Specifying NO MINVALUE causes numbering to restart its cycle from the minimum value that can be expressed for the data type of the column when the MAXVALUE limit is reached. You can only specify NO MINVALUE when the INCREMENT BY interval is a negative number.The default is the minimum value for the data type specified for the identity column.CREATE TABLE t (idnum INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 1000INCREMENT BY 10MINVALUE 0MAXVALUE 300000),phone INTEGER)UNIQUE PRIMARY INDEX(idnum);

MultiLoad (MLoad) allows you to upload data from the client to your Teradata Database. It operates on multiple tables simultaneously and can also insert, update, and delete data. The maximum number of MLoad jobs you can run is 152. The default is 5. (See Utilities formore information.)

Page 80: A Guide to Teradata Keywords

Calculates the remainder in a division operation

SELECT customer_number ,zip_code FROM location WHERE zip_code MOD 10000 = 0;The Moving Sum (MSUM) function permits a calculation of a moving sum of a specified column, based on a defined query width (n).MSUM(colname, n, sort_item1, sort_item2, …)n = the defined width of the query, i.e., how many preceding rows are used to compute sum.n<= 4096SELECT salesdate, itemid, sales, MSUM(sales, 3, salesdate)FROM daily_sales;salesdate itemid sales MSum98/01/01 10 150.00 150.0098/01/02 10 200.00 350.0098/01/03 10 250.00 600.0098/01/05 10 350.00 800.00The MULTINATIONAL keyword defines the name of the default collation sequence for the user to be one of the International sort orders.The MULTINATIONAL parameter determines that the International sort order is to be used.This parameter returns an error unless the hashing algorithm is set to recognize diacritical characters.On International/European sites MULTINATIONAL collation is two-level.On Japanese language sites, collation is single-level and is always available.A table defined to permit duplicate rows is called a MULTISET table because its properties are based on a multiset, or bag, model, where bag and multiset are defined as an unordered group of elements that may be duplicates.FastLoad cannot load tables with duplicate values in tables defined as MULTISET.CREATE MULTISET TABLE test01 (a1 INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1INCREMENT BY 20MAXVALUE 1000),a2 INTEGER);

EXTERNAL [ NAME [ <external name> | <string> ] ] Clause is used in create a function which can be used whenever the customer wants to bring data from outside the Teradata database directly into a query, without any intermediate step. It is also useful for shredding XML (or similar) data and extracting the contents into multiple rows. This is used to specify the location of source, object and libraries that make up or that are needed to create the function.REPLACE PROCEDURE ET001_xsp1(IN A_Name VARCHAR(10),OUT resultx VARCHAR(16000))LANGUAGE CMODIFIES SQLDATAPARAMETER STYLE TD_GENERALEXTERNAL NAME 'SP!CLI!CS!ET001_xsp1!ET001_xsp.c'; Here,The statement must include an EXTERNAL NAME string clause that specifies the Call-Level Interface (CLI) package. Specifying the CLI package provides the compilation process on the node the information it needs to link with CLIv2 libraries and set up environment variables.

NAMED is a keyword indicating that the variable that follows is the temporary new name for expression.The temporary name can be referenced elsewhere in the request. But it should not be the same as another column name of any table used in a query.Column headings default to the newly assigned name.The keyword NAMED is required in Teradata syntax. The keyword AS is optional. The NAMED clause is enclosed in parentheses immediately following the renamed column.In the following SELECT statement, a NAMED phrase associates an arithmetic expressionwith the name “Projection” so that the calculated column can be more easily referenced in theWHERE clause.SELECT Name, ((Salary + (YrsExp * 200))/12) (NAMED Projection)FROM EmployeeWHERE DeptNo = 600 AND Projection < 2500;COLUMN NAMES is an index attribute.Lists the names of the columns defined for theindex.On a standard language support system, the data type for COLUMN NAMES is VARCHAR(512) CHARACTER SET LATIN.On a Japanese language support system, the data type for COLUMN NAMES is VARCHAR(512) CHARACTER SET UNICODE if a multibyte site-defined session character set such as UTF-8, UTF-16, Chinese, or Korean is used.For any other language support system, the data type for COLUMN NAMES is VARCHAR(512) CHARACTER SET KANJI1.

Page 81: A Guide to Teradata Keywords

It is report option in the diagnostic help profile.Report cost parameters for workload management predicted elapsed times only.It is report option in the diagnostic help profile.Report initialization parameters for workload management predicted elapsed times only.

Returns the length of string_expression in octets when it is converted to the named character set

NATURAL is a fourth-generation language tool from Software AG. NATURAL allows users to access DB2 and other databases either by writing programs using the NATURAL programming language or interactively through native SQL commands. Through TS/API, NATURAL can be used to access information stored in a Teradata Database.It is an equivalent introductions to a table correlation name for the new values transition table.NEW TABLE is the form specified by the ANSI SQL-2003 standard.NEW_TABLE is a Teradata extension retained for backward compatibility.You can specify NEW_TABLE or NEW TABLE references in both statement triggers and row triggers. NEW_TABLE and NEW TABLE are valid only in AFTER trigger definitions with the INSERT and UPDATE triggering events.

CREATE TRIGGER Trig1 AFTER INSERT ON Tab1REFERENCING NEW_TABLE AS NewTableFOR EACH STATEMENT(CALL Sp1(NewTable.c1,NewTable.C2);)

Specifies that if the indicated lock cannot be obtained, the statement should be aborted.The NOWAIT option is an excellent way to avoid waiting on conflicting locks.The NOWAIT option tells that a transaction is to ABORT immediately if the LOCK MANAGER cannot immediately place the lock.A 7423 return code informs the that the lock could not be placed due to an existing, conflicting, lock. Locking Dept_table for Read NOWAITSelect * from From Dept_Table Order by Dept_No

The SQL Keyword Null is used to handle the missing information in the relational database. An SQL null simply means that the value of interest is not known. NULL does not equal to 0 or an empty string. Both 0 and empty string represents a value, while NULL has no value.

CASE expressionTHEN NULLENDorCASE expressionTHEN expressionELSE NULLEND

NULLABLE is an attribute which will expose whether the particular column is nUll or not. If the code is Y, then can be NULLand If the code is N, then the column is NOT NULLThe NULLIF function accepts two parameters. If the first parameter is equal to the second parameter, NULLIF returns Null. Otherwise, the value of the first parameter is returned.3) NULLIF(value1, value2)Thus, NULLIF is an abbreviation for the following CASE expression:CASE WHEN value1 = value2 THEN NULL ELSE value1 END

Converts data from zero to null to avoid problems with division by zero.If argument is nonzero -->the value of the numeric argumentIf argument is null or zero--> NULLSELECT empno, NULLIFZERO(hcap)FROM employeeWHERE empno = 10019 ;

Page 82: A Guide to Teradata Keywords

For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 10.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 11.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 12.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 13.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 14.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 15.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 2.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 3.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 4.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 5.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 6.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 7.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 8.For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the level 9.

ORDER BY clause specifies how results data are to be sorted. A view definition cannot contain an ORDER BY clause.Depending on the specific situation, We can specify one or more sort fields on expression, column_name, column_name_alias, or column_position.The first sort field determines the primary sort, with any subsequent sort fields specifying secondary, tertiary, …, and n-ary sorts, respectively, that occur when rows have the same values for the preceding sort fields.We can specify a sort field to be sorted in either ascending or descending order. If we do not specify an ORDER BY clause, the result rows are returned unsorted.

The following example produces a list of employees, sorted by years of work experience.SELECT name, jobtitle, yrsexpFROM employeeORDER BY yrsexp;The QUALIFY clause with the RANK or ROW_NUMBER ordered analytical functions returns the same results as the TOP n operator.For example, the following two requests have the same semantics:SELECT TOP 10 *FROM sales ORDER BY county;SELECT *FROM sales QUALIFY ROW_NUMBER() OVER (ORDER BY COUNTY) <= 10;It is a report_option in the DIAGNOSTIC HELP PROFILE . Report_option specifies that a report of cost profile information should be returned for the specified set of parameters and flags.PARAMID Report any parameters having a ConstId value between lower_boundary and upper_boundary.For a table that is defined with a partitioned primary index (PPI), the PARTITION column provides the partition number of the combined partitioning expression associated with a row, where the combined partitioning expression is derived from the partitioning expressions defined for each level of the PPI. This is zero for a table that does not have a PPI.CREATE TABLE …PRIMARY INDEX (invoice_number)PARTITION BY division_number;

For tables that are defined with a multilevel PPI, these columns provide the partition number associated with the corresponding level 1. These are zero for a table that does not have a PPI and zero if the level is greater than the number of partitions.The following example selects all rows from the orders table for customers that meet thefollowing criteria:• custkey values are between 100 and 199, specified by partition number 2 for level 1 (WHEREorders.PARTITION#L1=2)• orderdate values are from January, 2001, specified by partition number 13 for level 2(AND orders.PARTITION#L2=13)SELECT *FROM ordersWHERE orders.PARTITION#L1 = 2AND orders.PARTITION#L2 = 13;

Page 83: A Guide to Teradata Keywords

If you specify a NOT PARTITIONED phrase and the existing table has a PPI, then its primary index is modified to be an NPPI if the table is empty.If the table is not empty, then the system reports an error.If you specify a NOT PARTITIONED phrase and the existing table has an NPPI, then the primary index is not changed with respect to its partitioning.If you specify neither a PARTITIONED BY nor a NOT PARTITIONED phrase, then the primary index is not changed with respect to its partitioning.PASSWORD is an attribute which has to be mentioned in the CREATE USER statement itself. CREATE USER JANE AS PERM=1000000, PASSWORD=Jane;GRANT LOGON ON ALL TO JANE WITH NULL PASSWORD;

PERCENT_RANK Returns the relative rank of rows for a value_expression.The formula for PERCENT_RANK is:PERCENT_RANK= (RK - 1)/(NR - 1) where RK is rankof the row and NR is number of rows in the window partition.Determine the relative rank, called the percent_rank, of Christmas sales.The following query:SELECT sales_amt,PERCENT_RANK() OVER (ORDER BY sales_amt)FROM xsales;might return the following results. Note that the relative rank is returned in ascending order, the default when no sort order is specified and that the currency is not reported explicitly.sales_amt Rank Percent_Rank100.00 1 0.000000120.00 2 0.125000130.00 3 0.250000140.00 4 0.375000143.00 5 0.500000147.00 6 0.625000150.00 7 0.750000155.00 8 0.875000160.00 9 1.000000To create a spool reserve database, submit a CREATE DATABASE statement and specify the amount of space we want to keep in reserve as the PERM parameter.CREATE DATABASE Spool_Reserve FROM DBADMIN AS PERM = xxxx ; where xxxx is the number of bytes that is a specific percentage of your total available spaceIt is a parameter need to be mentioned while creating a databases.It is the total number of bytes to be reserved for permanent storage of the new database. The space is taken from unallocated space in the database of the immediate owner. The number of bytes can be entered as an integer, decimal, or floating point value. This option must be specified. There is no default.PLACING is an SQL 2003 status Non resered key word.It is not in teradata database status. But Een the usage of PLACINg as a variable name can be avoided.POSITION returns the position in string_expression_2 where string_expression_1 starts.POSITION (string_expression_1 IN string_expression_2) where string_expression_1 is a substring to be searched for its position within the full string and string_expression_2 is a full string to be searched.

SELECT column_1, column_2, POSITION(column_2 IN column_1)FROM iptest;

This represents the number of rows preceding the current row.Preceding value is always a positive integer constant.The maximum number of rows in an aggregation group is 4096 when value PRECEDING appears as the group start or group end.

UNBOUNDED PRECEDING represents the entire partition preceding the current row.

To compute the three-month moving average sales for each store in the sales_tbl table, partition by StoreID, order by SMonth, and perform the computation over the current row and the two preceding rows:SELECT StoreID, SMonth, ProdID, Sales,AVG(Sales) OVER (PARTITION BY StoreIDORDER BY SMonthROWS BETWEEN 2 PRECEDING AND CURRENT ROW)FROM sales_tbl;

Page 84: A Guide to Teradata Keywords

FLOAT is synonymous with REAL and DOUBLE PRECISION. This represents values in sign/magnitude form ranging from 2.226 x 10-308 to 1.797 x 10308.Rounding FLOAT, REAL, DOUBLE PRECISION Data Types: If a value being inserted does not fit into a field defined as a FLOAT, REAL, DOUBLE PRECISION data type, the same rounding rule applies as applies to the DECIMAL/ NUMERIC data type, but the rounding rule is based on the value of the actual number that is stored internally.For example, if the number 0.995 is stored as 0.9949999, it is rounded down to 0.99; if it is stored as 0.9950001, it is rounded up to 1.0.

PREPARE is an executable SQL statement.It specifies that that an SQL_statement_name is to be set up to be executed dynamically.The PREPARE statement is valid only for result set cursors.The following CREATE PROCEDURE request creates a stored procedure that contains dynamic SQL using a PREPARE statement:

CREATE PROCEDURE abc (IN data1v VARCHAR(10),IN data2v VARCHAR(10))DYNAMIC RESULT SETS 1BEGINDECLARE sql_stmt1 VARCHAR(100);DECLARE sales DECIMAL(8,2);DECLARE item INTEGER;DECLARE cstmt CURSOR WITH RETURN FOR stmt1;SET sql_stmt1 = 'SELECT T1.item, T1.sales FROM T1 WHERE'data1v | '= store_name AND ' | data2v | '= region;';PREPARE stmt1 FROM sql_stmt1;OPEN cstmt;FETCH NEXT FROM cstmt INTO item, sales;END;The PREPARE can also be written as follows using parameter markers as seen in the following stored procedure code fragment:SET sql_stmt1 = 'SELECT t1.item, t1.sales FROM t1 WHERE ?''= store_name AND ? = region;';PREPARE stmt1 FROM sql_stmt1;OPEN cstmt USING data1v, data2v;FETCH NEXT FROM cstmt INTO item, sales;

CREATE PROFILE - Creates a new profile that defines a set of system parameters that can be assigned to a group of users.To use CREATE PROFILE, we must have the CREATE PROFILE privilege.New users do not implicitly have the CREATE PROFILE privilege. User DBC or a user who has the CREATE PROFILE privilege WITH GRANT OPTION can grant this privilege to another user.The following statement creates a profile called human_resources that defines the default database to be personnel:CREATE PROFILE human_resources ASDEFAULT DATABASE = personnel;The following statement assigns the human_resources profile to a new user:CREATE USER marks ASPROFILE = human_resources;

Page 85: A Guide to Teradata Keywords

Quaified Specifies that if any view DDL is returned, it is to be qualified by the appropriate database and table names. This qualified text is taken from the DBC.TVM.CreateText column.All qualified objects in the report are enclosed within QUOTATION MARK characters.If you do not specify QUALIFIED, then any returned view DDL is taken from the DBC.TVM.RequestText column and is not qualified by the names of the appropriate database and table names.For Ex:SHOW QUALIFIED SELECT * FROM view_3;The report looks like this:*** Text of DDL statement returned.*** Total elapsed time was 1 second.-------------------------------------------------------------CREATE SET TABLE international.table_1, NO FALLBACK,NO BEFORE JOURNAL,NO AFTER JOURNAL(zno INTEGER)PRIMARY INDEX (a);*** Text of DDL statement returned.-------------------------------------------------------------CREATE SET TABLE us.table_1, NO FALLBACK,NO BEFORE JOURNAL,NO AFTER JOURNAL(eno INTEGER)PRIMARY INDEX (eno);*** Text of DDL statement returned.-------------------------------------------------------------CREATE VIEW "international"."view_1" AS SELECT * FROM"international"."table_1";*** Text of DDL statement returned.-------------------------------------------------------------CREATE VIEW "us"."view_1" AS SELECT * FROM "us"."table_1";*** Text of DDL statement returned.-------------------------------------------------------------CREATE VIEW "international"."view_3" AS SELECT * FROM"international"."view_1"."zno", "us"."view_1"."eno";

QUALIFY filters results of a previously computed ordered analytical function according to user-specified conditions. QUALIFY clause specifies an introduction to a conditional clause that, similar to HAVING, further filters rows from a WHERE clause. The major difference between QUALIFY and HAVING is that with QUALIFY the filtering is based on the result of performing various ordered analytical functions on the data.

When you specify a QUALIFY clause in a query, you must also specify a statistical function inone of the following locations within the query.• Select list of the SELECT clause• Grouping key of the GROUP BY clause• Search condition of the QUALIFY clauseIf you do not specify a statistical function in one of these clauses, then the query fails and thesystem returns an error.

The following request displays each item in a sales table, its total sales, and its rank within the top 100 selling items:SELECT itemid, sumprice, RANK() OVER (ORDER BY sumprice DESC)FROM (SELECT a1.itemID, SUM(a1.sale)FROM sales a1GROUP BY a1.itemID) AS T1 (itemID, sumprice)QUALIFY RANK() OVER (ORDER BY sumprice DESC) <=100;

Page 86: A Guide to Teradata Keywords

A quantile is a generic interval of user-defined width. For example, percentiles divide data among 100 evenly spaced intervals, deciles among 10 evenly spaced intervals, quartiles among 4, and so on. A quantile score indicates the fraction of rows having a sort_expression value lower than the current value. For example, a percentile score of 98 means that 98 percent of the rows in the list have a sort_expression value lower than the current value.

For each row in the group, QUANTILE returns an integer value that represents the quantile of the sort_expression value for that row relative to the sort_expression value for all the rows in the group.Quantile values range from 0 through (Q-1), where Q is the number of quantile partitions specified by quantile_constant.The follwing example displays each item and its total sales in the ninth (top) decile according to the total sales.SELECT itemID, sumPriceFROM (SELECT a1.itemID, SUM(price)FROM Sales a1GROUP BY a1.itemID) AS T1(itemID, sumPrice)QUALIFY QUANTILE(10,sumPrice)=9;Query bands provide you with a way to set your own unique identifiers on Teradata sessions and transactions and to add those identifiers to the current set of session identification fields maintained in DBC.SessionTbl.A query band is a set of user- or middle-tier-application-defined name:value pairs that can be set on a session, a transaction, or both to identify the originating source of a query. We can think of a query band as metadata that is wrapped around a request. Once a query band has been defined, the system passes it to Teradata Database as a list of name:value pairs in a single-quoted string such as the following examples:'org=Finance;report=EndOfYear; universe=west''Job=payroll; Userid=dg120444; Jobsession=1122;'

Setting a Query Band For a SessionThe following example sets a query band with two name:value pairs for the session:SET QUERY_BAND = 'org=Finance;report=Fin123;' FOR SESSION;The pairs in the query band string are org=Finance and report=Fin123.It is a combination of procedural control statements, SQL statements, and control declarations that provide a procedural interface to the Teradata Database.Using stored procedures, we can build large and complex database applications.You can use the C or C++ programming language to write external stored procedures.RADIANS takes a value specified in degrees and converts it to radians.DEGREES and RADIANS are useful when working with trigonometric functions such as SIN and COS, which expect arguments to be specified in radians, and inverse trigonometric functions such as ASIN and ACOS, which return values specified in radians.SIN(RADIANS(60.0))

Returns a random integer number for each row of the results table.

SELECT store_id, product_id, sales, RANDOM(1,3)FROM sales_table;

Store_ID Product_ID Sales RANDOM(1,3)1003 C 20000 11002 C 35000 21001 C 60000 21002 D 50000 31003 D 50000 21001 D 35000 3

RANDOMIZED ALLOCATION specifies whether rows are sampled randomly across AMPS (RANDOMIZED ALLOCATION) or proportionate to the number of qualified rows per AMP (proportional allocation).The proportional allocation option does not provide a simple random sample of the entire population. It provides a random sample stratified by AMPs, but it is much faster, especially for very large samples.Proportional is the default. You select it implicitly by not specifying RANDOMIZED ALLOCATION.

The following query uses randomized allocation without replacement to sample two mutually exclusive samples of 25% and 50%, respectively, of the rows from WI and two mutually exclusive samples of 25% each for CA:SELECT city, state, sampleidFROM storesSAMPLE RANDOMIZED ALLOCATIONWHEN state = 'WI' THEN 0.25, 0.5WHEN state = 'CA' THEN 0.25, 0.25ENDORDER BY 3;

Page 87: A Guide to Teradata Keywords

When ALTERing a MLPPI table, there is a special syntax that is used to reference 11th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 12th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 13th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 14th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 15th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 2nd level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 3rd level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 4th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 5th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 6th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 7th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 8th level being modified. When ALTERing a MLPPI table, there is a special syntax that is used to reference 9th level being modified.

DROP RANGE and ADD RANGE modify an existing partitioning expression to create a new partitioning expression for the table.If the new partitioning expression specifies the NO RANGE option, then no rows are deleted.• Rows can be moved from their current partition to any of the following:• Newly added range partitions.• The NO RANGE partition.• The NO RANGE OR UNKNOWN partition.• Similarly, rows can be moved from the NO RANGE partition to newly added range partitions.The following example Drop and Add Primary Index Partition Ranges and Delete Rows Outside the Defined RangesIt is valid if there are 0 or more rows with o_orderdate values between January 1 1992 (DATE ‘1992-01-01’) and December 31 1992 (DATE ‘1992-12-31’). As a result of the WITH DELETE specification, those rows, if any, are deleted from orders because they do not belong to any partition in the new partitioning expression:ALTER TABLE ordersMODIFY PRIMARY INDEX (o_orderkey)DROP RANGE BETWEEN DATE ’1992-01-01’AND DATE ’1992-12-31’EACH INTERVAL ’1’ MONTHADD RANGE BETWEEN DATE ’1999-01-01’AND DATE ’2000-12-31’EACH INTERVAL ’1’ MONTHWITH DELETE;When ALTERing a MLPPI table, there is a special syntax that is used to reference each level being modified. RANGE#L1 - Level 1 RANGE#L2 - Level 2 :RANGE#L15 - Level 15 It is possible to add or drop ranges at all levels. However adding or dropping ranges at levels 2 through 15, must result in the number of logical partitions at each of these levels remaining the same.When ALTERing a MLPPI table, there is a special syntax that is used to reference 10th level being modified. Eg:ALTER TABLE Orders_PPI_ML MODIFY PRIMARY INDEXDROP RANGE#L10 BETWEEN 1 AND 5 EACH 1ADD RANGE#L10 BETWEEN 11 AND 15 EACH 1WITH DELETE;One range is dropped at the beginning of level 10.

Page 88: A Guide to Teradata Keywords

RANGE_N evaluates an expression and maps the result into one of a list of specified ranges and returns the position of the range in the list.A range is defined by a starting boundary and an optional ending boundary. If an ending boundary is not specified, the range is defined by its starting boundary, inclusively, up to but not including the starting boundary of the next range. The list of ranges must specify ranges in increasing order, where the ending boundary of a range is less than the starting boundary of the next range.An example that defines a partitioned primary index that specifies one partition to which rows are assigned, for any value of the totalorders column, including NULL:CREATE TABLE orders(storeid INTEGER NOT NULL,productid INTEGER NOT NULL,orderdate DATE FORMAT 'yyyy-mm-dd' NOT NULL,totalorders INTEGER)PRIMARY INDEX (storeid, productid)PARTITION BY RANGE_N(totalorders BETWEEN * AND *); RANK is an Ordered analytical functions work over a range of data for a particular set of rows in some specific order to produce a result for each row in the set. RANK function allows ordered ranking of rows based on the valueof the column being ranked.FLOAT is a datatype represent values in sign/magnitude form ranging from 2.226 x 10-308 to 1.797 x 10308.FLOAT is synonymous with REAL and DOUBLE PRECISION.CREATE TABLE Salaries(Id CHAR(9),SalaryFactor FLOAT BETWEEN .1 AND 1E1 );

A recursive query is a way to query hierarchies of data, such as an organizational structure, bill-of-materials, and document hierarchy.A recursive query has three execution phases:1 Create an initial result set.2 Recursion based on the existing result set.3 Final query to return the final result set.2 ways to use Recursie queries:• Preceding a query with the WITH RECURSIVE clause• Creating a view using the RECURSIVE clause in a CREATE VIEW statementThe following recursive query retrieves the employee numbers of all employees who directlyor indirectly report to the manager with employee_number 801:Eg:WITH RECURSIVE temp_table (employee_number) AS( SELECT root.employee_numberFROM employee rootWHERE root.manager_employee_number = 801UNION ALLSELECT indirect.employee_numberFROM temp_table direct, employee indirectWHERE direct.employee_number = indirect.manager_employee_number)SELECT * FROM temp_table ORDER BY employee_number;

REGR_AVGX ( dependent_variable_expression, independent_variable_expression ). This Returns the mean of the independent_variable_expression for all non-null data pairs of the dependent and independent variable arguments.Dependent_variable_expression specifies dependent_variable_expression the dependent variable for the regression. A dependent variable is something that is measured in response to a treatment. The expression cannot contain any ordered analytical or aggregate functions.Independent_variable_expression specifies the independent variable for the regression.An independent variable is a treatment: something that is variedunder your control to test the behavior of another variable.The expression cannot contain any ordered analytical or aggregate functions.REGR_AVGX = SUM(x)/n where x represents independent ariable expression and n is count(x)SELECT REGR_AVGX(weight,height)FROM regrtbl;Regr_Avgx(weight,height)------------------------

Page 89: A Guide to Teradata Keywords

REGR_AVGY ( dependent_variable_expression, independent_variable_expression ). This Returns the mean of the dependent_variable_expression for all non-null data pairs of the dependent and independent variable arguments.Dependent_variable_expression specifies dependent_variable_expression the dependent variable for the regression. A dependent variable is something that is measured in response to a treatment. The expression cannot contain any ordered analytical or aggregate functions.Independent_variable_expression specifies the independent variable for the regression.An independent variable is a treatment: something that is variedunder your control to test the behavior of another variable.The expression cannot contain any ordered analytical or aggregate functions.REGR_AVGY = SUM(y)/n where x represents dependent ariable expression and n is count(x)SELECT REGR_AVGY(weight,height)FROM regrtbl;Regr_Avgy(weight,height)------------------------68

Returns the count of all non-null data pairs of the dependent and independent variable arguments.REGR_COUNT (dependent_variable_expression, independent_variable_expression ) where dependent_variable_expression is the dependent variable for the regression.A dependent variable is something that is measured in response to a treatment. The expression cannot contain any ordered analytical or aggregate functions. And independent_variable_expression is the independent variable for the regression.An independent variable is a treatment: something that is varied under your control to test the behavior of another variable. The expression cannot contain any ordered analytical or aggregate functions.REGR_COUNT can be combined with ordered analytical functions in a SELECT list, QUALIFY clause, or ORDER BY clause.The following SELECT statement returns the number of rows in regrtbl where neither height nor weight is null.SELECT REG_COUNT(weight,height)FROM regrtbl;Regr_Count (weight,height)-------------------------9

Returns the intercept of the univariate linear regression line through all non-null data pairs of the dependent and independent variable arguments.A dependent variable is something that is measured in response to a treatment. The expression cannot contain any ordered analytical or aggregate functions. And independent_variable_expression is the independent variable for the regression.An independent variable is a treatment: something that is varied under your control to test the behavior of another variable. The expression cannot contain any ordered analytical or aggregate functions.The intercept is the point at which the regression line through the non-null data pairs in the sample intersects the ordinate, or y-axis, of the graph.The plot of the linear regression on the variables is used to predict the behavior of the dependent variable from the change in the independent variable. Note that this computation assumes a linear relationship between the variables. There can be a strong nonlinear relationship between independent and dependent variables, and the computation of the simple linear regression between such variable pairs does not reflect such a relationship.

The equation for computing REGR_INTERCEPT is defined as follows: REGR_INTERCEPT = AVG(y) – REGR_SLOPE(y,x)AVG(x)where: x is independent_variable_expression and y is dependent_variable_expression.

The following query returns the intercept of the regression line for NbrSold and SalesPrice inthe range of 160000 to 280000 in the 358711030 area.SELECT CAST (REGR_INTERCEPT(NbrSold,SalesPrice) AS DECIMAL (5,1))FROM HomeSalesWHERE area = 358711030AND SalesPrice BETWEEN 160000 AND 280000;Here is the result:REGR_INTERCEPT(NbrSold,SalesPrice)----------------------------------249.9

Page 90: A Guide to Teradata Keywords

Returns the coefficient of determination for all non-null data pairs of the dependent and independent variable arguments.A dependent variable is something that is measured in response to a treatment. The expression cannot contain any ordered analytical or aggregate functions. And independent_variable_expression is the independent variable for the regression.An independent variable is a treatment: something that is varied under your control to test the behavior of another variable. The expression cannot contain any ordered analytical or aggregate functions.The equation for computing REGR_R2 is defined as follows:REGR_R2 = POWER(COUNT(xy)• SUM(xy)– SUM(x) • SUM(y) , 2)/ ((COUNT(xy)• SUM(x**2)– SUM(x) • SUM(x)) •(COUNT(xy)• SUM(y**2)– SUM(y) • SUM(y))) where: x is independent_variable_expression and y is dependent_variable_expression.Division by zero results in NULL rather than an error.The following SELECT statement returns the coefficient of determination for height and weight where neither height nor weight is null.

SELECT CAST(REGR_R2(weight,height) AS DECIMAL(4,2))FROM regrtbl;REGR_R2(weight,height)----------------------.58

This function returns the slope of the univariate linear regression line through all non-null data pairs of the dependent and independent variable arguments.The slope of the best fit linear regression is a measure of the rate of change of the regression of one independent variable on the dependent variable.The plot of the linear regression on the variables is used to predict the behavior of the dependent variable from the change in the independent variable. Note that this computation assumes a linear relationship between the variables.There can be a strong nonlinear relationship between independent and dependent variables, and the computation of the simple linear regression between such variable pairs does not reflect such a relationship.The equation for computing REGR_SLOPE is defined as follows:REGR_SLOPE = (COUNT(x)SUM(x*y))–(SUM(x)SUM(y)) / (COUNT(x)SUM(x**2))–(SUM(x)**2) where: x is independent_variable_expression and y is dependent_variable_expression.

The following query returns the slope of the regression line for NbrSold and SalesPrice in the range of 160000 to 280000 in the 358711030 area.SELECT CAST (REGR_SLOPE(NbrSold,SalesPrice) AS FLOAT)FROM HomeSalesWHERE area = 358711030AND SalesPrice BETWEEN 160000 AND 280000;Here is the result:REGR_SLOPE(NbrSold,SalesPrice)------------------------------

Returns the sum of the squares of the independent_variable_expression for all non-null data pairs of the dependent and independent variable arguments. Can refer the above other analytical functions.REGR_SXX = (SUM(x**2)) - (SUM(x). (SUM(x)/n)) Where x is independent_variable_expression and n is COUNT(x)

Returns the sum of the products of the independent_variable_expression and the dependent_variable_expression for all non-null data pairs of the dependent and independent variable arguments.REGR_SXY = (SUM(x*y)) - (SUM(x). (SUM(y)/n)) where n is count(x,y)Returns the sum of the squares of the dependent_variable_expression for all non-null data pairs of the dependent and independent variable arguments.REGR_SYY= (SUM(y*2))- (SUM(y). (SUM(y)/n)) where y is dependent variable. n is count(y)

The following SELECT statement returns the sum of squares for weight where neither height nor weight is null.SELECT REGR_SYY(weight,height)FROM regrtbl;Regr_Syy(weight,height)-----------------------10426

Page 91: A Guide to Teradata Keywords

In Fetching rows in a cursor, RELATIVE n is used to fetch the nth row of the response set:• forward by the value of n, if n is a positive number,• backward by the value of n, if n is a negative number, relative to the current cursor position. n can be a host_variable_name or an integer_constant.The data types for the host variable can be any 8-byte numeric data type with zero scale. An integer_constant can be up to 31 digits.

Also, Teradata Does Not Support The ANSI SQL STATE and RELATIVE Comparison Options.Teradata Database does not support the STATE and RELATIVE comparisons because they do not mesh well with the Teradata parallel architecture. The issue that makes these options problematic is that there is a strong relationship between the concepts of equality and the hash values that Teradata generates for many of its join strategies. Two values that are equal in the relational use of the concept must generate hash values that are also equal.The MAP ordering approach enables Teradata to generate internally an appropriate hash value for the UDT, enabling all Optimizer join strategies to function properly.RELEASE LOCK statement releases host utility locks on databases or tables. It is an archive option.It Automatically releases utility locks when the operation completes successfully.The ARC utility places locks on database objects while it performs archive and restore activities. These locks are referred to as host utility-level locks. The ARC utility does not automatically release these locks upon successful completion of an ARC command. In fact, these locks remain intact even when an AMP goes down and comes back online. You must submit the RELEASE LOCK statement to remove the locks. Not everyone can issue the release lock statement. You must have either the ARCHIVE or the RESTORE privilege on the locked object or be the owner of the locked object. You may submit the RELEASE LOCK option at the same time you issue ARCHIVE, ROLLBACK, ROLLFORWARD, RESTORE, and BUILD commands. This accomplishes the same purpose as issuing the RELEASE LOCK statement.REPLACE VIEW redefines an existing view or, if the specified view does not exist, creates a new view with the specified name.CREATE VIEW v1 ASSELECT cu (CHARACTER(6), CHARACTER SET UNICODE)FROM table_1;

Also, A procedure, Function , Macro or an Authorization bject can be replaced.RESTART INDEX ANALYSIS- Restarts a previously halted index analysis started by an INITIATE INDEX ANALYSIS request that specified a checkpoint.RESTART INDEX ANALYSISFROM MyWorkloadIN MyQCDAS table1_Index;Use the RESTORE statement to replace tables or databases from an archive. The RESTORE statement allows you to replace database objects from an archive tape to the same system or to another system. Teradata Database features the four types of RESTORE or RECOVER operations described in the following : ABORT,DATA TABLES,DICTIONARY TABLES,EXCLUDE TABLES,JOURNAL TABLESRESTORE is a Privilege applies to all tables in the specified database.RS represents RESTORE privilage.The Archive/Recovery (ARC) utility allows backup and restore of data from clustered AMPs. A CLUSTER option is available on both the DUMP and the RESTORE commands.It is a non reserved keyword. Usage is discouraged as it may result in possible confusion.It is a logical operator extracts one or more tuples from the projections.While creating the profile, We use many password attributes. One is RESTRICTWORDS = c.This specifies whether certain words are restricted from use within a password string.If the value of c is 'Y' or 'y' , then Any words listed in DBC.PasswordRestrictions cannot be used in password strings.If the value of c is 'X' or 'x' , then No words are restricted from password strings.DYNAMIC RESULT SETS clause is used in the CREATE PROCEDURE or REPLACE PROCEDURE request.Dynamic result sets are supported only for external procedures written in C or C++ using theCLIv2 API. Java external procedures do not support dynamic result sets.A procedure can return from 0 to 15, inclusive, result sets.To create a result set to return to the caller or client the external procedure must:• Submit the request to the database using the same session, which is the default connection, as the session for the external procedure.• Submit a single statement containing a SELECT request.• Specify a SPReturnResult of 1, 2, 3, or 4 in the Options parcel.• Specify keep response or positioning.

Page 92: A Guide to Teradata Keywords

.REVALIDATE PRIMARY INDEX regenerates table headers for a PPI in the specified table or noncompressed join index and optionally verifies the partitioning of its rows. If partitioning errors are detected for a table (but not a join index), they are then corrected.We cannot modify or revalidate a primary index in the same ALTER TABLE statement you perform to modify basic table parameters. The primary index for the table or noncompressed join index must be a partitioned primary index.Suppose any of the following events make you think that incorrect partitioning of the orders table has occurred:• You suspect that row partitioning might not be correct after a restore.• You copy the table to a system with different hardware or operating system.• Some sort of system malfunction has occurred.You can validate the partitioning of orders table rows using either of the following ALTER TABLE requests, with the first request deleting any problematic rows and the second moving them into a new table:ALTER TABLE ordersREVALIDATE PRIMARY INDEX WITH DELETE;ALTER TABLE ordersREVALIDATE PRIMARY INDEX WITH INSERT INTO old_orders;Use the REVOKE statement to take away (from a user, database, role, or PUBLIC) an explicit privilege on a database, user, role, profile, table, view, macro, stored procedure, or userdefined function.To revoke a privilege, you must either:• Be an owner of the object.• Have the same explicit privilege you are revoking. Or have WITH GRANT OPTION if you are not revoking from yourself. You can use the Teradata Administrator to revoke privileges.REVOKE ALL PRIVILEGES ON d2 FROM PUBLIC;ROLE returns the session current role.You can identify the session current role with the following statement:SELECT ROLE;The system responds with something like the following:Role------------------------------EXTERNALThe ROLLBACK command replaces a data row by its before change image from the end of the journal, to a checkpoint or to the beginning of the journal.The ROLLFORWARD command replaces a data row by its after-change image, starting from the beginning of the journal and proceeding to either a checkpoint or the end of the journal.

The ROLLUP function is used when aggregation is desired across all levels of a hierarchy within a single dimension.

salaries by department for department numbers less than 402.

SELECT department_number,SUM(salary_amount)FROM employeeWHERE department_number < 402GROUP BY ROLLUP (department_number)ORDER BY 1;

department_number Sum(salary_amount) ? 591925.00 100 100000.00 201 73450.00 301 116400.00 302 56500.00 401 245575.00

There is an additional row with a '?' department number. This row represents the rollup of all department salaries which is the top (and only) level of the hierarchy in this case. The '?' does not represent a null, rather it represents the 'total' of all department salaries.ROUTINE_CATALOG is a non-reserved SQL-2003 Status keyword. It’s a ANSI SQL-2003 nonreserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 nonreserved word cannot be used as an identifier. If the Teradata Database Status is Non-Reserved or empty, the word is permitted as an identifier, but discouraged because of the possible confusion that may result.

Page 93: A Guide to Teradata Keywords

OLD [ROW] and NEW [ROW] are used in the Referencing clause of triggers.

OLD [ROW] : An introduction to a correlation name for the current row before it is modified. The current row is called a transition row. The ROW keyword is optional. We can specify OLD or OLD ROW only in ROW triggers. OLD and OLD ROW are valid only for the DELETE and UPDATE triggering events.

NEW [ROW] : An introduction to a correlation name for the current row after it is modified. The current row is called a transition row. The ROW keyword is optional. We can specify NEW or NEW ROW only in ROW triggers. NEW and NEW ROW are valid only for the INSERT and UPDATE triggering events.

ROW_COUNT is a field in the diagnostics Area. It describes the number of rows affected by executing a searched DELETE request, INSERT request, a MERGE request, a searched UPDATE request, or as a direct result of executing the previous SQL statement.Datatype is INTEGER. Default value is zero. READ_ONLY attribute.

The following example illustrates the usage of the statement information item field ROW_COUNT in a GET DIAGNOSTICS statement. During the execution of the procedure, the GET DIAGNOSTICS statement sets the rowcount parameter to zero. The CALL statement returns OParam = 0 and rowcount = 0.CREATE PROCEDURE getdiag1 (OUT OParam INTEGER,INOUT rowcount INTEGER)BEGINSELECT c1 INTO OParam FROM tab1; -- Returns warning NODATA FOUNDGET DIAGNOSTICS rowcount = ROW_COUNT;IF (rowcount = 0) THENSET OParam = 0;END IF;END;BTEQ> CREATE SET TABLE tab1 (c1 INTEGER);BTEQ> CALL getdiag1(OParam, NULL);The ROW_NUMBER function returns the sequential row number of a group starting with the number one.

SELECT storeid, prodid, sales, RANK() OVER (PARTITION BY storeid ORDER BY sales DESC) AS rank_sales FROM salestbl QUALIFY rank_sales <= 3;

'PARTITION BY' is optional. If there is no PARTITION BY clause, then the entire result set, specified by the ORDER BY clause constitutes a single group, or partition.

When a row is inserted into a table, Teradata Database stores the 32-bit row hash value of the primary index with it. Because row hash values are not necessarily unique, Teradata Database also generates a unique 32-bit numeric value (called the Uniqueness Value) that it appends to the row hash value, forming a unique RowID. This RowID makes each row in a table uniquely identifiable and ensures that hash collisions do not occur. If a table is defined with a partitioned primary index (PPI), the RowID also includes the combined partition number to which the row is assigned, where the combined partition number is derived from the partition numbers for each level of the PPI.

The ROWID keyword can only be used in a join index definition.

CREATE JOIN INDEX OrdJIdx1 ASSELECT (o_orderdate), (o_orderkey, orders.ROWID)FROM ordersORDER BY o_orderdatePRIMARY INDEX (o_orderdate);ON COMMIT DELETE ROWSON COMMIT PRESERVE ROWS

Both the above statements explain the action to be taken with the contents of a global temporary table when a transaction ends.DELETE ROWS clears the temporary table of all rows.PRESERVE ROWS retains the rows in the table after the transaction is committed.We cannot change the ON COMMIT properties of a global temporary tableif any materialized instance of the table exists anywhere in the Teradata Database.

Page 94: A Guide to Teradata Keywords

RU is the synonym for READ UNCOMITTED.READ UNCOMITTED is used if we need fast response time over data accuracy. Response time is quick because queries can retrieve data without taking locks.Use READ UNCOMMITTED if you require read-only operations and it is not important that the data has not yet been committed. ("Read-only" operations do not include any SELECT statements specified within DELETE, INSERT, or UPDATE). READ UNCOMMITTED is especially useful for:• Looking up data that is generally static in nature, for example, codes or references in a look-up table.• Gathering information for statistical processing on a large amount of data when you only want to obtain averages or estimates for a general impression.The follwing is the example for Setting the Default Session Isolation Level To READ UNCOMMITTEDSET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL RU;SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

SAMPLE clause comes with a keyword ‘RANDOMIZED ALLOCATION’ that specifies whether retrieved rows are sampled randomly across the amps or proportionate to the number of qualified rows per AMP. Proportional allocation is default.

Multiple sample sets may be generated in a single query if desired. To identify the specific set, a tag called the SAMPLEID is made available for association with each set. The SAMPLEID may be selected, used for ordering, or used as a column in a new table.SELECT department_number ,sampleid FROM departmentSAMPLE .25, .25, .50ORDER BY sampleid;

This is a keyword used in Query and Workload Analysis Statements like DIAGNOSTIC DUMP SAMPLES,DIAGNOSTICS HELP SAMPLES etc.DAIGNOSTIC DUMP SAMPLES extracts random AMP samples from a target system and writes it to SystemFE.Opt_RAS_Table on that system.Eg: Dump the random AMP statistical samples on the current system for the payroll table in the employee database to SystemFE.Opt_RAS_Table. For this example, you are using the name production_1 for the current system.DIAGNOSTIC DUMP SAMPLES Production_1 TABLE Employee.Payroll;

SCALE is SQL 2003 Nonreserved keyword. So, It is better to avoid the usage of SCALE as variable name to avoid unneccessary confusion.It is not anymore as a keyword in the teradata database statusCREATE USER is functionally equivalent to the ANSI SQL:2003 CREATE SCHEMA statement.DROP DATABASE is functionally similar to the ANSI SQL:2003 statement DROP SCHEMA.DROP USER is functionally similar to the ANSI SQL:2003 statement DROP SCHEMA.SCHEMA_NAME is SQL 2003 Nonreserved keyword. So, It is better to avoid the usage of SCALE as variable name to avoid unneccessary confusion.It is not anymore as a keyword in the teradata database status

The form of fetching is available which allows the cursor to position itself back to the first row in the sequence. This is useful if a series of rows must be processed multiple times, and it is undesirable to re-execute the cursor a second time. The coding used to accomplish this is the following:

FETCH FIRST FROM EmpCur INTO emp, dept;

This will reposition the cursor back to first row, will retrieve it, and will allow for the fetch sequence to take place again. This type of fetch is only possible if the cursor has been declared as a scrollable cursor using the keyword SCROLL. The coding used to accomplish this is the following:

DECLARE EmpCur SCROLL CURSOR FOR SELECT employee_number , department_number FROM employee WHERE employee_number < 1005 ORDER BY 1;It is a parameter to be set in the INITIATE INDEX ANALYSIS statement.This specifies the maximum size of the search space to be allowed for evaluating index candidates. The higher the number we specify, the more candidate indexes the system canevaluate. But larger the number we specify, the longer the evaluation time. To shorten our evaluation times, change the specification for SearchSpace to a lower number.The default is 256.The valid range is 128 to 512.

Page 95: A Guide to Teradata Keywords

Allows one or more expressions to be compared with one or more constants or with one or more values returned by a subquery.

It is used in DAY/TIME INTERVAL Datatype.

SECOND is used in the following cases.1) INTERVAL SECOND(n,m) (9999.999999 seconds)2)INTERVAL DAY(n) TO SECOND(n,m)3)INTERVAL HOUR(n) TO SECOND(n,m)4)INTERVAL MINUTE(n) TO SECOND(n,m)

BEGIN DELARE SECTION is used to identify the start of an embedded SQL declare section for an application written in C.The BEGIN DECLARE SECTION and the END DECLARE SECTION statements are mandatory for applications written in C.Preprocessor2 issues a warning if it finds either statement in a COBOL or PL/I application. All host variables must be defined within the declare section.An external routine with an EXTERNAL SECURITY clause DEFINER authorization always uses the OS user authorization that is associated with the creator of the authorization object.An external routine with an EXTERNAL SECURITY clause INVOKER authorization uses the OS user authorization that is associated with the database user who invokes it.Both routines require external authorization.Sets the internal seed for the random number generator (the function random). Allowed values are floating-point numbers between 0 and 1, which are then multiplied by 231-1. The seed can also be set by invoking the function setseed:SELECT setseed(value);SESSION is a parameter which specifies that the command takes effect for the current session. (This is the default if neither SESSION nor LOCAL appears.)to set the frequency at which processorresource usage data is updated in the TeradataDatabase.to set the frequency at which session-levelperformance data is updated in the TeradataDatabase.SHOW— show the value of a run-time parameter. SHOW will display the current setting of run-time parameters. These variables can be set using the SET statement, by editing the postgresql.conf configuration file, through the PGOPTIONS environmental variable (when using libpq or a libpq-based application), or through command-line flags when starting the postgres server.Syntax . SHOW name ,SHOW ALLSIN is a function which performs the trigonometric or inverse trigonometric function of an argument. Eg. SIN(arg) the result value will the the sine of arg in radians in the range -1 to 1, inclusive.It is a Hyperbolic Functions which performs the hyperbolic or inverse hyperbolic function of an argument. Eg. SINH(arg) gives the Hyperbo lic sine of arg as the resultSkewness is the third moment of a distribution. It is a measure of the asymmetry of thedistribution about its mean compared with the normal, Gaussian, distribution.The normal distribution has a skewness of 0.Positive skewness indicates a distribution having an asymmetric tail extending toward morepositive values, while negative skewness indicates an asymmetric tail extending toward morenegative values.Represents a signed binary integer value in the range -32768 to 32767.SMALLINT values are stored as two bytes, with the least significant byte first.In the following table definition, column DeptNo is a SMALLINT data type:CREATE TABLE Departments(DeptNo SMALLINT FORMAT '999' BETWEEN 100 AND 900,ManagerName CHAR(26),ManagerID CHAR(9));

SOUNDEX is a function that translates the sound of a spoken word into a code. This code can then be compared against other SOUNDEX codes to find words which sound alike. It is usually used to locate the names of people, either first or last names, which sound alike but which are spelled differently.

SOUNDEX codes begin with the first letter of the name followed by a three-digit code. Zeroes are added if the name doesn't have enough letters.

SOUNDEX RestrictionsOnly the 26 Latin character set is permitted, either upper or lowercase. No spaces, quotes, numbers or other special characters are permitted.

Page 96: A Guide to Teradata Keywords

STDDEV_POP returns the population standard deviation for the non-null data points in value_expression.STDDEV_SAMP Returns the sample standard deviation for the non-null data points in value_expression.

Function returns the cumulative or moving sum of an expression based on how the aggregation group is specified. Hyperbolic tangent of arg. TANH(0)=0.00000000000000E 000

SPL option is an compile-time attribute of a stored procedure. SPL means that the SQL source text of the stored procedure should be stored in thedictionary.

SPOOL = n BYTES; It is a parameter while creating the database. It describes the number of bytes to be allowed for spool and volatile temporary files. The default is the largest value that is not greater then the owner spool space and that is a multiple of the number of AMPs on the system. n must not exceed the owner spool space. The number of bytes can be entered as an integer, decimal, or floating point value.The SQL Descriptor Area (SQLDA) is a data structure that contains a list of individual item descriptors for each of the values to be produced by a dynamically executed single row SELECT.The application needs to have information such as the number of columns that will be in a retrieved row, their data types, size, and precision so it can know how to process values to be retrieved dynamically at runtime.

SQLDATA is a field of SQLDA.It indicates to the preprocessor either:• The address of the input host variable from which the valueis to be taken.• The output host variable where the result value is to be stored.

It is used in condition handling statements. SQLEXCEPTION indicates a generic exception condition.

DECLARE CONTINUE HANDLERFOR SQLEXCEPTIONBEGINSET p1='FAILED TO INSERT ROW';END;SQL return codes provide information about the status of a completed executable SQL DML statement.ANSI SQL defines two status variables for receiving return codes:• SQLSTATE• SQLCODE

For Successful completion, SQLSTATE value is '00000'For Warning,SQLSTATE value is corresponding to the warning code.For No data found orany other Exception,SQLSTATE valueis corresponding to the error code.SQLTEXT[=n] is one of the options for determining various boundary conditions for query logging.SQLTEXT[=n] Sets the maximum number of SQL text characters to log in the default row.The default value is 200.The value specified cannot be negative. If you specify 0, then no characters are logged.If we specify SQLTEXT without specifying a numeric value to limit the number of characters logged, then the entire SQL statement is logged up to a maximum of 10 000 characters. If the statement exceeds 10,000 characters, then the excessive characters are not logged.We should not specify both ALL and SQLTEXT. If we specify ALL, then we should set the value for SQLTEXT to 0; otherwise, the SQL text is redundantly logged in both the DBQLogTbl and DBQLSqlTbl tables.It is used in condition handling statements. SQLWARNING indicates a generic completion condition.

DECLARE EXIT HANDLERFOR SQLWARNINGINSERT INTO Proc_Error_Table (:SQLSTATE,CURRENT_TIMESTAMP, 'spSample11', 'Generic handlerperformed');Function returns the square root of the number.Select SQRT(4)-2

Extracts a substring from a named string based on position.

SELECT SUBSTR (<column name> FROM <starting position> FOR <ending position>)

TBL_CS is a reserved teradata databse status keyword. Teradata Database reserved word that cannot be used as an identifier to name host variables, correlations, local variables in stored procedures, objects, such as databases, tables, columns, or stored procedures, or parameters, such as macro or stored procedure parameters, because Teradata Database already uses the word and might misinterpret it.

Page 97: A Guide to Teradata Keywords

TEMPORARY is a previlege. Allows temporary tables to be created while using the specified database.

TD_GENERAL is a non-reserved teradata databse status keyword. Teradata Database nonreserved keyword that is permitted as an identifier but discouraged because of possible confusion that may result.TD_INTERNAL is a non-reserved teradata databse status keyword. Teradata Database nonreserved keyword that is permitted as an identifier but discouraged because of possible confusion that may result.

This is a keyword to mention the limit option in the BEGIN QUERY LOGGING statement. Sets a threshold time in seconds that determines whether a query is to be logged fully or just counted.If a query completes earlier than or equal to the threshold value, then it is only logged as a count in DBQLSummaryTbl. The Threshold row in DBQLSummaryTbl is identified by a HighHist column value of 0.If a query completes later than the threshold value, then a full entry is logged for it in DBQLogTbl with values for all columns of the row.If you specify THRESHOLD without also specifying a value for n, then the value 5 seconds is assigned by default.If you specify THRESHOLD, then you can specify a threshold limit.If you do not specify a threshold limit, then all queries are logged fully.The maximum value for n is 32,767 seconds (roughly 9 hours).

SELECT TOP 5 WITH TIESdepartment_number, budget_amountFROM department ORDER BY 2 DESC;

department_number budget_amount----------------- ------------- 401 982300.00 403 932000.00 301 465600.00 100 400000.00 501 308000.00 402 308000.00

Things to notice:

Even though TOP 5 is specified, six rows are returned. Because there is a tie for the fifth position, both rows are returned. This only occurs when WITH TIES is specified. WITH TIES returns multiple tied rows when there is a tie for the 'last' position. It will return all rows containing the 'tied' value, but it will only count it as one row. Tied rows which are not in the last position, are each counted separately toward the N total. The same result could have been retuned by specifying TOP 6 without the WITH TIES option.

TIME is also a Teradata data type. In addition, a keyword TIME is also selectable ( as in SELECT TIME;) and returns an integer representing the time of day in format HHMMSS. This is not a data type and has no real clock intelligence for purposes of calculations. The TIME data type has some similarities to the DATE data type. It is a single column which carries three different fields of information. It also has an intelligent clock in its implementation, just as DATE has calendar intelligence. Additionally, the TIME data type supports precision in seconds up to six places. Time, like date, may be represented as a literal. As before, the character string must conform properly to the TIME data type, and the exact degree of precision will be determined by the parser as it scans the literal. For example, TIME ‘11:37:58.213000’ will be determined to be a TIME(6) data type. TIME data types require six total bytes of storage, regardless of the specified precision. CREATE TABLE tbla (tbltime TIME); INSERT INTO tbla (CURRENT_TIME); SELECT * FROM tbla; tbltime11:33:13.4800001. The system evaluates the top n operator after all other clauses in the SELECT request have been evaluated. 2. It gives the ranked result only when you specify order by clause. So, If you don’t specify order by, results can be any n rows.

TPA- Trusted Parallel ApplicationA TPA is an application that Teradata has certified to run safely on the Teradata Database. TheTeradata Database software itself is a TPA.

Page 98: A Guide to Teradata Keywords

This will specify how to trim the specified trim character or byte from string_expression.TRAILING Trim only trailing characters or bytes.Assume column a is BYTE(4) and column b is VARBYTE(10).If these columns contained the following values:a b------------ ---------78790000 4344000068690000 320012550000 332200then this function:SELECT TRIM (TRAILING FROM a) || TRIM (TRAILING FROM b) FROM ...returns:7879434468693212553322

TRANSACTION_ACTIVE is a field in the diagnostice area.This is a code indicating whether the transaction is currently active or not.Code Description0 The transaction is not currently active.1 The transaction is currently active.Datatype is Integer.Default is 0.The following example illustrates the usage of the statement information item field TRANSACTION_ACTIVE in a GET DIAGNOSTICS statement in Teradata session mode. When the procedure finishes executing, OParam has the value 0 because there is no transaction active when the GET DIAGNOSTICS statement is submitted and Stmt has the string 'INSERT'.If the du[pliacte row is allowed, then TRANSACTION_ACTIVE will be returned as 1.CREATE PROCEDURE getdiag3 (OUT OParam INTEGER)BEGINDECLARE CONTINUE HANDLER FOR SQLSTATE '23505'GET DIAGNOSTICS OParam = TRANSACTION_ACTIVE;INSERT INTO Tab1 VALUES(100);INSERT INTO Tab1 VALUES(100);END;BTEQ> CREATE SET TABLE tab1 (c1 INTEGER);BTEQ> CALL getdiag3(OParam);CREATE TRANSFORM/ REPLACE TRANSFORM creates a transform group to handle the import and export of UDT data from a client system to Teradata Database and from Teradata Database to a client system.TRANSLATE function converts a character string or character string expression from one server character set to another server character set.TRANSLATE('abc' USING UNICODE_TO_LATIN) ; Result is 'abc'; Type of the result is VARCHAR(3) CHARACTER SET LATIN

TRANSLATE_CHK determines if a TRANSLATE conversion can be performed without producing errors; returns an integer test result. Use TRANSLATE_CHK to filter untranslatable strings. we can choose to select translatable strings only, or untranslatable strings only, depending on how we form our SELECT statement.0 Represents The string can be translated without error.Other han 0 represents the position of the first character in the string causing a translation error. The value is a logical position for arguments of type LATIN, UNICODE, KANJISJIS, and GRAPHIC. The value is a physical position for arguments of type KANJI1.

Eg: TRANSLATE_CHK(‘abc’ USING UNICODE_TO_LATIN) ; Result is 0TRANSLATE_CHK(‘abc ’ USING UNICODE_TO_LATIN) ; Result is 4

Consider the following table definition:CREATE TABLE table_1(cunicode CHARACTER(64) CHARACTER SET UNICODE);To find all values in cunicode that can be translated to LATIN, use the following statement:SELECT cunicodeFROM table_1WHERE TRANSLATE_CHK(cunicode USING Unicode_TO_Latin) = 0;

Page 99: A Guide to Teradata Keywords

The trigger defines events that happen when some other event, called a triggering event, occurs. This database object is essentially a stored SQL statement associated with a table called a subject table.Triggers execute when any of the following modifies a specified column or columns in the subject table:• DELETE• INSERT• UPDATETypically, the stored SQL statements perform a DELETE, INSERT, or UPDATE on a table different from the subject table.

Use the TRIM function to suppress leading and/or trailing blanks in a CHAR column or leading and/or trailing binary zeroes in a BYTE or VARBYTE column. TRIM is most useful when performing string concatenations.

TRIM ([expression]) leading and trailing blanks/binary zeroesTRIM (BOTH FROM [expression]) leading and trailing blanks/binary zeroesTRIM (TRAILING FROM[expression]) trailing blanks/binary zeroesTRIM (LEADING FROM[expression]) leading blanks/binary zeroes

SELECT first_name ,last_name (TITLE 'last') FROM employee WHERE CHAR (TRIM (TRAILING FROM last_name)) = 4;CREATE TYPE creates a user-defined data type that is constructed directly from a predefined Teradata Database data type.

CREATE TYPE NameUdt AS (first_name VARCHAR(20),last_name VARCHAR(20));This represents upper case.If used with the concatenation (||) operator, UC must be enclosed in parentheses, and be placed immediately after the column name.SELECT (City_name (UC)) || ', ' || State, PopulationFROM WorldWHERE Country = 'USA'ORDER BY Population ;UDTCASTAS is a is a reserved teradata databse status keyword. Teradata Database reserved word that cannot be used as an identifier to name host variables, correlations, local variables in stored procedures, objects, such as databases, tables, columns, or stored procedures, or parameters, such as macro or stored procedure parameters, because Teradata Database already uses the word and might misinterpret it.It is a Priivilege that can only be granted on the SYSUDTLIB database.Privilege applies to all UDTs, UDMs, and UDFs contained within the SYSUDTLIB database. Effectively grants UDTUSAGE on all UDTs contained within SYSUDTLIB as well as UDTTYPE on the SYSUDTLIB database. Privilege applies to the specified UDT object.It is a Priivilege that can only be granted on the SYSUDTLIB database.Privilege applies to all UDTs, UDMs, and UDFs contained within the SYSUDTLIB database. Effectively grants UDTUSAGE on all UDTs contained within the SYSUDTLIB database. Privilege applies to the specified UDT object.UDTUSAGE. One can grant this privilege at both the database and object level. It is not an automatic privilege and a user must be granted this privilege or acquire it through a role. A user granted UDTUSAGE WITH GRANT option can grant it (optionally also with the WITH GRANT option) to others.The Unicode escape character is specified by the UESCAPE clause. The Unicode_esc_char a single character from the session character set to use as the Unicodeescape character in the character string literal.

The Sum Window Remaining function permits a computed aggregate based on the remaining rows in a defined window. Remaining rows are defined as relative to the current row. The remaining function is activated by the following two conditions:- use of the keywords UNBOUNDED FOLLOWING. (the entire partition following the current row.)- absence of the keywords UNBOUNDED PRECEDING.(the entire partition preceding the current row.)Show sales of all products in all stores in ascending sequence. Also show the sales sum of all products following the current row in the hierarchy.

SELECT storeid, prodid, sales, SUM(sales) OVER (ORDER BY sales DESCROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)FROM salestbl;

Page 100: A Guide to Teradata Keywords

READ UNCOMITTED is used if we need fast response time over data accuracy. Response time is quick because queries can retrieve data without taking locks.Use READ UNCOMMITTED if you require read-only operations and it is not important that the data has not yet been committed. ("Read-only" operations do not include any SELECT statements specified within DELETE, INSERT, or UPDATE). READ UNCOMMITTED is especially useful for:• Looking up data that is generally static in nature, for example, codes or references in a look-up table.• Gathering information for statistical processing on a large amount of data when you only want to obtain averages or estimates for a general impression.The follwing is the example for Setting the Default Session Isolation Level To READ UNCOMMITTEDSET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL RU;SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;UNICODE is one of the Internal Server Character Sets which Teradata Database uses to represent user data and data in the Data Dictionary within the system. Unicode is a 16-bit encoding of virtually all characters in all current languages in the world. Teradata Database UNICODE server character set supports Unicode 4.1 and is designed eventually to store all character data on the server. UNICODE may be used to store all characters from all single-byte and multibyte client character sets. User data stored as UNICODE can be shared among heterogeneous clients.

UNION and UNION ALL are the set operators which combine two or more SELECT results tables into a single result.Each query connected by UNION is performed to produce a result consisting of a set of rows. The union must include the same number of columns from each table in each SELECT statement (more formally, they must be of the same degree), and the data types of these columns should be compatible. All the result sets are then combined into a single result set that has the data type of the columns specified in the first SELECT statement in the union.If the ALL option is used, duplicate rows are retained for the applicable result set.SELECT DeptNo, NameFROM EmployeeWHERE DeptNo = 500UNIONSELECT DeptNo, NameFROM EmployeeWHERE DeptNo = 600 ;A UNIQUE column definition requires that data cannot be NULL. Queries are flagged as nonentry- level ANSI when the SQL flagger is enabled if any listed column is not also defined as NOT NULL. Teradata Database instantiates UNIQUE as a unique primary or secondary index.CREATE TABLE InfoTable(InfoKey VARCHAR(10) NOT NULL,InfoData VARCHAR(16384) )UNIQUE PRIMARY INDEX ( InfoKey );It is used as an optional condition to use with NO CASE.UNKNOWN evaluates to TRUE if a conditional_expression evaluates to UNKNOWN and all prior conditions in the list evaluate to FALSE.UNNEST is a reserved SQL-2003 Status keyword. It’s a ANSI SQL-2003 reserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 reserved word cannot be used as an identifier. If the Teradata Database Status is Nonreserved or empty, the word is permitted as an identifier but discouraged because of possible confusion that may result.UNTIL is a keyword introducing a conditional expression to qualify the statements in the loop. UNTIL is also a reserved teradata database keyword and hence cannot be used as an indentifier. UPD is short for Update row. It is a reserved teradata databas keyword and hence cannot be used as an indentifier. It is used to modify column values in existing rows of a table.

To modify data in one or more rows of a table, use the UPDATE statement. In the UPDATE statement, you specify the column name of the data to be modified along with the new value.You can also use a WHERE clause to qualify the rows to change.Attributes specified in the CREATE TABLE statement affect an update operation in the following ways:• When an update supplies a value that violates some defined constraint on a column or columns, the update operation is rejected and an error message is returned.• When an update supplies the value NULL and a NULL is allowed, any existing data is removed from the column.• If the result of an UPDATE will violate uniqueness constraints or create a duplicate row in a table which does not allow duplicate rows, an error message is returned.UPDATE table_2SET col_1=1WHERE table_1.col_1=table_2.col_2;

Page 101: A Guide to Teradata Keywords

UPPER or LOWER operators for case-blind comparisons.The UPPER function converts a string to uppercase. Use the UPPER string function on both strings being compared to ensure a case-blind comparison regardless of the session transaction mode. UPPER does not convert multibyte characters to uppercase in the KANJI1 server character set.

SELECT emp_idFROM employeeWHERE UPPER(emp_id) = UPPER(emp_ssn);

UPPERCASE specifies that character data for a column is stored as uppercase.Also used to specify case for character data comparisons and collations.The Sex column is created using the UPPERCASE option.Gender CHAR UPPERCASEIf Sex data is entered in lowercase as shown in the following INSERT statement, then it is stored and returned in uppercase.INSERT INTO Employee (Name, EmpNo, Gender ...VALUES ('Smith', 10021, 'f', ...);

SELECT GnderFROM Employee;GenderFUSUAGE is a previlege. For procedural languages, allows the use of the specified language for the creation of functions in that language. This is the only type of privilege that is applicable to procedural languages. For schemas, allows access to objects contained in the specified schema (assuming that the objects’ own privilege requirements are also met). Essentially this allows the grantee to “look up” objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access. For sequences, this privilege allows the use of the currval and nextval functions.When Teradata Database is first installed on a server, only one user exists on the system, that is, User DBC.The database administrator typically manages this user and assigns space from User DBC to all other organizations. User DBC owns all other databases and users in the system.To protect the security of system tables within Teradata Database, the database administrator typically creates User System Administrator from User DBC. The usual procedure is to assign all database disk space that system tables do not require to User System Administrator.The database administrator then uses this user as a resource from which to allocate space to other databases and users of the system.USER_DEFINED_TYPE_CATALOG is a non-reserved SQL 2003 keyword. It’s a ANSI SQL-2003 nonreserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 nonreserved word cannot be used as an identifier. If the Teradata Database Status is Non-Reserved or empty, the word is permitted as an identifier, but discouraged because of the possible confusion that may result.USER_DEFINED_TYPE_CODE is a non-reserved SQL 2003 keyword. It’s a ANSI SQL-2003 nonreserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 nonreserved word cannot be used as an identifier. If the Teradata Database Status is Non-Reserved or empty, the word is permitted as an identifier, but discouraged because of the possible confusion that may result.USER_DEFINED_TYPE_NAME is a non-reserved SQL 2003 keyword. It’s a ANSI SQL-2003 nonreserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 nonreserved word cannot be used as an identifier. If the Teradata Database Status is Non-Reserved or empty, the word is permitted as an identifier, but discouraged because of the possible confusion that may result.USER_DEFINED_TYPE_SCHEMA is a non-reserved SQL 2003 keyword. It’s a ANSI SQL-2003 nonreserved word. If the Teradata Database Status is Reserved or Future, an SQL-2003 nonreserved word cannot be used as an identifier. If the Teradata Database Status is Non-Reserved or empty, the word is permitted as an identifier, but discouraged because of the possible confusion that may result.New value of parameter. Values can be specified as string constants, identifiers, numbers, or comma-separated lists of these, as appropriate for the particular parameter. DEFAULT can be written to specify resetting the parameter to its default value (that is, whatever value it would have had if no SET had been executed in the current session).

We can insert a row using only the default values using DEFAULT VALUES keywords.For this feature to work successfully, one of the following statements must be true for each column of the table:

- the column has defined default values - the column has a default system value specified - the column permits nulls Eg: INSERT INTO test_tbl DEFAULT VALUES;

Also, It is used as the followingINSERT INTO DATETAB VALUES (DATE '2001-12-20');

Page 102: A Guide to Teradata Keywords

VAR_POP Returns the population variance for the data points in value_expression.VAR_POP DISTINCT/ALL ( value_expression ). Value expression denotes a numeric constant or column expression whose population variance is to be computed. The expression cannot contain any ordered analytical or aggregate functions.The equation for computing VAR_POP is as follows:VAR_POP= (COUNT(x)SUM(x**2)–(SUM(x)**2))/(COUNT(x)**2)VAR_SAMP Returns the sample variance for the data points in value_expression.VAR_SAMP DISTINCT/ALL ( value_expression ).Value expression denotes a numeric constant or column expression whose population variance is to be computed. The expression cannot contain any ordered analytical or aggregate functions.VAR_SAMP = COUNT(x)SUM(x**2)–(SUM(x)**2) / (COUNT(x))(COUNT(x) – 1)

Teradata supports two data types for holding binary data: BYTE. VARBYTE. BYTE is for fixed length binary strings. VARBYTE is for variable length binary strings. These data types are used for storing binary objects such as digital images, executable objects, flat files, etc.It is a Variable length Binary string Default: (1) Max: 64,000 bytesVARCHAR Represents a variable length character string of length 0 to n for Teradata Database internal character storage.The following statement creates a table that defines two VARCHAR columns: InfoKey and InfoData.CREATE TABLE InfoTable(InfoKey VARCHAR(10) NOT NULL,InfoData VARCHAR(16384) )UNIQUE PRIMARY INDEX ( InfoKey );The following statements insert character data of varying lengths into the InfoKey and InfoData columns:INSERT INTO InfoTable ('001_5_799', 'Data for keyVARGRAPHIC type to represent multibyte character data. The VARGRAPHIC(n) data type is equivalent to VARCHAR(n) CHARACTER SET GRAPHIC. For best practice, define all VARGRAPHIC(n) data as VARCHAR(n) CHARACTER SET GRAPHIC.The maximum value for n in a VARCHAR(n) CHARACTER SET GRAPHIC definition is 32000. There is no default length—omitting the length specification results in an error.Cannot decrease maxlength.VARGRAPHIC('92 abcΔ') '92 abcΔ'VARYING COULMNS is used while creating function.This represents that the number of output columns to be returned by the function is not known before it is invoked, so limit them to a maximum of maximum_output_columns columns. The upper limit is 2,048 columns. There is no default value.CREATE FUNCTION sales_retrieve(store_no INTEGER)RETURNS TABLE VARYING COLUMNS (256)LANGUAGE CNO SQLPARAMETER STYLE SQLEXTERNAL NAME '...';A view is a virtual table created by defining a SELECT statement on one or more base tables or other views. When a user references a view, the response returns the rows selected according to the CREATE VIEW viewname AS … SELECT FROM … definition.There are several good reasons to use views:• A simplified user perception of very large and complex tables• Security, by omitting to select the sensitive columns of the underlying data table• Well-defined, well-tested, high-performance access to data• Logical data independence, which minimizes the need to modify your applications if you restructure base tables• A column defined in a view can be derived and does not need to exist in the underlying base tables. For example, it is possible to display summed or averaged data in a column you name in the CREATE VIEW definition.Neither the definition nor the contents of a volatile table persist across a system restart. Wemust use CREATE TABLE with the VOLATILE keyword to create a new volatile table eachtime we start a session in which it is needed.Eg:Create volatile table VT3.WAIT is a embedded SQL statements that support multisession programming. Its purpose is to pause execution of the invoking program and waits for the completion of one or more asynchronous SQL statements. WAIT is a Teradata extension to the ANSI SQL:2008 standard. eg. EXEC SQL WAIT ANY COMPLETION INTO :STMTNAMF, :CONNAMEF;

Page 103: A Guide to Teradata Keywords

WARNING is a compile time attribute of altering a procedure.If the attribute is WITH WARNING, then compilation warnings are returned during alteration of the stored procedure.And if the syntax element is WITH NO WARNING, then that compilation warnings are not returned during alteration of the stored procedure.ALTER PROCEDURE SP1 COMPILE WITH NO PRINT, NO WARNING, NO SPL; The WHENEVER statement specifies the action to be taken when an exception condition occurs.The actions which may occur are CONTINUE,GOTO host label,CALL function call.The WHENEVER statement must precede the SQL statement or statements for which the condition is to apply.• When it is used, the host label object must follow C rules for the C goto instruction. The target of the goto is formed following the same rules as a variable name with a colon appended.• When the CALL action is used, the function call object must be a valid C function call at every SQL statement to which the exception declaration applies. This translates to a regular C function call and follows the same rules.This is used to restrict the number of rows to be processed. Use of where clause will avoid full table scan.SELECT storeid, deptid, SUM(sales_dollars)FROM salesWHERE EXTRACT(year FROM sales_date) = 2007;It is a keyword introducing an iteration statement to repeat the execution of one or more statements within its defined scope.The associated condition is checked before each iteration (including the first) and if true, the statements are performed. Otherwise, the WHILE statement completes with no further iterations.WHILE (resultrownum> 0 )DOINSERT INTO Sales VALUES (:partnum, :qtysold, :storecode,:salesdate);CALL xmlsalesparser(:resultrownum,:partnum,:qtysold,:salesclob);END WHILE;

The WIDTH_BUCKET function assigns partition numbers to values associated with a column or expression, based on a specified range and based on the number of partitions desired.Like many OLAP and aggregate functions, WIDTH_BUCKET is used to extract statistical information from sample populations.The format of the function is as follows:WIDTH_BUCKET (column_expr,lower_bound, upper_bound ,partition_count)Where:Column expression is the column or expression containing the values. Partition count is the number of partitions specified for the range. Lower bound is the lowest value in the range to be partitioned. Upper bound is the highest value in the range to be partitioned.

WINDOW is the time frame between which the jobs are meant to run. It is a reserved SQL 2003 keyword and cannot be used as an Identifier in the Teradata Database. WITH DEFAULT - Assign the system default, spaces for char strings, zero for numeric data types and current date for date data type CREATE TABLE test_tbl (cold DEC(3,2) NOT NULL WITH DEFAULT ;

DECLARE cur1 CURSOR WITHOUT RETURN FOR – This indicates that the no result set is returned to the client or caller. The COMMIT [WORK] or ROLLBACK [WORK] statements close a transaction.When you perform a stored procedure in ANSI transaction mode, each DDL statementspecified in the procedure body must be followed by a COMMIT WORK statement.Otherwise, the system raises a runtime exception.WRITE is a lock type.WRITE Lock mode is placed in response to an INSERT, UPDATE, or DELETE request. Restricts access byother requests, except those that specify an access lock.The requester has exclusive rights to the locked resource except for readers not concerned with data consistency. Usage is ..LOCKING ROW FOR WRITESELECT y FROM tableA WHERE pi =1;UPDATE tableA SET y=0 WHERE pi =1;..YEAR is an reserved keyword which is used in many of the teradata SQL manipulation statements. Eg:SELECT c_nationkey, SUM(o_totalprice(FLOAT)) AS price,EXTRACT(YEAR FROM o_orderdate) AS o_yearFROM orders, customer

Page 104: A Guide to Teradata Keywords

The purpose of this function is to compare the data value in a column and when it contains a NULL, transform it, for the life of the SQL statement, to a zero.SELECT ZEROIFNULL(<COULMN NAME>), <Aggregate>(Zeroifnull(<Column name>) From <tablename> Group By 1;All TIME and TIMESTAMP data is associated with Time Zones either explicitly or implicitly.A Time Zone is represented by a signed displacement from Universal Coordinated Time(UTC). All TIME and TIMESTAMP values are stored internally as UTC.

Page 105: A Guide to Teradata Keywords

AACCESSACTIONAREARRAYASENSITIVEASYMMETRICATATTRIBUTEAVEBERNOULLIBETWEENBINARYBREADTHBUTBYTESCCALLCALLEDCALLERCASCADEDCASECATALOGCATALOG_NAMECDCHAINCHARCHARACTERCHARACTER_SET_CATALOGCHARACTER_SET_NAMECHARACTER_SET_SCHEMACHARACTERISTICSCHARACTERSCHARSCHECKCHECKEDCLASSCLASS_ORIGINCLIENTCLOSECOBOLCOLLATECOLLATION_CATALOGCOLLATION_NAMECOLLATION_SCHEMACOLLECTCOLUMN

Page 106: A Guide to Teradata Keywords

COLUMN_NAMECOLUMNSCOMMAND_FUNCTION_CODECOMMITTEDCOMPARABLECOMPARISONCONDITIONCONDITION_NUMBERCONNECTIONCONNECTION_NAMECONSTRAINT_CATALOGCONSTRAINT_NAMECONSTRAINT_SCHEMACONSTRAINTSCONTAINSCONVERTCONVERT_TABLE_HEADERCORRESPONDINGCOSTSCPPCROSSCSCTCUME_DISTCURRENTCURRENT_DEFAULT_TRANSFORM_GROUPCURRENT_PATHCURRENT_TRANSFORM_GROUP_FOR_TYPECURSOR_NAMECVDATADATABASEDATEDATETIME_INTERVAL_CODEDATETIME_INTERVAL_PRECISIONDAYDEALLOCATEDEBUGDECDEFAULTSDEFERRABLEDEFINEDDEGREEDELDEMOGRAPHICSDENIALSDENSE_RANKDEPTH

Page 107: A Guide to Teradata Keywords

DEREFDERIVEDDESCRIBEDESCRIPTORDETERMINISTICDIGITSDISCONNECTDOMAINDUALDUMPDYNAMICDYNAMIC_FUNCTIONDYNAMIC_FUNCTION_CODEEACHEBCDICECHOELEMENTELSEELSEIFENCRYPTENDEQEQUALSERRORERRORFILESERRORSERRORTABLESETEVERYEXCEPTIONEXCLEXCLUDINGEXISTINGEXPLAINEXTERNALFILTERFINALFIRSTFOLLOWINGFORFOREIGNFORTRANFREEFROMFULLFUNCTIONFUSIONG

Page 108: A Guide to Teradata Keywords

GEGENERALGENERATEDGETGLOBALGOGRANTGRANTEDGROUPGTHASHHAVINGHELPHIERARCHYHIGHHOLDHOSTHOURIFIMMEDIATEIMPLEMENTATIONINCLUDINGINCONSISTENTINDEXINDICATORINITINITIALLYINNERINOUTINPUTINSINSENSITIVEINSTANCEINSTEADINTINTERFACEINTERNALINTERSECTINTERSECTIONINTERVALINTOISISOLATIONITERATEJARJAVAJOINK

Page 109: A Guide to Teradata Keywords

KBYTEKBYTESKEEPKEYKEY_MEMBERKEY_TYPEKILOBYTESLANGUAGELARGELASTLATERALLELEADINGLEAVELEFTLENGTHLEVELLIKELIMITLOADINGLOCALTIMELOCALTIMESTAMPLOCATORLOCKINGLOGGINGLOGONLONGLOWLTMMATCHMATCHEDMAXIMUMMAXLOGONATTEMPTSMCHARACTERSMEDIUMMEMBERMESSAGE_LENGTHMESSAGE_OCTET_LENGTHMESSAGE_TEXTMETHODMINDEXMINIMUMMINUSMINUTEMLINREGMODEMODIFIED

Page 110: A Guide to Teradata Keywords

MODIFIESMODIFYMODULEMONITORMONRESOURCEMONSESSIONMONTHMOREMSUBSTRMUMPSNATIONALNCHARNCLOBNENESTINGNEWNEXTNONONENORMALIZENORMALIZEDNOTNULLSNUMBERNUMERICOAOBJECTOBJECTSOCTETSOFOFFOLDOLD_TABLEONONLINEONLYOPENOPTIONOPTIONSORORDERED_ANALYTICORDERINGORDINALITYOTHERSOUTOUTEROUTPUTOVERLAPS

Page 111: A Guide to Teradata Keywords

OVERLAYOVERLAYSOVERRIDEOVERRIDINGPADPARAMETERPARAMETER_MODEPARAMETER_NAMEPARAMETER_ORDINAL_POSITIONPARAMETER_SPECIFIC_CATALOGPARAMETER_SPECIFIC_NAMEPARAMETER_SPECIFIC_SCHEMAPARTIALPASCALPATHPERCENTPERCENTILE_CONTPERCENTILE_DISCPLIPOWERPRESERVEPRIMARYPRINTPRIORPRIVATEPRIVILEGESPROCEDUREPROTECTEDPROTECTIONPUBLICQUERYREADREADSRECALCREFREFERENCESREFERENCINGRENAMEREPEATREPEATABLEREPLACEMENTREPLCONTROLREPLICATIONREQUESTRESUMERETRETAINRETRIEVE

Page 112: A Guide to Teradata Keywords

RETURNRETURNED_CARDINALITYRETURNED_LENGTHRETURNED_OCTET_LENGTHRETURNED_SQLSTATERETURNSREUSERIGHTRIGHTSROUTINEROUTINE_NAMEROUTINE_SCHEMASAVEPOINTSCOPESCOPE_CATALOGSCOPE_NAMESCOPE_SCHEMASEARCHSELSELECTSELFSENSITIVESEQUENCESERIALIZABLESERVER_NAMESESSION_USERSETSETSSHARESIMILARSIMPLESIZESOURCESPACESPECCHARSPECIFICSPECIFIC_NAMESPECIFICTYPESQLSRSSSTARTSTARTUPSTATSTATESTATEMENTSTATICSTATISTICS

Page 113: A Guide to Teradata Keywords

STATSSTEPINFOSTRING_CSSTRUCTURESTYLESUBCLASS_ORIGINSUBLISTSUBMULTISETSUBSCRIBERSUBSTRINGSUMMARYSUMMARYONLYSUSPENDSYMMETRICSYSTEMSYSTEM_USERSYSTEMTESTTABLETABLE_NAMETABLESAMPLETANTARGETTERMINATETEXTTHANTHENTIMESTAMPTIMEZONE_HOURTIMEZONE_MINUTETITLETOTOP_LEVEL_COUNTTRACETRANSACTIONTRANSACTIONS_COMMITTEDTRANSACTIONS_ROLLED_BACKTRANSFORMSTRANSLATIONTREATTRIGGER_CATALOGTRIGGER_NAMETRIGGER_SCHEMAUDTCASTLPARENUNDEFINEDUNDERUNDOUNNAMEDUSE

Page 114: A Guide to Teradata Keywords

USINGWHENWITHIN