You are on page 1of 36

Features of Teradata SQL

Module 14

Setting the Stage


After completing this module, you will be able to:

State the purpose and function of the session


setting flags

Recognize differences in transaction modes for


Teradata and ANSI

Use the various HELP functions available

SQL Version 2 Differences


Teradata V2R2 (and later) consists of: - All existing Teradata features from v1. - ANSI compatible ways to perform many Teradata V1 features. - Completely new features based on ANSI standard.
Macros

ANSI

Inter. Full

CASE

WITH BY FORMAT

Teradata

AS

NAMED

V2R2 allows for sessions to operate in either ... - BTET (Teradata) mode - ANSI mode All syntax, both ANSI and Teradata extensions, is accepted in either mode.

The same syntax might function differently in each mode.


Using ANSI mode to run existing V1 scripts will affect: - Transaction protocol behavior - Case sensitivity and collating sequences - Certain data conversion and display functions

SQL Session Modes


Transaction mode setting ANSI - uses ANSI mode (Commit mode) BTET - uses standard Teradata mode (Begin Txn - End Txn mode) BTEQ Examples .SET SESSION TRANSACTION ANSI; - requires COMMIT to end transaction

.SET SESSION TRANSACTION BTET; - requires BT to start explicit transaction - requires ET to end explicit transaction - requires neither for implicit transactions

Must be entered prior to LOGON. To change session mode, must LOGOFF first. Affects: - Transaction protocol - Default case sensitivities - Data conversions

Transaction Modes - ANSI


.SET SESSION TRANSACTION ANSI; ANSI mode: A transaction is committed only by an explicit COMMIT.

COMMIT WORK will commit the currently active Txn.


A rollback occurs when any of the following occur: ROLLBACK WORK - explicit rollback of active Txn Session abort - rollback of active Txn SQL statement failure - rollback current statement only Transactions are by definition explicit. Statement following a COMMIT automatically starts a new Txn. COMMIT is required immediately following any DDL. Locks are accumulated until a COMMIT is issued.

Transaction Modes - Teradata


.SET SESSION TRANSACTION BTET;

BTET mode: A transaction is by definition implicit. Each request is an implicit transaction. BEGIN and END TRANSACTION are used to create larger transactions out of individual requests. BT begins an explicit Txn. ET commits the currently active Txn. A rollback occurs when any of the following occur: ROLLBACK WORK - explicit rollback of active Txn Session abort - rollback of active Txn SQL statement failure - rollback of active Txn Locks are accumulated following a BT until an ET is issued.

Transaction Examples
ANSI Mode BTET Mode (explicit) BT Upd A Upd B ET (both commit) BT Upd A Upd B (fails) (both rollback) BTET Mode (implicit) Upd A (A commits) Upd B (B commits)

Upd A Upd B COMMIT (both commit) Upd A Upd B (fails) COMMIT (A commits)

Upd A (A commits) Upd B (fails) (rollback B)

Upd A Upd B ROLLBACK (both rollback)

BT Upd A Upd B ROLLBACK (both rollback) BT Upd A Upd B LOGOFF (both rollback)

(No explicit ROLLBACK in implicit Txn)

Upd A Upd B LOGOFF (both rollback)

Upd A (A commits) Upd B (B commits) LOGOFF

BTEQ .SHOW Command


.LOGON XYZ,XYZ;

.SHOW CONTROL;
[SET] FOLDLINE = OFF ALL [SET] FOOTING = NULL [SET] FORMAT = OFF [SET] FORMCHAR = OFF [SET] HEADING = NULL [SET] INDICDATA = OFF [SET] NOTIFY = OFF [SET] NULL =? [SET] OMIT = OFF ALL [SET] PAGEBREAK = OFF ALL [SET] PAGELENGTH = 55 [SET] QUIET = OFF [SET] RECORDMODE = OFF [SET] RETCANCEL = OFF [SET] RETLIMIT = No Limit [SET] RETRY = ON [SET] RTITLE = NULL [SET] SECURITY = NONE [SET] SEPARATOR = two blanks [SET] SESSION CHARSET = ASCII [SET] SESSION SQLFLAG = NONE [SET] SESSION TRANSACTION = BTET [SET] SESSIONS =1 [SET] SIDETITLES = OFF for the normal report. [SET] SKIPDOUBLE = OFF ALL [SET] SKIPLINE = OFF ALL [SET] SUPPRESS = OFF ALL [SET] TDP = l5442 [SET] 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

