You are on page 1of 21

Teradata SQL Advanced

%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

Teradata and ANSI SQL


Objectives
After completing this module, you should be able to:
State the purpose and function of the session setting flags.
Recognize transaction mode differences for Teradata and ANSI.
Use available HELPfunctions.

Teradata SQL
To become an 'ANSI-standard' language, all vendors of SQL must become certified in ANSI (American National Standards Institute)
standards by the NIST (National Institute of Standards and Technology), a government certification agency.
There are three ANSI standards:
ANSI SQL - 89 (SQL 1)
ANSI SQL - 92 (SQL 2)
ANSI SQL - 99 (SQL 3)
There are three levels of compliance within each level:
ANSI SQL - 92 (SQL 2)
Entry level
Intermediate level
Full level
ANSI SQL - 99 (SQL 3)
Core
Enhanced
Teradata SQL is an ANSI compliant product. Teradata has its own extensions to the language, as do most vendors. Teradata SQL
is fully certified at the SQL92 Entry level, with some intermediate, some full and some SQL-99 Core features also implemented.
As the Teradata database evolves, each major release is expected to move Teradata SQL closer to conformance with full SQL2,
and including some features from the SQL3 standard.

Modes of Operation
Teradata SQL allows two different modes of session operation:
ANSI mode
Teradata (BTET) mode
Choice of mode affects:
Transaction protocol behavior
Case sensitivity defaults
Collating sequences
Data conversions
Display functions
Be aware that the same SQL statement might perform differently in each mode based on the above considerations. Regardless of the
mode you select, all syntax, whether or not ANSI compliant, is useable. No functionality is inhibited by choice of mode.

Transaction Modes
Transactions
A transaction is a unit of work performed against one or more tables of a database. It can consist of one or more data-changing
statements. By definition, a transaction must commit all of its associated changes or they must all be rolled back, meaning all
changes are returned to the original pre-transaction state. A transaction is an all-or-nothing proposition i.e., it either succeeds in its
entirety, or it is entirely rolled back. Knowing that transactions cannot partially complete provides assurance of data integrity.
ANSI Mode Transactions
.SET SESSION TRANSACTION ANSI

1 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

ANSI mode is also referred to as COMMIT mode. It automatically accumulates all requests until an explicit COMMIT is submitted. At that
point, all transactions are committed to the database and the transaction is ended. All transactions in ANSI mode are considered
explicit, that is, they require an explicit COMMITcommand to complete.
In the special case of DDL (Data Definition Language) statements, they must always be followed immediately by a COMMIT
statement. Macros containing DDL statements must contain a single DDL statement and be followed by an immediate COMMIT.
A rollback operation occurs when for some reason, the transaction is not able to complete. Rollback will automatically undo any
changes which have been applied during the transaction and release all locks which are being held by the transaction. Following a
rollback, there is no active transaction until another one is initiated. In ANSI mode, a rollback will occur in the following situations:
ROLLBACK work

Explicit rollback of an active transaction

Session Abort

Rollback of active transaction

SQL statement failure

Rollback of active transaction

SQL statement error

Rollback the current request only

ANSI mode makes a distinction between SQL statement 'error' and 'failure'.
SQL Failure - rolls back entire transaction when any of the following
A deadlock condition occurs requiring transaction rollback
A DDL statement has failed
An explicit ROLLBACK command is encountered
In this case:
The transaction terminates
SQL Error - rolls back individual SQL statement when
An SQL statement completes unsuccessfully, and
None of the above SQL 'failure' situations apply
In this case:
The transaction continues
If this was the first statement in the TXN, then the next statement starts the TXN
Any statement that follows a COMMITautomatically starts a new transaction. Locks are accumulated until a is used.
Teradata Mode Transactions
.SET SESSION TRANSACTION BTET
Teradata mode also is referred to as BTET mode, which stands for BEGINTRANSACTION/ENDTRANSACTION. In BTET mode, all
individual requests are treated as single implicit transactions. If you need to aggregate requests into a single transaction, use the
BEGIN and ENDTRANSACTION delimiters.
In Teradata mode, no distinction is made between 'error' and 'failure'. They are both considered 'failures'. A rollback will occur if
any of the following events occur:
ROLLBACK work

