Teradata SQL Advanced
Teradata SQL Advanced
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
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
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 COMMIT command 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 Session Abort SQL statement failure SQL statement error Explicit rollback of an active transaction Rollback of active transaction Rollback of active transaction 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 COMMIT automatically 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 BEGIN TRANSACTION / END TRANSACTION. 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 END TRANSACTION 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 Session Abort SQL statement failure explicit rollback of active transaction rollback of active transaction rollback of active transaction
2 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
Example
(Note: all user input commands are in red.) .SET SESSION SQLFLAG ENTRY; .LOGON xyz,xyz; sel date; *** Query completed. One row found. One column returned. *** Total elapsed time was 1 second. sel date; $ *** SQL Warning 5836 Token is not an entry level ANSI Identifier or Keyword. sel date; $ *** SQL Warning 5821 Built-in values DATE and TIME are not ANSI. sel date; $ *** SQL Warning 5804 A FROM clause is required in ANSI Query Specification. (Note that three warnings were generated because ANSI does not accept lowercase characters, abbreviations, or the DATE keyword. In spite of the warnings, the date is returned.) Date -------97/01/20
(Note that we must logoff in order to reset the ANSI Flagger.) .LOGOFF; .SET SESSION SQLFLAG NONE; .LOGON xyz,xyz; sel date; *** Query completed. One row found. One column returned. *** Total elapsed time was 1 second. Date -------97/01/20
Note: SQLFLAG may also be set when using Teradata front-end clients other than BTEQ, for example the Teradata Preprocessor (PP2) and
3 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
SESSION SQLFLAG = NONE SESSION TRANSACTION = BTET SESSIONS = 1 SIDETITLES = OFF for the normal report. SKIPDOUBLE = OFF ALL SKIPLINE = OFF ALL SUPPRESS = OFF ALL TDP = l5442 TITLEDASHES = ON for the normal report. And, it is ON for results of WITH clause number: 1 2 3 4 5 6 7 8 9. [SET] UNDERLINE = OFF ALL [SET] WIDTH = 75
Example
HELP 'SQL SELECT'; /* Provides syntax help for the SQL SELECT statement */ HELP 'SQL ALTER TABLE'; /* Provides syntax help for SQL ALTER TABLE statement */ HELP also provides syntax help for most Teradata client utilities as well as for SQL.
Example
HELP 'utilityname utilitycommand'; such as: HELP 'ARCHIVE Command-name'; HELP 'MULTILOAD command-name';
HELP Examples
HELP either generates a list of all available commands and functions, as in: HELP 'SQL'; *** Query completed. 35 rows found. One column returned. *** Total elapsed time was 1 second. On-Line Help (Partial Listing) ----------------------------------------------------------------------DBS SQL COMMANDS: ABORT BEGIN TRANSACTION COMMIT CREATE INDEX CREATE USER DELETE DROP DATABASE DROP TABLE ECHO EXECUTE GRANT ALTER TABLE CHECKPOINT COMMENT CREATE MACRO CREATE VIEW DELETE DATABASE DROP INDEX DROP VIEW END LOGGING EXPLAIN GRANT LOGON BEGIN LOGGING COLLECT STATISTICS CREATE DATABASE CREATE TABLE DATABASE DELETE USER DROP MACRO DROP STATISTICS END TRANSACTION GIVE HELP
or, delivers the full syntax for any specified command, such as: HELP 'SQL UPDATE'; *** Query completed. 10 rows found. One column returned. *** Total elapsed time was 1 second. On-Line Help --------------------------------------------------------------------------UPD[ATE] tablename [ [AS] aname ] [ FROM tname [ [AS] aname] ] [... ,tname [ [AS] aname ] ] ;
4 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
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.
A. Logon using your assigned userid and password. Do a HELP SESSION to see session information. Notice that output exceeds screen width. To adjust output width, use the following setting commands: .sidetitles; .foldline; Do the HELP SESSION again. 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 HELP SESSION. 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 COMMIT command 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 (.SIDETITLES OFF;.FOLDLINE OFF;). Use the appropriate HELP command to view the contents of your userid database. Do a HELP command on a table called "employee". (Hint: Its not in your database. Its in Customer_Service.). Do a HELP command 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 ALTER TABLE command.
5 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
The COUNT Window function is an ANSI-standard function, whereas the WITH and WITH BY functions are not. The COUNT Window function also produces true relational output (uniform columns and rows) whereas WITH and WITH BY do not.
Example
Produce a report showing the people in departments 401 and 403, their salaries, and how many people are in each department. Use the WITH BY feature of Teradata SQL. SELECT last_name AS Name ,salary_amount AS Salary ,department_number AS Dept FROM employee WHERE Dept IN (401,403) WITH COUNT(Dept)(TITLE 'Dept_Count') BY Dept; 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 ----6
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.
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 AS Name ,salary_amount AS Salary ,department_number AS Dept ,COUNT(Salary) OVER (PARTITION BY Dept ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS Dept_Count FROM employee WHERE Dept IN (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
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
Lombardo Villegas
31000.00 49700.00
403 403
6 6
Note that the generated output is relational in form. All rows and columns are uniform. The PARTITION BY clause defines the group whose rows will be counted by the COUNT Window Function. This count is displayed as part of each row within the group, thus it may appear multiple times. The COUNT Window 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 COUNT Window function and standard aggregate functions (i.e., SUM, AVG, COUNT, MIN, MAX) may not be combined in a single SELECT statement.
The WITH clause 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.
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. SELECT last_name AS Name ,salary_amount AS Salary ,department_number AS Dept ,COUNT(salary) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS Dept_Count FROM employee WHERE Dept IN (401,403) ORDER BY 3,1; Name ---------Brown Salary -------43100.00 Dept ---401 Dept_Count ---------13
7 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
Hoover Johnson Machado Phillips Rogers Trader Brown Charles Hopkins Lombardo Ryan Villegas
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 SELECT with standard aggregate functions (i.e. SUM, COUNT, AVG, MIN, MAX>) may not be combined in a SELECT with WITH and/or WITH BY 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.
8 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
Sales Table Using the WITH BY clause 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 * FROM salestbl ORDER BY 1,2; storeid ----------1001 1001 1001 1001 1002 1002 1002 1003 1003 1003 1003 prodid --------A C D F A C D A B C D sales ------------100000.00 60000.00 35000.00 150000.00 40000.00 35000.00 25000.00 30000.00 65000.00 20000.00 50000.00
Example
Produce a report showing the sales for each product by store and the total sales for each store. (Use the WITH BY feature of Teradata SQL.) SELECT storeid , prodid , sales FROM salestbl WITH SUM(sales) BY storeid ORDER BY 1,2; storeid ------1001 1001 1001 1001 prodid ------A C D F sales --------100000.00 60000.00 35000.00 150000.00 --------345000.00 40000.00 35000.00 25000.00 --------100000.00 30000.00 65000.00 20000.00 50000.00 --------165000.00
Sum(sales)
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. SELECT storeid , prodid , sales , SUM(sales) OVER (PARTITION BY storeid ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) FROM salestbl ORDER BY 1,2; storeid ------prodid ------sales --------Group Sum(sales) ----------------
9 of 137
3/10/2010 1:07 AM
file:///G:/Study/DWH1/teradata/New%20Folder/SQL/SQL
1001 1001 1001 1001 1002 1002 1002 1003 1003 1003 1003
A C D F A C D A B C D
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 PARTITION BY 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.
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 FROM salestbl WITH SUM(sales) ORDER BY 1,2; storeid ------1001 1001 1001 1001 1002 1002 1002 1003 1003 1003 1003 prodid ------A C D F A C D A B C 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.
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.