HELP SESSION Command


HELP SESSION; *** Help information returned. One row. *** Total elapsed time was 1 second. User Name Account Name Logon Date Logon Time Current DataBase Collation Character Set Transaction Semantics Current DateForm Session Time Zone Default Character Type TUSER25 $M_9038_&L 00/06/16 15:14:04 TUSER25 ASCII ASCII Teradata IntegerDate 00:00 LATIN

Note: To produce this format, use BTEQ settings: .SET SIDETITLES .SET FOLDLINE To return to the default settings: .SET DEFAULTS

Online Syntax HELP


Provides help on multiple utilities. Provides global command menu. Provides individual command syntax. Online Syntax help HELP HELP utilityname utilitycommand; SQL ARCHIVE BULKLOAD DUMP FASTEXPORT FASTLOAD MULTILOAD PMPC TPCCONS command-name; command-name; command-name; command-name; command-name; command-name; command-name; command-name; command-name;

HELP SQL; HELP SQL SELECT; HELP SQL ALTER TABLE;

HELP Examples
HELP 'SQL';
*** Query completed. 35 rows found. One column returned. *** Total elapsed time was 1 second. On-Line Help --------------------------------------------------------------------------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 :

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 ] ] ; SET columnname = expr [ ... ,columnname = expr]

[ WHERE condition ] [ ]; [ ALL ]

SELECT Statement ANSI Join Syntax


With V2R2 (and later), Teradata supports the ANSI join syntax and outer joins - details in Appendix B.
SELECT cname [, cname , ] FROM tname [aname] [INNER] LEFT [OUTER] RIGHT [OUTER] FULL [OUTER] CROSS

JOIN ON Where:

tname [aname] condition ;

cname tname aname condition INNER JOIN LEFT OUTER JOIN

Column or expression name Table or view name Alias for table or view name Criteria for the join All matching rows Table to the left is used to qualify, table on the right has nulls when rows do not match. Table to the right is used to qualify, table on the left has nulls when rows do not match. Both tables are used to qualify and extended with nulls. Cartesian product

RIGHT OUTER JOIN

FULL OUTER JOIN CROSS JOIN

CASE Sensitivity Issues - Teradata


Teradata Rules - Column Attributes Storage As entered (default) UPPERCASE UPPER, LOWER CASESPECIFIC (CS) NONCASESPECIFIC (NOT CS) (Teradata default)

Comparisons

Default (NOT CS) result


SELECT first_name , last_name FROM employee WHERE last_name LIKE %Ra%; first_name Robert James I.B. Larry Peter last_name Crane Trader Trainer Ratzlaff Rabbit

(CS) result
SELECT first_name , last_name FROM employee WHERE last_name(CS) LIKE %Ra%; first_name last_name Larry Ratzlaff Peter Rabbit

CASE Sensitivity Issues - ANSI


ANSI Rules - Column Attributes Storage None (As entered is default) UPPER, LOWER (Casespecific is default)

Comparisons

Default (CS) result


SELECT first_name , last_name FROM employee WHERE last_name LIKE %Ra%;
first_name last_name Larry Ratzlaff Peter Rabbit

Explicit CS result
SELECT first_name , last_name FROM employee WHERE last_name(CS) LIKE %Ra%;
first_name last_name Larry Ratzlaff Peter Rabbit

Using ESCAPE with LIKE


LIKE Wildcard rules Underscore _ replaces one character. Percent sign % replaces zero to many characters. ESCAPE rule
ESCAPE permits use of _ or % as part of string search criteria.

SELECT test_num, comment FROM test_results WHERE comment LIKE %95a%% ESCAPE a;

test num 15365

comment Result is 95%

SELECT filename, filesize FROM file_table WHERE filename LIKE %ANSIb_SQLb_% ESCAPE b;

filename ANSI_SQL_QRY3

filesize 2068

Data Types
Teradata INTEGER SMALLINT BYTEINT DATE TIME TIME WITH ZONE TIMESTAMP TIMESTAMP WITH ZONE FLOAT FLOAT FLOAT DECIMAL(n,m) DECIMAL(n,m) CHAR(n) VARCHAR(n) CHAR VARYING(n) LONG VARCHAR BYTE(n) VARBYTE(n) GRAPHIC(n) VARGRAPHIC(n) LONG VARGRAPHIC ANSI (Entry) equivalent INTEGER SMALLINT