explicit rollback of active transaction

Session Abort

rollback of active transaction

SQL statement failure

rollback of active transaction

Locks are accumulated following a BT until an ET is issued.

Setting the ANSI Flagger


There is an additional BTET session setting called the ANSI SQL Flag. It may be set to flag any non-ANSI syntax. It returns warning messag
encountered but it does not inhibit execution of the command. It is an informational setting only.
The SQLFLAG may be set to any of the following three options:
ENTRY - Flags syntax which does not conform to ANSI entry level requirements
INTERMEDIATE - Flags syntax which does not conform to ANSI intermediate level requirements
NONE - Sqlflag is disabled
Teradata SQL is fully compliant at the ENTRY level and partially compliant at the INTERMEDIATE level.
The SQL flagger must be enabled prior to logging on to a session:
.
This setting flags all non-entry level ANSI syntax.

2 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

Example

(Note:alluserinputcommandsareinred.)
.SETSESSIONSQLFLAGENTRY;
.LOGONxyz,xyz;
seldate;
***Querycompleted.Onerowfound.Onecolumnreturned.
***Totalelapsedtimewas1second.
seldate;
$
***SQLWarning5836TokenisnotanentrylevelANSIIdentifierorKeyword.
seldate;
$
***SQLWarning5821BuiltinvaluesDATEandTIMEarenotANSI.
seldate;
$
***SQLWarning5804AFROMclauseisrequiredinANSIQuerySpecification.
(NotethatthreewarningsweregeneratedbecauseANSIdoes
notacceptlowercasecharacters,abbreviations,ortheDATEkeyword.
Inspiteofthewarnings,thedateisreturned.)
Date

97/01/20
(NotethatwemustlogoffinordertoresettheANSIFlagger.)
.LOGOFF;
.SETSESSIONSQLFLAGNONE;
.LOGONxyz,xyz;
seldate;
***Querycompleted.Onerowfound.Onecolumnreturned.
***Totalelapsedtimewas1second.
Date

97/01/20
(WithouttheSQLFlagger,nowarningsaregenerated)

Note: SQLFLAG may also be set when using Teradata front-end clients other than BTEQ, for example the Teradata Preprocessor (PP2) and

BTEQ .SHOW CONTROL


The .SHOWCONTROL command shows all BTEQ reporting specifications, import and export features, as well as session parameters,
including the SQL Flagger and the session Transaction mode: ANSI or BTET.
Example
[SET]FOLDLINE
[SET]FOOTING
[SET]FORMAT
[SET]FORMCHAR
[SET]HEADING
[SET]INDICDATA
[SET]NOTIFY
[SET]NULL
[SET]OMIT
[SET]PAGEBREAK
[SET]PAGELENGTH
[SET]QUIET
[SET]RECORDMODE
[SET]RETCANCEL
[SET]RETLIMIT
[SET]RETRY
[SET]RTITLE
[SET]SECURITY
[SET]SEPARATOR
[SET]SESSIONCHARSET

=OFFALL
=NULL
=OFF
=OFF
=NULL
=OFF
=OFF
=?
=OFFALL
=OFFALL
=55
=OFF
=OFF
=OFF
=NoLimit
=ON
=NULL
=NONE
=twoblanks
=ASCII

3 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

[SET]SESSIONSQLFLAG
=NONE
[SET]SESSIONTRANSACTION=BTET
[SET]SESSIONS
=1
[SET]SIDETITLES
=OFFforthenormalreport.
[SET]SKIPDOUBLE
=OFFALL
[SET]SKIPLINE
=OFFALL
[SET]SUPPRESS
=OFFALL
[SET]TDP
=l5442
[SET]TITLEDASHES
=ONforthenormalreport.
And,itisONforresultsofWITHclausenumber:123456789.
[SET]UNDERLINE
=OFFALL
[SET]WIDTH
=75

