teradata sql
DESCRIPTION
New Features of Teradata SQLTRANSCRIPT
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.
ANSI Teradata Inter.
Full
WITH BY
FORMAT
NAMED
CASE
AS
Macros
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)
.SET SESSION TRANSACTION ANSI;
- requires COMMIT to end transaction
BTEQ Examples
.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
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.
.SET SESSION TRANSACTION ANSI;
Transaction Modes - Teradata
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.
.SET SESSION TRANSACTION BTET;
Transaction Examples
ANSI Mode
Upd A
Upd B
COMMIT
(both commit)
Upd A
Upd B (fails)
COMMIT
(A commits)
Upd A
Upd B
ROLLBACK
(both rollback)
Upd A
Upd B
LOGOFF
(both rollback)
BTET Mode
(explicit)
BT
Upd A
Upd B
ET (both commit)
BT
Upd A
Upd B (fails)
(both rollback)
BT
Upd A
Upd B
ROLLBACK
(both rollback)
BT
Upd A
Upd B
LOGOFF
(both rollback)
BTET Mode
(implicit)
Upd A (A commits)
Upd B (B commits)
Upd A (A commits)
Upd B (fails)
(rollback B)
(No explicit ROLLBACK
in implicit Txn)
Upd A (A commits)
Upd B (B commits)
LOGOFF
BTEQ .SHOW Command
[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
.LOGON XYZ,XYZ;
.SHOW CONTROL;
HELP SESSION Command
HELP SESSION;
*** Help information returned. One row.
*** Total elapsed time was 1 second.
User Name TUSER25
Account Name $M_9038_&L
Logon Date 00/06/16
Logon Time 15:14:04
Current DataBase TUSER25
Collation ASCII
Character Set ASCII
Transaction Semantics Teradata
Current DateForm IntegerDate
Session Time Zone 00:00
Default Character Type 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.
HELP ‘utilityname utilitycommand’;
HELP ‘SQL command-name’;
‘ARCHIVE command-name’;
‘BULKLOAD command-name’;
‘DUMP command-name’;
‘FASTEXPORT command-name’;
‘FASTLOAD command-name’;
‘MULTILOAD command-name’;
‘PMPC command-name’;
‘TPCCONS command-name’;
HELP ‘SQL’;
HELP ‘SQL SELECT’;
HELP ‘SQL ALTER TABLE’;
Online Syntax help
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 ALTER TABLE BEGIN LOGGING
BEGIN TRANSACTION CHECKPOINT COLLECT STATISTICS
COMMIT COMMENT CREATE DATABASE
CREATE INDEX CREATE MACRO CREATE TABLE
CREATE USER CREATE VIEW DATABASE
DELETE DELETE DATABASE DELETE USER
DROP DATABASE DROP INDEX DROP MACRO
DROP TABLE DROP VIEW DROP STATISTICS
ECHO END LOGGING END TRANSACTION
EXECUTE EXPLAIN GIVE
GRANT GRANT LOGON 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
SELECT cname [, cname , …]
FROM tname [aname] [INNER]
LEFT [OUTER]
RIGHT [OUTER]
FULL [OUTER]
CROSS
JOIN tname [aname]
ON condition ;
Where:
cname Column or expression name
tname Table or view name
aname Alias for table or view name
condition Criteria for the join
INNER JOIN All matching rows
LEFT OUTER JOIN Table to the left is used to qualify,
table on the right has nulls when
rows do not match.
RIGHT OUTER JOIN Table to the right is used to qualify,
table on the left has nulls when
rows do not match.
FULL OUTER JOIN Both tables are used to qualify and
extended with nulls.
CROSS JOIN Cartesian product
With V2R2 (and later), Teradata supports the ANSI
join syntax and outer joins - details in Appendix B.
CASE Sensitivity Issues - Teradata
Storage As entered (default)
UPPERCASE
Comparisons UPPER, LOWER
CASESPECIFIC (CS)
NONCASESPECIFIC (NOT CS)
(Teradata default)
Teradata Rules - Column Attributes
SELECT first_name
, last_name
FROM employee
WHERE last_name
LIKE ‘%Ra%’;
first_name last_name
Robert Crane
James Trader
I.B. Trainer
Larry Ratzlaff
Peter Rabbit
SELECT first_name
, last_name
FROM employee
WHERE last_name(CS)
LIKE ‘%Ra%’;
first_name last_name
Larry Ratzlaff
Peter Rabbit
Default (NOT CS) result (CS) result
CASE Sensitivity Issues - ANSI
SELECT first_name
, last_name
FROM employee
WHERE last_name
LIKE ‘%Ra%’;
first_name last_name
Larry Ratzlaff
Peter Rabbit
SELECT first_name
, last_name
FROM employee
WHERE last_name(CS)
LIKE ‘%Ra%’;
first_name last_name
Larry Ratzlaff
Peter Rabbit
Default (CS) result Explicit CS result
Storage None
(As entered is default)
Comparisons UPPER, LOWER
(Casespecific is default)
ANSI Rules - Column Attributes
Using ESCAPE with LIKE
SELECT test_num, comment
FROM test_results
WHERE comment LIKE ‘%95a%%’ ESCAPE ‘a’;
LIKE Wildcard rules
Underscore ‘_’ replaces one character.
Percent sign ‘%’ replaces zero to many characters.
ESCAPE permits use of ‘_’ or ‘%’ as part of string
search criteria.
ESCAPE rule
SELECT filename, filesize
FROM file_table
WHERE filename LIKE ‘%ANSIb_SQLb_%’ ESCAPE ‘b’;
test num comment
15365 Result is 95%
filename filesize
ANSI_SQL_QRY3 2068
Data Types
Teradata ANSI (Entry) equivalent
INTEGER INTEGER
SMALLINT SMALLINT
BYTEINT
DATE
TIME
TIME WITH ZONE
TIMESTAMP
TIMESTAMP WITH ZONE
FLOAT FLOAT
FLOAT REAL
FLOAT DOUBLE PRECISION
DECIMAL(n,m) DECIMAL(n,m)
DECIMAL(n,m) NUMERIC(n,m)
CHAR(n) CHAR(n)
VARCHAR(n)
CHAR VARYING(n)
LONG VARCHAR
BYTE(n)
VARBYTE(n)
GRAPHIC(n)
VARGRAPHIC(n)
LONG VARGRAPHIC
Table Level Attributes
CREATE MULTISET TABLE sales_period
DATABLOCKSIZE = 16384 BYTES
FREESPACE = 10 PERCENT
(period_num INT);
SET Don’t allow duplicate rows
MULTISET Allow duplicate rows (ANSI)
DATABLOCKSIZE
Maximum multi-row blocksize for table in:
BYTES Rounded to nearest sector (512)
KILOBYTES Increments of 1024
(or KBYTES)
MINIMUM DATABLOCKSIZE (6144)
MAXIMUM DATABLOCKSIZE (65024)
FREESPACE Percent of freespace to keep on
cylinder during loading operations
(0 - 75%)
Column Attributes
Attribute ANSI Teradata
UPPERCASE Yes
CASESPECIFIC Yes
FORMAT Yes
TITLE Yes
NAMED/AS Yes
COMPRESS Yes
COMPRESS NULL Yes
COMPRESS value Yes
WITH DEFAULT Yes
DEFAULT DATE Yes
DEFAULT TIME Yes
NOT NULL Yes Yes
DEFAULT value Yes Yes
DEFAULT USER Yes Yes
DEFAULT NULL Yes Yes
Primary Keys And Indexes (Review)
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.
PK’s are always unique and cannot be null.
PK’s are not known to the Teradata DBS as such.
PK’s are implemented as indexes by the Teradata DBS.
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 non-
unique.
Primary Keys
Indexes
Creating Employee Table
With Constraints
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.
All constraints are unnamed.
All constraints are at the column level.
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
ALTER TABLE tablename
ADD CONSTRAINT constrname CHECK
ADD CONSTRAINT constrname UNIQUE
ADD CONSTRAINT constrname PRIMARY KEY
ADD CONSTRAINT constrname FOREIGN KEY
To add constraints to a table:
ALTER TABLE tablename
DROP CONSTRAINT constrname
ALTER TABLE tablename
MODIFY CONSTRAINT constrname
To modify existing constraints:
To drop constraints:
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 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
TRIGGERS
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.
INSERT INTO test_tbl DEFAULT VALUES;
SELECT * FROM test_tbl;
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);
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 colb colc cold cole colf colg
------- ----- --------------- ------ ----------- ----------- --------
22 ? 2000-01-01 .00 11:14:14 111414 PED
22 ? 2000-01-01 .00 11:14:37 111437 PED
Lab Environment
DBC
Accounts
Lab3_1_1
Lab3_1_2
Customer
Trans Accounts
Customer
Trans
T____01
Teradata_Factory
AU ____Students
Accounts
Customer
Trans
T____02
Accounts
Customer
Trans
T____xx
Note: ___ Instructor Initials
UNIX userids u____01
u____02
u____xx
Useful Teradata Commands in BTEQ:
.LOGON tpdid/username - logon to Teradata
HELP SESSION; - displays session information
HELP USER username; - lists objects owned by user
HELP ‘SQL sqlcommand’; - help for an SQL command
SHOW TABLE tablename; - shows table creation syntax
SELECT COUNT(*) FROM tname; - provides count of rows in table
DELETE tablename ALL; - deletes all rows in a table
DROP TABLE tablename; - drops table from the database
EXEC macroname; - executes a macro
.RUN FILE=filename - executes a file of BTEQ/SQL commands
.QUIT - exits BTEQ
Useful UNIX Commands:
ls -l - long listing of UNIX files)
pg (or more) filename - view contents of text file
vi (or vedit) filename - create or edit a text file
cp file1 file2 - copies file1 to file2
mv filename newfilename - renames a file
rm filename - delete a file
exit - exits UNIX
SELECT Statement Join Syntax
SELECT cname [, cname , …]
FROM tname [aname] [INNER]
LEFT [OUTER]
RIGHT [OUTER]
FULL [OUTER]
CROSS
JOIN tname [aname]
ON condition ;
Where:
cname Column or expression name
tname Table or view name
aname Alias for table or view name
condition Criteria for the join
INNER JOIN All matching rows
LEFT OUTER JOIN Table to the left is used to qualify,
table on the right has nulls when
rows do not match.
RIGHT OUTER JOIN Table to the right is used to qualify,
table on the left has nulls when
rows do not match.
FULL OUTER JOIN Both tables are used to qualify and
extended with nulls.
CROSS JOIN Cartesian product
Inner Joins
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;
An inner join returns an output row for each successful
match between the join tables.
Dept Department_Name Last_Name EmpDept
402 software support Crane 402
100 executive Trainer 100
501 marketing sales Runyon 501
301 research and development Stein 301
301 research and development Kanieski 301
Information about employees and their department names
where the employee’s 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 non-
matching 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 Department_Name Last_Name EmpDept
600 new department ? ?
402 software support Crane 402
? ? James 111
501 marketing sales Runyon 501
301 research and development Kanieski 301
? ? Green ?
100 executive Trainer 100
301 research and development Stein 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
FROM Employee E LEFT OUTER JOIN
Department D
ON E.Department_Number =
D.Department_Number
;
department_number department_name last_name
402 software support Crane
111 ? James
501 marketing and sales Runyon
301 research and develop Stein
? ? Green
100 executive Trainer
301 research and develop 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
FROM Employee E RIGHT OUTER JOIN
Department D
ON E.Department_Number =
D.Department_Number
;
department_number department_name last_name
600 new department ?
402 software support Crane
100 executive Trainer
501 marketing sales Runyon
301 research and develop Stein
301 research and develop 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.
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;
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.
The same SELECT example could be written as:
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.
employee_number department_number
--------------------------- ----------------------------
1008 501
1008 301
1008 402
1008 201
1008 302
1008 600
1008 401
1008 100
1008 403
SELECT e.employee_number
,d.department_number
FROM employee e CROSS JOIN
department d
WHERE e.employee_number = 1008;
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!!!