FLOAT REAL DOUBLE PRECISION DECIMAL(n,m) NUMERIC(n,m) CHAR(n)

Table Level Attributes


CREATE MULTISET TABLE sales_period DATABLOCKSIZE = 16384 BYTES FREESPACE = 10 PERCENT (period_num INT);

SET MULTISET

Dont allow duplicate rows Allow duplicate rows (ANSI)

DATABLOCKSIZE Maximum multi-row blocksize for table in: BYTES KILOBYTES (or KBYTES) Rounded to nearest sector (512) Increments of 1024

MINIMUM DATABLOCKSIZE MAXIMUM DATABLOCKSIZE

(6144) (65024)

FREESPACE

Percent of freespace to keep on cylinder during loading operations (0 - 75%)

Column Attributes

Attribute UPPERCASE CASESPECIFIC FORMAT TITLE NAMED/AS COMPRESS COMPRESS NULL COMPRESS value WITH DEFAULT DEFAULT DATE DEFAULT TIME NOT NULL DEFAULT value DEFAULT USER DEFAULT NULL

ANSI

Teradata Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

Yes Yes Yes Yes

Primary Keys And Indexes (Review)


Primary Keys
Primary key - one or more columns used to uniquely identify the rows of a table (one per table). Primary keys (PK) are used in conjunction with foreign keys to define the important relationships in a database. PKs are always unique and cannot be null. PKs are not known to the Teradata DBS as such. PKs are implemented as indexes by the Teradata DBS.

Indexes
Primary index - one or more columns used to distribute and locate the rows of a table (one per table). Primary index(PI) choice will affect distribution, access and thus performance. Indexes (primary or secondary) may be used to enforce uniqueness. Indexes (primary or secondary) may be used to improve access. Indexes (primary or secondary) may be unique or nonunique.

Creating Employee Table With Constraints


All constraints are unnamed. All constraints are at the column level.
CREATE TABLE employee ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( employee_number INTEGER NOT NULL PRIMARY KEY, manager_employee_number INTEGER REFERENCES employee(employee_number), department_number INTEGER REFERENCES department(department_number), job_code INTEGER REFERENCES job(job_code), last_name CHAR(20) NOT NULL, first_name VARCHAR(30) NOT NULL, hire_date DATE NOT NULL, birthdate DATE NOT NULL, salary_amount DECIMAL(10,2) NOT NULL) ;

Primary Key column(s) must be defined NOT NULL. Referenced columns must be defined as unique. Up to 64 foreign keys may be defined on a table. User must have REFERENCES right on referenced table.

Show Table Constraints Employee Table


SHOW TABLE employee; CREATE SET TABLE employee ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( employee_number INTEGER NOT NULL, manager_employee_number INTEGER, department_number INTEGER NOT NULL, job_code INTEGER, last_name CHAR(20) NOT CASESPECIFIC NOT NULL, first_name VARCHAR(30) NOT CASESPECIFIC NOT NULL, hire_date DATE NOT NULL, birthdate DATE NOT NULL, salary_amount DECIMAL(10,2) NOT NULL, FOREIGN KEY ( manager_employee_number ) REFERENCES employee ( employee_number ), FOREIGN KEY ( department_number ) REFERENCES department( department_number), FOREIGN KEY ( job_code ) REFERENCES job ( job_code ) ) UNIQUE PRIMARY INDEX ( employee_number );

Note: Primary key becomes the Primary index.

Altering Table Constraints


To add constraints to a table: ALTER TABLE tablename ADD CONSTRAINT constrname CHECK ADD CONSTRAINT constrname UNIQUE ADD CONSTRAINT constrname PRIMARY KEY ADD CONSTRAINT constrname FOREIGN KEY

To modify existing constraints: ALTER TABLE tablename MODIFY CONSTRAINT constrname

To drop constraints: ALTER TABLE tablename DROP CONSTRAINT constrname

What is a Trigger?
A Trigger may be defined as: One or more stored SQL statements associated with a table An event driven procedure attached to a table An object in a database, like tables, views and macros Any of the following SQL statements may be applied to triggers: CREATE DROP SHOW ALTER RENAME REPLACE HELP

TRIGGERS

Triggers may not be used in conjunction with: The FastLoad utility The MultiLoad utility Updateable Cursors (Preprocessor environment) DELETE DATABASE