On-Line Syntax HELP


HELPis available for SQL syntax problems. It can either display a menu of all available SQL commands and functions or provide
syntax help on a particular SQL command.

Example
HELP'SQLSELECT';

/*Providessyntaxhelpforthe
SQLSELECTstatement*/
HELP'SQLALTERTABLE';/*Providessyntaxhelpfor
SQLALTERTABLEstatement*/
HELPalso provides syntax help for most Teradata client utilities as well as for SQL.

Example
HELP'utilitynameutilitycommand';
such as:
HELP'ARCHIVECommandname';
HELP'MULTILOADcommandname';

HELP Examples
HELP either generates a list of all available commands and functions, as in:
HELP'SQL';
***Querycompleted.35rowsfound.Onecolumnreturned.
***Totalelapsedtimewas1second.
OnLineHelp
(Partial Listing)

DBSSQLCOMMANDS:
ABORT
BEGINTRANSACTION
COMMIT
CREATEINDEX
CREATEUSER
DELETE
DROPDATABASE
DROPTABLE
ECHO
EXECUTE
GRANT

ALTERTABLE
CHECKPOINT
COMMENT
CREATEMACRO
CREATEVIEW
DELETEDATABASE
DROPINDEX
DROPVIEW
ENDLOGGING
EXPLAIN
GRANTLOGON

BEGINLOGGING
COLLECTSTATISTICS
CREATEDATABASE
CREATETABLE
DATABASE
DELETEUSER
DROPMACRO
DROP STATISTICS
END TRANSACTION
GIVE
HELP

or, delivers the full syntax for any specified command, such as:
HELP'SQLUPDATE';
***Querycompleted.10rowsfound.Onecolumnreturned.
***Totalelapsedtimewas1second.
OnLineHelp

UPD[ATE]tablename[[AS]aname][FROMtname[[AS]aname]]
[...,tname[[AS]aname]];

4 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

SETcolumnname=expr[...,columnname=expr]
[WHEREcondition]
[
];
[ALL
]

Lab
Try It!

For this set of lab questions you will need information from the Database Info document.
To start the online labs, click on the Telnet button in the lower left hand screen of the course. Two
windows will pop-up: a BTEQ Instruction Screen and your Telnet Window. Sometimes the BTEQ
Instructions get hidden behind the Telnet Window. You will need these instructions to log on to Teradata.
Click on the buttons to the left to see the answers.

Answers:
Lab A
Lab B
Lab C

A. Logon using your assigned userid and password. Do a HELPSESSION to see session information.
Notice that output exceeds screen width. To adjust output width, use the following setting
commands: .sidetitles;.foldline;
Do the HELPSESSIONagain. Notice the transaction semantic. Is it set to Teradata or to ANSI? Select
todays date. Note the output.
Change your transaction semantic to ANSI and enable the SQL Flagger to ENTRY level. You must
logoff (.LOGOFF) before you change session characteristics. Log back on again.
Do another HELPSESSION. Notice the new transaction semantic. Re-Select todays date. What
difference do you notice?
B. Create a simple, empty table entitled "quick" with a single integer column entitled "col1". After
creating the table, select todays date. What happens?
Because you are in commit mode, a COMMITcommand following a DDL statement is needed.
Issue the command. Attempt to select today's date again.
C. Reset your BTEQ session as follows:
Logoff the current id.
Turn off the ANSI flagger.
Return to BTET mode.
Logon.
Turn off sidetitles and foldline (.SIDETITLESOFF;.FOLDLINEOFF;).
Use the appropriate HELP command to view the contents of your userid database.
Do a HELPcommand on a table called "employee". (Hint: Its not in your database. Its in
Customer_Service.).
Do a HELPcommand on the indexes defined for the "employee" table.
Do a HELP command showing a menu of all possible SQL commands.
Do a HELP command getting syntax help for the SELECT command.
Do a HELP command getting syntax help for the ALTERTABLE command.

Using The COUNT Window Function


Objectives
After completing this module, you should be able to:
Produce reports requiring group-based counts using the COUNT Window function