DELETE USER

Both cause all triggers to be dropped.

Privileges are required to create and drop triggers. GRANT REVOKE CREATE DROP TRIGGER

Temporary Table Choices


Derived Tables Local to the query (table and columns are named within query) Incorporated into SQL query syntax (populated in query via SELECT in FROM) Materialized in SPOOL - Spool rows are discarded when query finishes No data dictionary involvement Commonly used with aggregation Volatile Tables Local to a session - uses SPOOL space Uses CREATE VOLATILE TABLE syntax Discarded automatically at session end No data dictionary involvement (Global) Temporary Tables Local to a session - uses TEMPORARY space Uses CREATE GLOBAL TEMPORARY TABLE syntax Materialized instance of table discarded at session end. Creates and keeps table definition in data dictionary

Inserting Default Values


INSERT INTO tablename DEFAULT VALUES; Will insert defined default values into each column. If no default is defined, will insert a null. If no default defined and null not allowed, insert will fail. CREATE TABLE test_tbl (cola SMALLINT NOT NULL DEFAULT 22 ,colb CHAR(1) ,colc DATE DEFAULT 1000101 FORMAT 'YYYY-MM-DD' ,cold DEC(3,2) NOT NULL WITH DEFAULT ,cole TIME(0) DEFAULT CURRENT_TIME ,colf INT DEFAULT TIME ,colg CHAR(8) DEFAULT USER);

INSERT INTO test_tbl DEFAULT VALUES; SELECT * FROM test_tbl;


cola colb colc cold cole colf colg ------- ----- --------------- ------ ----------- ----------- -------22 ? 2000-01-01 .00 11:14:14 111414 PED

INSERT INTO test_tbl DEFAULT VALUES; SELECT * FROM test_tbl;


cola ------22 22 colb colc cold cole colf ----- --------------- ------ ----------- ----------? 2000-01-01 .00 11:14:14 111414 ? 2000-01-01 .00 11:14:37 111437 colg -------PED PED

Lab Environment
DBC
UNIX userids u____01 u____02 u____xx
Note: ___ Instructor Initials

Teradata_Factory AU
Accounts Customer Trans Lab3_1_1 Lab3_1_2
Accounts Customer Trans

____Students
T____01 T____02
Accounts Customer Trans

T____xx
Accounts Customer Trans

Useful Teradata Commands in BTEQ:


.LOGON tpdid/username HELP SESSION; HELP USER username; HELP SQL sqlcommand; SHOW TABLE tablename; SELECT COUNT(*) FROM tname; DELETE tablename ALL; DROP TABLE tablename; EXEC macroname; .RUN FILE=filename .QUIT - logon to Teradata - displays session information - lists objects owned by user - help for an SQL command - shows table creation syntax - provides count of rows in table - deletes all rows in a table - drops table from the database - executes a macro - executes a file of BTEQ/SQL commands - exits BTEQ

Useful UNIX Commands:


ls -l pg (or more) filename vi (or vedit) filename cp file1 file2 mv filename newfilename rm filename exit - long listing of UNIX files) - view contents of text file - create or edit a text file - copies file1 to file2 - renames a file - delete a file - exits UNIX

SELECT Statement Join Syntax


SELECT cname [, cname , ] FROM tname [aname] [INNER] LEFT [OUTER] RIGHT [OUTER] FULL [OUTER] CROSS

JOIN ON

tname [aname] condition ;

Where: cname tname aname condition INNER JOIN LEFT OUTER JOIN Column or expression name Table or view name Alias for table or view name Criteria for the join All matching rows Table to the left is used to qualify, table on the right has nulls when rows do not match. Table to the right is used to qualify, table on the left has nulls when rows do not match. Both tables are used to qualify and extended with nulls. Cartesian product

RIGHT OUTER JOIN

FULL OUTER JOIN CROSS JOIN

Inner Joins
An inner join returns an output row for each successful match between the join tables. SELECT D.Department_Number AS Dept ,Department_Name ,Last_name ,E.Department_Number AS EmpDept FROM Department D INNER JOIN Employee E ON E.Department_Number = D.Department_Number;

Dept Department_Name 402 software support 100 executive 501 marketing sales 301 research and development 301 research and development

Last_Name Crane Trainer Runyon Stein Kanieski

EmpDept 402 100 501 301 301