COUNT Window Function


The COUNT Window function may be used to perform the following operations:
Count the number of rows in a defined group
Count the number of rows in all groups
A similar result can be produced using the WITH and WITHBY extensions to Teradata SQL. The WITHBYfunction is used to
produce sub-totals (and sub-counts) over the detail data for a group, as defined by the BY clause. Similarly, the WITHfunction is
used to provide grand totals (and grand counts) over the detail data for all rows.

5 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

The COUNT Window function is an ANSI-standard function, whereas the WITH and WITHBYfunctions are not. The COUNT Window
function also produces true relational output (uniform columns and rows) whereas WITH and WITHBY do not.

Using WITH BY For Group Counts


Using the WITHBYclause allows generation of sub-total counts based on groupings identified in the BY clause.
Consider the following example which demonstrates a report showing a count of employees by department.

Example
Produce a report showing the people in departments 401 and 403, their salaries, and how many people are in each department. Use
the WITHBY feature of Teradata SQL.
SELECTlast_name
ASName
,salary_amount
ASSalary
,department_number
ASDept
FROMemployee
WHEREDeptIN(401,403)
WITHCOUNT(Dept)(TITLE'Dept_Count')BYDept;
Name

Trader
Hoover
Johnson
Phillips
Machado
Brown
Rogers

Salary

37850.00
25525.00
36300.00
24500.00
32300.00
43100.00
46000.00
Dept_Count

Lombardo
Brown
Villegas
Hopkins
Charles
Ryan

31000.00
43700.00
49700.00
37900.00
39500.00
31200.00
Dept_Count

Dept

401
401
401
401
401
401
401

7
403
403
403
403
403
403

Note that the output from this query is a non-relational output. The sub-total rows are of a different format than the data rows.

Using The COUNT Window Function For Group Counts


Consider the same problem done using the COUNT Window function.

Example
Produce a report showing the people in departments 401 and 403, their salaries, and how many people are in each department. Use
the COUNT Window function.
SELECT

last_name
ASName
,salary_amount
ASSalary
,department_number
ASDept
,COUNT(Salary)OVER(PARTITIONBYDept
ROWSBETWEENUNBOUNDEDPRECEDINGANDUNBOUNDED
FOLLOWING)
ASDept_Count
FROMemployee
WHEREDeptIN(401,403)
;
Name

Trader
Johnson
Phillips
Rogers
Machado
Brown
Hoover
Charles
Brown
Hopkins
Ryan

Salary

37850.00
36300.00
24500.00
46000.00
32300.00
43100.00
25525.00
39500.00
43700.00
37900.00
31200.00

Dept

401
401
401
401
401
401
401
403
403
403
403

Dept_Count

7
7
7
7
7
7
7
6
6
6
6

6 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

Lombardo
Villegas

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

31000.00
49700.00

403
403

6
6

Note that the generated output is relational in form. All rows and columns are uniform.
The PARTITIONBY clause defines the group whose rows will be counted by the COUNTWindow Function. This count is displayed
as part of each row within the group, thus it may appear multiple times.
The COUNTWindow function permits viewing the detail data of each group, whereas the standard COUNT function does not show
detail data, but only the aggregation at the group level.
The COUNTWindow function and standard aggregate functions (i.e., SUM,AVG,COUNT,MIN,MAX) may not be combined in a single
SELECT statement.

Using WITH For Final Counts


Using the WITH clause allows generation of final counts.
Consider the following example using the WITH clause.
Produce a report showing the employees in departments 410 and 403 by last name, their salaries and the total number of people
in both departments.
Use the WITH feature of Teradata SQL.
SELECTlast_name
ASName
,salary_amount
ASSalary
,department_number
ASDept
FROMemployee
WHEREDeptIN(401,403)
WITHCOUNT(Dept)(TITLE'Total_Count')
ORDERBY3,1;
Name

Brown
Hoover
Johnson
Machado
Phillips
Rogers
Trader
Brown
Charles
Hopkins
Lombardo
Ryan
Villegas

Salary

43100.00
25525.00
36300.00
32300.00
24500.00
46000.00
37850.00
43700.00
39500.00
37900.00
31000.00
31200.00
49700.00
Total_Count

Dept

401
401
401
401
401
401
401
403
403
403
403
403
403

13

The WITHclause generates a total count of all rows in the sample.


The COUNT Window function may also be used to generate final counts, comparably to the WITH clause capability.

Using The COUNT Window Function For Final Counts


Consider the same problem using the COUNT Window function.

Example
Produce a report showing the employees in departments 401 and 403 by last name, their salaries and the total number of people
in both departments. Use the COUNT Window feature.
SELECTlast_name
ASName
,salary_amount
ASSalary
,department_number
ASDept
,COUNT(salary)OVER
(ROWSBETWEENUNBOUNDEDPRECEDINGANDUNBOUNDEDFOLLOWING)
ASDept_Count
FROMemployee
WHEREDeptIN(401,403)
ORDERBY3,1;
Name

Brown

Salary

43100.00

Dept

401

Dept_Count

13

7 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

Hoover
Johnson
Machado
Phillips
Rogers
Trader
Brown
Charles
Hopkins
Lombardo
Ryan
Villegas

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

25525.00
36300.00
32300.00
24500.00
46000.00
37850.00
43700.00
39500.00
37900.00
31000.00
31200.00
49700.00

401
401
401
401
401
401
403
403
403
403
403
403

13
13
13
13
13
13
13
13
13
13
13
13

Rather than generate a separate row for the result, the total is included on each row of output.

Summary
The COUNT Window function:
produces a group count in conjunction with each detail row
is an ANSI standard function
may not be combined in a SELECTwith standard aggregate functions (i.e. SUM,COUNT,AVG,MIN,MAX>)
may not be combined in a SELECT with WITH and/or WITHBY clauses

Lab
Try It!

For this set of lab questions you will need information from the Database Info document.
To start the online labs, click on the Telnet button in the lower left hand screen of the course. Two
windows will pop-up: a BTEQ Instruction Screen and your Telnet Window. Sometimes the BTEQ
Instructions get hidden behind the Telnet Window. You will need these instructions to log on to Teradata.
Be sure to change your default database to the Customer_Service database in order to run
these labs.
Click on the buttons to the left to see the answers.

Answers:
Lab 1
Lab 2

1.) We wish to see a report showing us how many people in departments 301, 401 and 501 are earning a
salary greater than $35,000. Show the count for each department and a list of the employee numbers
who qualify.
2.) How many people in each department were born prior to 1950 and who are they? Show last name,
first name (reduce both to 10 characters), birth date(as Birthdate), department number (as Dept), and
the count of people in that department who qualify (as Dept_Cnt). Order the results by birth date within
department.

Using The SUM Window Function


Objectives
After completing this module, you should be able to:
Produce reports requiring group-based sums using the SUM Window function.

SUM Window Function


The SUM Window function may be used to perform the following operations:
Sum a column from rows in a defined group.
Sum a column from all rows in all groups.
A similar result can be produced using the WITH and WITHBY extensions to SQL. The WITHBY function is used to produce sub-totals
(and sub-counts) over the detail data for a group, as defined by the BY clause. Similarly, the WITHfunction is used to provide
grand totals (and grand counts) over the detail data for all rows.
The SUMWindow function is an ANSI-standard function, whereas the WITH and WITHBY functions are not.

Using WITH BY For Group Totals

8 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

Sales Table
Using the WITHBYclause allows generation of sub-totals based on groupings identified in the BY clause.
Consider the 'salestbl' used in the following example. Its contents are shown here.
SELECT*FROMsalestblORDERBY1,2;
storeid

1001
1001
1001
1001
1002
1002
1002
1003
1003
1003
1003

prodid
sales

A
100000.00
C
60000.00
D
35000.00
F
150000.00
A
40000.00
C
35000.00
D
25000.00
A
30000.00
B
65000.00
C
20000.00
D
50000.00