Information about employees and their department names where the employees department number matches the existing departments. No information about employees who have no department number or an invalid department number. No information about departments which have no employees assigned to them.

Outer Joins
An outer join returns matching rows and nonmatching rows.
SELECT D.Department_Number AS Dept ,Department_Name ,Last_name ,E.Department_Number AS EmpDept FROM Employee E FULL OUTER JOIN Department D ON E.Department_Number = D.Department_Number;
Dept 600 402 ? 501 301 ? 100 301 Department_Name new department software support ? marketing sales research and development ? executive research and development Last_Name ? Crane James Runyon Kanieski Green Trainer Stein EmpDept ? 402 111 501 301 ? 100 301

In addition to output from inner join:


Shows employees with null departments. Shows employees with invalid departments. Shows departments with no employees.

LEFT Outer Join Example


SELECT E.Department_Number ,Department_Name ,Last_Name Employee E LEFT OUTER JOIN Department D E.Department_Number = D.Department_Number

FROM ON

;
department_number 402 111 501 301 ? 100 301 department_name software support ? marketing and sales research and develop ? executive research and develop last_name Crane James Runyon Stein Green Trainer Kanieski

In addition to output from inner join: Shows employees with null departments. Shows employees with invalid departments.

RIGHT Outer Join Example


SELECT D.Department_Number ,Department_Name ,Last_Name Employee E RIGHT OUTER JOIN Department D E.Department_Number = D.Department_Number

FROM

ON
;

department_number 600 402 100 501 301 301

department_name new department software support executive marketing sales research and develop research and develop

last_name ? Crane Trainer Runyon Stein Kanieski

In addition to output from inner join:

Shows departments with no employees.

Outer Joins of More Than Two Tables


Each JOIN must have an associated ON clause. In joining more than two Tables in an outer join, the ON clause needs to be placed appropriately so that the join operation can be evaluated correctly.
SELECT last_name AS Employee ,department_name AS Dept ,description AS Job FROM Department D RIGHT OUTER JOIN Employee E ON D.Department_Number = E.Department_Number LEFT OUTER JOIN Job J ON E.Job_Code = J.Job_Code ;

Returns all employees including: employees with invalid departments employees with null departments employees with invalid job codes employees with null job codes

ON Clause Placement
The placement of the ON clause in the SELECT is important. The rules are: The first ON clause (from left to right) is evaluated first. An ON clause applies to the immediately preceding join operation. The same SELECT example could be written as: SELECT last_name AS Employee ,department_name AS Dept ,description AS Job FROM Department D RIGHT OUTER JOIN Employee E LEFT OUTER JOIN Job J ON E.Job_Code = J.Job_Code ON D.Department_Number = E.Department_Number; Using parenthesis can clarify the reading of the statement. SELECT last_name AS Employee ,department_name AS Dept ,description AS Job FROM (Department D RIGHT OUTER JOIN (Employee E LEFT OUTER JOIN Job J ON E.Job_Code = J.Job_Code ) ON D.Department_Number = E.Department_Number);

Cross Joins
A cross join is a join that requires no join condition. Cross joins are sometimes called product joins. Each participating row of one table is joined with each participating row of another table. Cross join syntax does not allow an ON clause.

A WHERE clause may restrict which rows participate from either table.
SELECT e.employee_number ,d.department_number FROM employee e CROSS JOIN department d WHERE e.employee_number = 1008;
employee_number department_number --------------------------- ---------------------------1008 501 1008 301 1008 402 1008 201 1008 302 1008 600 1008 401 1008 100 1008 403

One employee matched with nine departments results in nine rows of output. Output is not meaningful.

Cartesian Products
A completely unconstrained cross join is called a Cartesian Product. Each row of one table is joined to each row of another table. A Cartesian product results from a CROSS JOIN without a WHERE clause.
SELECT e.employee_number ,d.department_number FROM employee e CROSS JOIN department d;

Each employee row (26) matched with each department row (9) yields 234 rows of output. An 8,000,000 row table and a 50,000 row table would yield a 400,000,000,000 row answer set. The output of a Cartesian product is rarely meaningful. Cartesian products can also result from an INNER JOIN with improper aliasing or improper join conditions.
SELECT employee.employee_number ,d.department_number FROM employee e INNER JOIN department d ON e.department_number = d.department_number;

Thank You!!!

You might also like