The following example produces a report showing a sub-total of sales by store.

Example
Produce a report showing the sales for each product by store and the total sales for each store. (Use the WITHBY feature of Teradata
SQL.)
SELECT
storeid
,prodid
,sales
FROMsalestbl
WITHSUM(sales)BYstoreid
ORDERBY1,2;
storeid prodid

1001 A
1001 C
1001 D
1001 F

sales

100000.00
60000.00
35000.00
150000.00

Sum(sales)345000.00
1002 A
1002 C
1002 D

40000.00
35000.00
25000.00

Sum(sales)100000.00
1003 A
1003 B
1003 C
1003 D

30000.00
65000.00
20000.00
50000.00

Sum(sales)165000.00

Using The SUM Window Function For Group Totals


Consider the same problem done using the SUM Window function.

Example
Produce a report showing the sales for each product by store and the total sales for each store. Use the SUM Window feature of
Teradata SQL.
SELECTstoreid
,prodid
,sales
,SUM(sales)OVER(PARTITIONBYstoreid
ROWSBETWEENUNBOUNDEDPRECEDINGANDUNBOUNDEDFOLLOWING)
FROMsalestbl
ORDERBY1,2;
storeid prodid

salesGroupSum(sales)

9 of 137

3/10/2010 1:07 AM

Teradata SQL Advanced


%20%20Adv...

1001 A
1001 C
1001 D
1001 F
1002 A
1002 C
1002 D
1003 A
1003 B
1003 C
1003 D

file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL

100000.00
60000.00
35000.00
150000.00
40000.00
35000.00
25000.00
30000.00
65000.00
20000.00
50000.00

345000.00
345000.00
345000.00
345000.00
100000.00
100000.00
100000.00
165000.00
165000.00
165000.00
165000.00

The PARTITIONBY clause defines the group whose rows will be totaled by the SUM Window Function. This count is displayed as part of
each row within the group, thus it may appear multiple times.
The SUM Window function permits viewing the detail data of each group, whereas the standard SUM function does not show detail
data, but only the aggregation at the group level.
The SUM Window function and standard aggregate functions (such as SUM) may not be combined in a single SELECT statement.

Using WITH For Final Totals


Using the WITH clause allows generation of final totals.
Consider the following examples.

Example
Show the sales of all products in all stores and a grand total for all stores. (Use the WITH feature of Teradata SQL.)
SELECT
storeid
,prodid
,sales
FROMsalestbl
WITHSUM(sales)
ORDERBY1,2;
storeidprodid

1001 A
1001 C
1001 D
1001 F
1002 A
1002 C
1002 D
1003 A
1003 B
1003 C
1003 D

sales

100000.00
60000.00
35000.00
150000.00
40000.00
35000.00
25000.00
30000.00
65000.00
20000.00
50000.00

Sum(sales)610000.00

The WITH clause generates a grand total of all rows in the sample. This result requires the generation of a separate line of output.
The SUM Window function may also be used to generate grand totals, comparably to the WITH clause capability.

Using The SUM Window Function For Final Totals


Consider the same problem using the SUM Window function.
Show the sales of all products in all stores and a grand total for all stores. (Use the SUM Window function.)
SELECTstoreid
,prodid
,sales
,SUM(sales)OVER
(ROWSBETWEENUNBOUNDEDPRECEDINGANDUNBOUNDEDFOLLOWING)
FROMsalestbl
ORDERBY1,2;
storeidprodid

1001 A
1001 C
1001 D
1001 F
1002 A
1002 C

sales

100000.00
60000.00
35000.00
150000.00
40000.00
35000.00

GroupSum(sales)

610000.00
610000.00
610000.00
610000.00
610000.00
610000.00

10 of 137

3/10/2010 1:07 AM

Thank you for trying Solid Converter PDF.


The trial version of this product only converts 10% of your document, with a 10 page maximum.
For this conversion, Solid Converter PDF converted 10 of 137 pages.
Please register Solid Converter PDF at http://www.solidpdf.com/buy.htm to remove this restriction.

You might also like