Professional Documents
Culture Documents
Tera Cram SQL Final
Tera Cram SQL Final
Teradata SQL
Certification
Tera-Tom Notes
Tera-Tom Notes
Tera-Tom Notes
Table of Contents
Module 1 Teradata Basics ................................................................................7
Introduction .........................................................................................................8
A Table has Rows and Columns..........................................................................10
Retrieving Data From A Table ............................................................................12
Example of Selecting Data From A Table...........................................................14
Example of Selecting All Columns in a table......................................................16
Example of Selecting Only Certain Rows ...........................................................18
Example of Sorting the Data................................................................................20
Checking for NULL Data ....................................................................................22
Examples of NULL Data .....................................................................................24
How Sorting Works with NULL Data.................................................................26
AND, OR, and NOT ............................................................................................28
Valid Table Names ..............................................................................................30
Absolute Function................................................................................................32
The Extract Function ...........................................................................................34
The Date Function ...............................................................................................36
The Between Statement .......................................................................................38
ADD_MONTHS Command ................................................................................40
IN Command .......................................................................................................42
Subqueries............................................................................................................44
Aliasing................................................................................................................46
Joining Two Tables Using Teradata Syntax........................................................48
Joining Two Tables Using ANSI Syntax.............................................................50
SET Operators .....................................................................................................52
SET Operators Continued....................................................................................54
Macros .................................................................................................................56
Derived Tables.....................................................................................................58
Macros .................................................................................................................60
What is a View?...................................................................................................62
Cast ......................................................................................................................64
Traditional Subqueries.........................................................................................66
Traditional Subqueries Continued .......................................................................68
Correlated Subqueries..........................................................................................70
How Correlated Subqueries Work.......................................................................72
Insert Select .........................................................................................................74
Insert Select Continued........................................................................................76
SHOW Commands ..............................................................................................78
HELP Command..................................................................................................80
CREATE a Secondary INDEX............................................................................82
The NULLIF Command ......................................................................................84
Aggregate Functions............................................................................................86
GROUP BY .........................................................................................................88
GROUP BY and HAVING Conditions ...............................................................90
Some Aggregate examples ..................................................................................92
4
Tera-Tom Notes
Tera-Tom Notes
Tera-Tom Notes
Module 1
A
M
P
A
M
P
A
M
P
1
5
9
13
2
6
10
14
3
7
11
15
Tera-Tom Notes
A
M
P
4
8
12
16
Introduction
Welcome to the Tera-Cram series. The Tera-Cram series is designed to teach
readers Teradata and help them pass their Teradata exams. This book is your
guide to passing the Teradata Basics Certification exam. Look for the BOLD and
enlarged print that jumps out at you on the right pages. Know this information
especially well and your chances for success go way up.
Tera-Tom Notes
Introduction
Tera-Tom Notes
10
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
Tera-Tom Notes
11
12
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
To retrieve data from a table users use the four key words
SELECT, FROM, WHERE, and ORDER BY.
You must use the keywords SELECT and FROM.
SELECT: After the word SELECT you will name all the
columns you would like to retrieve.
FROM: After the word FROM you will name the table or
tables in which the information will be retrieved.
WHERE: The WHERE is designed to limit the number of
rows coming back. If you dont use a WHERE clause
then all rows from the table will be returned.
ORDER BY: The ORDER BY statement sorts the data. If
you dont use the ORDER BY statement then the data
comes back in random order.
Tera-Tom Notes
13
14
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
SELECT emp
,dept
,lname
FROM Employee;
Four Rows Returned
EMP
1
2
3
4
DEPT
10
20
30
10
LNAME
JONES
SMITH
CHANG
WILSON
Tera-Tom Notes
15
16
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
SELECT *
FROM Employee;
Four Rows Returned
EMP
1
2
3
4
DEPT
10
20
30
10
LNAME
JONES
SMITH
CHANG
WILSON
FNAME
Dave
Mary
Vu
Sue
SAL
45000.00
50000.00
65000.00
44000.00
Tera-Tom Notes
17
18
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
SELECT *
FROM Employee
WHERE Dept = 10;
Two Rows Returned
EMP
1
4
DEPT
10
10
LNAME
JONES
WILSON
FNAME
Dave
Sue
SAL
45000.00
44000.00
Tera-Tom Notes
19
20
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
SELECT
*
FROM
Employee
ORDER BY LNAME;
Four Rows Returned
EMP
3
1
2
4
DEPT
30
10
20
10
LNAME
CHANG
JONES
SMITH
WILSON
FNAME
Vu
Dave
Mary
Sue
SAL
65000.00
45000.00
50000.00
44000.00
Tera-Tom Notes
21
22
Tera-Tom Notes
LNAME
FNAME
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
IS NULL
IS NOT NULL
Tera-Tom Notes
23
24
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
NULL
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
NULL;
No Rows Returned
NULL;
EMP
99
FNAME
JIM
NOT NULL;
EMP
1
2
3
4
Tera-Tom Notes
FNAME
Dave
Mary
Vu
Sue
25
26
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
NULL
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
SELECT EMP
,DEPT
FROM EMPLOYEE
ORDER BY Dept;
Five Rows Returned
EMP
99
1
4
2
3
DEPT
NULL
10
10
20
30
Tera-Tom Notes
27
28
Tera-Tom Notes
DEPT
LNAME
FNAME
10
20
30
10
NULL
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
SELECT EMP
,DEPT
,FNAME
FROM EMPLOYEE
WHERE Dept = 10
AND
Dept = 20
OR Sal > 80000.00;
One Row Returned
EMP
99
DEPT
FNAME
NULL 99000.00
Tera-Tom Notes
29
30
Tera-Tom Notes
Tera-Tom Notes
characters:
31
Absolute Function
The Absolute Function returns the absolute value for any value requested in the
function. It even returns values for negative numbers and makes them positives.
32
Tera-Tom Notes
Absolute Function
The ABS function looks for the Absolute functions. It can
even look at negative numbers and return the absolute
value which is positive.
Sel ABS(-1.2)
One Row Returned
1.2
Sel ABS(-8.1)
One Row Returned
8.1
Tera-Tom Notes
33
34
Tera-Tom Notes
HIRE_DATE
LNAME
FNAME
01-10-85
02-20-90
02-30-95
04-20-99
05-06-01
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
SELECT *
FROM Employee
WHERE EXTRACT(month from HIRE_DATE) = 5;
One Row Returned
EMP
HIRE_DATE
99
05-06-01
Tera-Tom Notes
LNAME FNAME
NULL
JIM
SAL
99000.00
35
36
Tera-Tom Notes
HIRE_DATE
LNAME
FNAME
01-10-85
02-20-90
02-30-95
04-20-99
05-06-01
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
YRS_OF_SERVICE
17
12
7
3
1
The above query gave us Years since Hire_date for all
employees in the table.
Tera-Tom Notes
37
38
Tera-Tom Notes
HIRE_DATE
LNAME
FNAME
01-10-85
02-20-90
02-30-95
04-20-99
05-06-01
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
SELECT *
FROM Employee
WHERE SAL BETWEEN 45000.00 AND 65000.00;
Three Rows Returned
EMP
1
2
3
HIRE_DATE
01-10-85
02-20-90
02-30-95
LNAME
JONES
SMITH
CHANG
FNAME
DAVE
MARY
VU
SAL
45000.00
50000.00
65000.00
Tera-Tom Notes
39
ADD_MONTHS Command
and the SQL request uses the Primary Index, then the PEP uses the hash algorithm
and the hash map to locate the AMP that owns that record and only one AMP is
utilized. We will talk about the Primary Index and the Hash Maps in the next
couple of pages.
40
Tera-Tom Notes
ADD_MONTHS Command
The ADD_MONTHS command utilizes the date or a date
column as the first parameter and adds the number of
months as the second parameter.
Employee Table
EMP
Primary
Key
1
2
3
4
99
HIRE_DATE
LNAME
FNAME
01-10-85
02-20-90
02-30-95
04-20-99
05-06-01
JONES
SMITH
CHANG
WILSON
NULL
DAVE
MARY
VU
SUE
JIM
SAL
45000.00
50000.00
65000.00
44000.00
99000.00
EMP
1
2
3
4
99
HIRE_DATE
01-10-85
02-20-90
02-30-95
04-20-99
05-06-01
Months_Plus2
03-10-85
04-20-90
04-30-95
06-20-99
07-06-01
Tera-Tom Notes
41
IN Command
The IN command provides a list of values to the query as input. It is looked at
like a OR situation.
42
Tera-Tom Notes
IN Command
The IN OPERATOR is used in the WHERE
CLAUSE. It is also used when a column is used in a
SET OF VALUES.
Employee
EMP
Primary
Key
1
2
3
4
DEPT
LNAME
FNAME
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
SELECT
*
FROM
Employee
WHERE DEPT IN (20,30);
Two Rows Returned
EMP
3
2
Tera-Tom Notes
DEPT
30
20
LNAME
CHANG
SMITH
FNAME
Vu
Mary
SAL
65000.00
50000.00
43
Subqueries
A subquery involves two queries which are the top query and the bottom query.
The bottom query runs first. It delivers a distinct list of values that are used as
input to the top query. The Subquery fully qualifies which rows will be in the
answer set, but data selected in the subquery will NOT be in the Answer Set.
Here is another way of thinking about subqueries. It is easy to understand the IN
Operator. Here is an example:
SELECT
*
FROM
Employee
WHERE DEPT IN (20,30);
The above query will select all columns from the employee table where the DEPT
is equal to 20 or 30.
A subquery is similar except it builds the list (which was 20 or 30) on the fly. On
the following page you will notice that the bottom query asks:
SELECT DEPT from Department
WHERE Dept_name = Finance;
The DEPT that has a Dept_name = Finance is DEPT 30.
30 is passed to the top query. The top query in a sense is now asking:
SELECT * FROM EMPLOYEE
WHERE DEPT IN (30);
44
Tera-Tom Notes
Subqueries
A Subquery involves two queries. The bottom query
which is the subquery runs first. The Subquery
fully
qualifies which rows will be in the answer set, but
data selected in the subquery will NOT be in the
Answer Set.
Employee Table
EMP
DEPT
Primary
Foreign
Key
Key *
1
10
2
20
3
30
4
10
LNAME
FNAME
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
Department Table
DEPT
PK
10
20
30
40
DEPT_NAME
SALES
MARKETING
FINANCE
HUMAN RESOURCES
EMP
3
Tera-Tom Notes
DEPT
30
LNAME
CHANG
FNAME
Vu
SAL
65000.00
45
Aliasing
To give an alias is to give a column or table a new name. Once you alias a
column or a table you must use the alias throughout the SQL.
46
Tera-Tom Notes
Aliasing
You can alias a column or a table by giving them a new
name. A golden rule is that once you alias you must
use the alias throughout the SQL.
Employee Table
EMP
DEPT
Primary
Foreign
Key
Key *
1
10
2
20
3
30
4
10
LNAME
FNAME
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
LAST_NAME
SMITH
CHANG
The above Query uses LAST_NAME as an alias for
LNAME and EMP_Table as an alias for EMPLOYEE.
Notice the ORDER BY statement. It uses LAST_NAME
as the sort key. We have followed the golden rule.
Tera-Tom Notes
47
Important Note:
Notice that we have qualified the DEPT column in our query with the table name
first. Do you know why we called it E.DEPT? The reason is that the column
DEPT is in both the EMPLOYEE_TABLE AS E and DEPARTMENT_TABLE
AS D. If you dont qualify the column name when the column name exists in
both tables you will get an error message saying, Column Ambiguous.
This means the system is not sure which table you want to get the column from.
Even though the result might be the same from either table, the system still needs
you to tell it which table you want the duplicate column name to come from.
48
Tera-Tom Notes
AMP 2
Department_Table
& Employee_Table
PI
Dept
10
20
Department_Table
& Employee_Table
PI
DeptName
Sales
Mrkt
Dept
30
40
PI
DeptName
Finance
IT
PI
Emp
,E.Dept
,Name
,DeptName
FROM Employee_Table
E
,Department_Table D
WHERE
E.Dept = D.Dept
Four Rows Returned
EMP
1
2
4
3
Tera-Tom Notes
DEPT
10
10
20
30
NAME
Bo Doe
Vu Too
Jo Noe
Lu Koo
DeptName
Sales
Sales
Mrkt
Finance
49
50
Tera-Tom Notes
Emp
,E.Dept
,Name
,DeptName
FROM
Employee_Table AS E
INNER JOIN Department_Table AS D
ON
E.Dept = D.Dept
Four Rows Returned
EMP
1
2
4
3
DEPT
10
10
20
30
NAME
Bo Doe
Vu Too
Jo Noe
Lu Koo
DeptName
Sales
Sales
Mrkt
Finance
Tera-Tom Notes
51
SET Operators
The SET Operators are UNION, INTERSECT, and EXCEPT. The word MINUS
is also acceptable and it means the exact same thing as EXCEPT. SET Operators
52
Tera-Tom Notes
Set Operators
The SET Operators are UNION, INTERSECT, and
EXCEPT/MINUS.
The SET Operators are two queries that are separated by
the word UNION or INTERSECT or EXCEPT. Both
Queries run simultaneously and the answer sets are
combined eliminating
duplicates.
TableA
TableB
1
2
3
3
4
5
ANSWER
1
2
3
4
5
Tera-Tom Notes
53
54
Tera-Tom Notes
TableA
TableB
1
2
3
3
4
5
ANSWER
1
2
3
4
5
What did the above query deliver?
Tera-Tom Notes
55
Macros
Users can create macros even if they dont have PERM space because MACROS
are stored in the DATA DICTIONARY. Macros dont need privileges on
underlying tables, views, or other macros. You can have multiple SQL statements
in a macro and you can place comments inside a macro. All of the above
information is important to know.
56
Tera-Tom Notes
Macros
Users can create macros even if they dont have PERM
space because MACROS are stored in the DATA
DICTIONARY.
Macros dont need privileges on underlying
tables, views, or other macros.
Here is an example of creating a macro:
CREATE MACRO MYMAC
/* We will select everything from the employee table and
then select everything from the department table */
AS
(SELECT * FROM Employee;
SELECT * FROM Department;);
The above MACRO contains multiple
SQL
Tera-Tom Notes
57
Derived Tables
Derived tables are a fantastic way for users to create temporary tables inside their
query. Derived tables are always local to a single SQL request. They are built
dynamically using an additional SELECT within the query. The rows of the
derived table are stored in spool and discarded as soon as the query finishes. The
DD has no knowledge of derived tables. Therefore, no extra privileges are
necessary. Its space comes from the users spool space.
Example:
SELECT employee_number, dept, salary, maxsal
From EMPLOYEE_TABLE,
(SELECT max(salary) from EMPLOYEE_TABLE)
derived_tbl(maxsal);
In the example above we pulled employee_number, dept, and salary from the
employee_table. We created a derived table to get the Maxsal field. Notice how
the second query selects Max(sal) from the employee_table and places it into a
table called Derived_tbl. Inside Derived_tbl we name the column we just
selected as maxsal.
58
Tera-Tom Notes
Derived Tables
Derived tables are always local to a single SQL request
and cannot be referenced by multiple SQL statements
in a multi-statement
request.
SPOOL Space.
SELECT employee_number, dept, salary, maxsal
From EMPLOYEE_TABLE,
(SELECT max(salary) from EMPLOYEE_TABLE)
derived_tbl(maxsal);
Derived tables allow for aggregates to be used in the
WHERE clause.
A referenced
Tera-Tom Notes
59
Macros
Users can create macros even if they dont have PERM space because MACROS
are stored in the DATA DICTIONARY. Macros dont need privileges on
underlying tables, views, or other macros. You can have multiple SQL statements
in a macro and you can place comments inside a macro. All of the above
information is important to know.
60
Tera-Tom Notes
Macros
Users can create macros even if they dont have PERM
space because MACROS are stored in the DATA
DICTIONARY.
Macros dont need privileges on underlying
tables, views, or other macros.
Here is an example of creating a macro:
CREATE MACRO MYMAC
/* We will select everything from the employee table and
then select everything from the department table */
AS
(SELECT * FROM Employee;
SELECT * FROM Department;);
The above MACRO contains multiple
Tera-Tom Notes
SQL
61
What is a View?
A view can be compared to a window through which you can see selected
portions of a database. A view is used to retrieve portions of one or more tables
and/or other views.
Views look like tables; they display data in columns and rows and, in general,
may be used as if they were tables. However, only their column definitions are
stored. A view is not assembled until it is referenced by a statement. A view does
not contain data. Some operations used on tables are not valid on views, and
other operations are restricted, depending on how the view is defined.
The CREATE VIEW statement defines a view. The statement names the view
and its columns, defines a SELECT of one or more columns from one or more
underlying tables and/or views, and can include conditional expressions and
aggregate operators to limit the row retrieval.
There is information in some tables such as SALARY that employers do not want
individuals to see, but would like these individuals to have access to much of the
other information in a table. This is the purpose of views. Views do not actually
store the data, but are SQL statements that are stored in the DD/D. When the
view is selected from the system actually run the query against only the data
defined in the view against the table or tables. This provides a window into tables
that have sensitive data. Management can define what columns employees can
see and what columns they cannot.
62
Tera-Tom Notes
What is a View?
A virtual table where data is not duplicated or stored
allowing restricted access to certain columns or rows.
The definition is stored in the Data Dictionary (DD) so a
creator needs no PERM space.
Most users utilize views to access Teradata tables.
Because there can be thousands of end users utilizing
window based tools a great way to maximize
FNAME SAL
Dave XXXXX
Mary XXXXX
Vu
XXXXX
Sue
XXXXX
Tera-Tom Notes
63
Cast
Under most conditions, the data types defined and stored in a table should be
appropriate. However, sometimes it is neither convenient nor desirable to use the
defined type. That is where the CAST statement comes into play. You can use
the CAST statement to temporarily convert data into a different data type. This
allows you to compare apples to apples and oranges to oranges.
64
Tera-Tom Notes
CAST
The CAST statement stands for Convert And Store. You
can utilize CAST to change column data types
temporarily.
This example uses literals to show actual conversions, but
you can also use column names:
SELECT CAST(ABC AS CHAR(1) ) AS Alph
,CAST(128 AS CHAR(3) ) AS 128
,CAST(127 AS INTEGER ) AS Big
,CAST(151.53 AS SMALLINT) AS chop
,CAST(151.53 AS DECIMAL(3,0)) AS Round ;
ONE ROW RETURNED
ALPH
A
128 Big
128
chop
127
Round
151
152
Tera-Tom Notes
65
Traditional Subqueries
Traditional subqueries are generally read from the bottom to the top. The lowest
or bottom query is answered and the results are put to the next level of query. An
SQL statement may reference up to 16 tables or views, thus resulting in up to 16
subquery levels.
Remember some simple keys about subqueries:
66
Tera-Tom Notes
Traditional Subqueries
A subquery is two queries in one. The bottom query runs
first and delivers a list of values to the top query. The top
query uses that list for input.
Employee Table
EMP
Primary
Key
1
2
3
4
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
Department Table
DEPT
PK
10
20
30
40
DEPT_NAME
SALES
MARKETING
FINANCE
HUMAN RESOURCES
EMP
-------1
4
DEPT
--------10
10
LNAME
---------Jones
Wilson
Tera-Tom Notes
67
68
Tera-Tom Notes
DEPT
Foreign
Key *
10
20
30
50
LNAME
FNAME
SAL
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
Department Table
DEPT
PK
10
20
30
40
DEPT_NAME
SALES
MARKETING
FINANCE
HUMAN RESOURCES
EMP
-------1
2
3
DEPT
--------10
20
30
LNAME
---------Jones
Smith
Chang
Tera-Tom Notes
69
Correlated Subqueries
Correlated subqueries are processed differently from traditional subqueries. Each
row of the outer query is selected and is compared to the criteria in the subquery.
Usually, correlated subqueries involve aggregates, although they may involve
expressions and other computed columns. Correlated subqueries allow the SQL
user to write one query instead of having to write two. In the past the user would
have to write a query and build a table to run the second result against.
70
Tera-Tom Notes
Correlated Subqueries
Employee Table
EMP
Primary
Key
1
2
3
4
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
DEPT
--------10
20
30
LNAME
-----------Wilson
Smith
Chang
departments.
Tera-Tom Notes
71
72
Tera-Tom Notes
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
salary
Tera-Tom Notes
73
Insert Select
You can populate one table directly from another table with an INSERT SELECT
statement.
74
Tera-Tom Notes
Insert Select
Employee Table
EMP
Primary
Key
1
2
3
4
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
EMPXX Table
EMP
Primary
Key
1
2
3
4
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
Tera-Tom Notes
75
76
Tera-Tom Notes
DEPT
LNAME
FNAME
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
SAL
45000.00
50000.00
65000.00
44000.00
SELECT
Emp, dept, lname FROM Employee;
INSERT INTO EMPXX
EMPXX Table
EMP
Primary
Key
1
2
3
4
DEPT
LNAME
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
Tera-Tom Notes
77
SHOW Commands
The SHOW command shows the actual create statements to let the user see useful
information. This is what the user actually typed in to create the table, view, or
macro. The following syntax applies:
SHOW TABLE tablename;
(Displays the CREATE statement used for the TABLE definition)
SHOW VIEW viewname;
(Displays a VIEW definition)
SHOW MACRO macroname;
(Displays a MACRO definition)
SHOW CONTROL;
(Displays BTEQ format information)
78
Tera-Tom Notes
Show Commands
The Show Table command shows the CREATE Statement
or Data Definition Language (DDL) for a specific table.
Show Table Department;
Results:
CREATE TABLE Department, NO FALLBACK
(
DEPT
INTEGER
,DEPT_NAME CHAR(20)
)
PRIMARY INDEX (Dept)
Tera-Tom Notes
or database that
79
HELP Command
The HELP command is used to provide help with databases, tables, views, macros,
columns, indexes, statistics, and sessions. When you use help you will be able to see
help information about the table, view, etc. that you want to see. The following page
shows the help command on a table. You can then see information about the table
columns, column types, and a comment. You only see comment information if the
customer has built the comments themselves. The I, CV,CF, and D in the type
column stand for Integer, Character Variable, Character Fixed, and Decimal.
Here is the syntax for help:
HELP DATABASE databasename;
(This command shows all the tables, views, macros, and triggers in a particular
database)
HELP TABLE tablename;
(This command shows all the columns in a particular table)
HELP VIEW viewname;
(This command shows the columns in a view that are accessible)
HELP MACRO macroname;
(Shows MACRO parameters)
HELP COLUMN tablename.*;
tablename.colname;
viewname.*;
viewname.colname;
(Gives help on columns)
HELP INDEX tablename;
(Gives help on indexes of a particular table)
HELP STATISTICS tablename;
(Gives help on number or rows and duplicates, etc. You need to collect statistics on a
table to see this information)
Other helpful command that provides information including the Current Database and
Transaction Semantics: HELP SESSION;
SQL Help:
80
Tera-Tom Notes
HELP Command
The HELP command is a Teradata extension that
can be used to get information about a table, database,
view, macro, column, index or statistics.
The HELP command reports information from the Teradata
Data Dictionary.
The HELP TABLE COMMAND will show a user three
Tera-Tom Notes
Type
------I
I
CF
CV
D
Comment
---------------------EMPLOYEE NUMBER
DEPARTMENT No
Surname
First Name
Pay
81
CREATE INDEX
DROP INDEX
COLLECT STATISTICS
DROP STATISTICS
An index may be optionally named as seen in the NUSI on the opposite page
(DeptIdx). This is a good idea when the index is a composite (multi-column) index.
The name allows the index to be dropped using the name instead of repeating all the
column names.
82
Tera-Tom Notes
ORDER BY VALUES;
Tera-Tom Notes
83
NULLIF logic:
84
Tera-Tom Notes
Tera-Tom Notes
85
Aggregate Functions
Aggregate operators can be used in arithmetic expressions. An aggregate operator is
used to perform a computation for the values in a group. The group used is the entire
table unless a GROUP BY clause is specified.
Aggregates do not give you detail lines. You are getting a one-line report that shows
the SUM of the entire table. If you use the GROUP BY statement you can get a oneline report per the GROUP.
Aggregate operators are often used for reports. These are:
SUM
AVERAGE
COUNT
MINIMUM
MAXIMUM
It is legal to apply AVERAGE, MINIMUM, MAXIMUM, or COUNT to Date, but it
is not legal to do SUM(Date).
All aggregate operators can be applied to numeric data.
MIN, MAX, and COUNT operate on character as well as numeric data; MIN may be
used to return the lowest sort order of a character expression, MAX the highest.
The COUNT operator has two forms, COUNT(value) and COUNT(*). Both forms of
COUNT operate on any data type.
86
Tera-Tom Notes
Aggregate Functions
Aggregate functions are: COUNT, SUM, AVG, MAX, AND
MIN.
AGGREGATES can ONLY produce SINGLE-LINE answers.
AGGREGATE operations ignore
NULLs.
SELECT COUNT(column)
,SUM(column)
,AVG(column)
,MAX(column)
,MIN(column)
FROM table;
Tera-Tom Notes
87
GROUP BY
The GROUP BY clause of the SELECT statement groups result rows by the values in
one or more columns.
The GROUP BY clause creates summary information for a table.
Each col_name in a GROUP BY clause is the name of a column referenced in the
SELECT expression list.
When an aggregate operation (SUM, AVERAGE, MAX, MIN, or COUNT) is
specified, GROUP BY can be used to return a summary row for each group.
Aggregate operators can be used only in the SELECT expression list or in the
optional HAVING clause.
All non-aggregate groups in a SELECT expression list must be included in the
GROUP BY clause. If an ORDER BY clause is used, any group contained in the
ORDER BY clause must also be included in the GROUP BY clause.
The following page shows the GROUP BY options. The pages following will
provide examples.
88
Tera-Tom Notes
GROUP BY
The GROUP BY clause will produce aggregates by
GROUP.
Any non-aggregated attribute in a SELECT List
Sum(Sal)
---------------------180,500.00
143,000.00
268,000.00
Tera-Tom Notes
89
90
Tera-Tom Notes
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
20
30
10
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
SUM(SAL)
------------89000.00
Tera-Tom Notes
MAX(SAL)
-------------45000.00
AVG(SAL)
-------------44500.00
91
92
Tera-Tom Notes
Salary
1
2
3
4
100000
100000
100000
NULL
AVG(Salary)
-----------------100000
The reason the answer is 100000 is because aggregates
ignore nulls.
SELECT COUNT(Salary) from EMPxx;
One row returned
Count(Salary)
-------------------3
The count above was on Salary and since aggregates
ignore NULLs the answer is 3.
Tera-Tom Notes
93
94
Tera-Tom Notes
Salary
1
2
3
4
100000
100000
100000
NULL
is 4 is because the
Tera-Tom Notes
95
96
Tera-Tom Notes
Salary
1
2
3
4
100000
100000
100000
NULL
answer is 4
Tera-Tom Notes
97
98
Tera-Tom Notes
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
10
30
10
Wilson
Wilson
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
Lname
---------Wilson
Count(*)
-----------3
Tera-Tom Notes
99
100
Tera-Tom Notes
Tera-Tom Notes
101
102
Tera-Tom Notes
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
10
20
20
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
3
4
SUM(sal) by dept;
Dept
Lname
Sal
--------- ----------- ------------10
Jones
45000.00
10
Smith
50000.00
---------------------Sum(sal) 95000.00
20
Chang
20
Wilson
---------------------Sum(sal) 109000.00
65000.00
44000.00
Tera-Tom Notes
103
104
Tera-Tom Notes
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
10
20
20
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
SUM(sal),
AVG(sal) by dept;
Emp
-------1
2
Dept
Lname
Sal
--------- ----------- ------------10
Jones
45000.00
10
Smith
50000.00
---------------------Sum(sal) 95000.00
Avg(sal) 47500.00
3
4
20
Chang
20
Wilson
---------------------Sum(sal) 109000.00
Avg(sal) 54500.00
Tera-Tom Notes
65000.00
44000.00
105
106
Tera-Tom Notes
DEPT
LNAME
FNAME
SAL
Foreign
Key *
10
10
20
20
JONES
SMITH
CHANG
WILSON
DAVE
MARY
VU
SUE
45000.00
50000.00
65000.00
44000.00
SUM(sal) ;
Dept
Lname
Sal
--------- ----------- ------------10
Jones
45000.00
10
Smith
50000.00
20
Chang
65000.00
20
Wilson
44000.00
---------------------Sum(sal) 204,000.00
The WITH
Tera-Tom Notes
107
108
Tera-Tom Notes
Sales
City
50000
100000
40000
200000
State
Dayton
Dayton
Cincinnati
Cincinnati
Country
OHIO
OHIO
OHIO
OHIO
USA
USA
USA
USA
SUM(sales) BY City
With SUM(sales) BY State;
WITH
Store_no
-------------1
2
Sales
City
--------- ----------50000
Dayton
100000 Dayton
State
------------Ohio
Ohio
40000
200000
Cincinnati
Cincinnati
Ohio
Ohio
Tera-Tom Notes
109
110
Tera-Tom Notes
Dept
10
10
10
20
Lname
Sal
Smith
Jones
Wilson
Lane
50000
40000
100000
50000
Mgr
Y
N
N
Y
SELECT WRKS.Emp
,WRKS.Dept
,WRKS,Lname
,WRKS.Sal
,MGRS.Lname
,MGRS.Sal
From
Employee WRKS
,Employee MGRS
WRKS and
MGRS.
Tera-Tom Notes
111
Characters Functions
The Characters function works with Varchar data types and returns the length of
the column. The following page shows and excellent example.
112
Tera-Tom Notes
Characters Function
Employee Table
Emp
1
2
3
4
Dept
10
10
10
20
Lname
Sal
Smith
Jones
Wilson
Lane
50000
40000
100000
50000
Mgr
Y
N
N
Y
SELECT
Lname
/* A VARCHAR 20 Column */
,CHARACTERS(Lname) AS Name_Length
FROM Employee;
Lname
Name_Length
------------- -------------------Smith
5
Jones
5
Wilson
6
Lane
4
Tera-Tom Notes
113
Trim
The TRIM function is used to eliminate either leading, trailing spaces or both
leading and trailing spaces from character data.
The following are the four different syntax options for the TRIM function:
TRIM( TRAILING FROM <column-name> )
/* Trims only spaces stored after all text characters
TRIM( LEADING FROM <column-name> )
/* Trims only spaces stored before all text characters
*/
*/
114
/* defaults to BOTH
Tera-Tom Notes
*/
Trim
The TRIM function is used to eliminate either leading,
trailing spaces or both leading and trailing spaces from
character data.
The following are the four different syntax options for the TRIM function:
TRIM( TRAILING FROM <column-name> )
/* Trims only spaces stored after all text characters
TRIM( LEADING FROM <column-name> )
/* Trims only spaces stored before all text characters
*/
*/
/* defaults to BOTH
*/
PAD
Example:
Select Trim( ABCDE )
Results: ABCDE
The leading and trailing spaces have been trimmed.
Tera-Tom Notes
115
116
Tera-Tom Notes
Tera-Tom Notes
117
Unique Constraint
The UNIQUE constraint is used to enforce uniqueness of values stored within the
column(s). This means that no two rows in the table can have the same value for
the column or columns utilizing the UNIQUE constraint.
118
Tera-Tom Notes
UNIQUE Constraint
The UNIQUE constraint is used to enforce uniqueness of
values stored within the column(s).
No two rows in the table can have the same value for the
column or columns utilizing the UNIQUE constraint.
CREATE TABLE Employee
(Emp
Integer NOT
NULL
Tera-Tom Notes
119
Compress
Compressing a column value can save valuable disk space. The compress allows
you to specify a value in a column and not store that value. The value is stored in
the table header. For example, you might have a State in your database like
CALIFORNIA. Because your business is located in California most of the values
in your database have a state code of CALIFORNIA. You can compress the
value CALIFORNIA and instead of storing it on the disk for almost every row
you can compress the value.
There are some trade offs with compress. While compression greatly reduces the
amount of storage space required, it increases the processing overhead whenever
a compressed column is accessed because the location of the data must be
computed on the fly.
Most of the time you can compress up to about 5 columns in a table before you
start to see performance impacts.
A Volatile Table does not support compression.
120
Tera-Tom Notes
Compress
Compressing a column value can save valuable disk
space. The compress allows you to specify a value in a
column and not
header.
Tera-Tom Notes
121
Substring
The SUBSTRING function is used to extract a portional character string from
character data. The following page shows some examples.
122
Tera-Tom Notes
Substring
Substring extracts a substring from a named string based
on position.
The Substring function will be performed on a string
expression. The expression can be a column value or a
literal.
You will describe the starting position of the substring and
the length of the substing to be extracted from the string
expression.
This example uses literals:
SELECT SUBSTRING(Hello FROM 2 FOR 3) AS S1
, SUBSTRING(Hello FROM 2) AS S2 ;
One row returned
S1
ell
S2
ello
Tera-Tom Notes
123
- Result = 3
The newer ANSI standard code for this function is POSITION. Its functionality
is exactly the same as INDEX, however it is written differently. The following
would return 3 due to the c being the third character in the string:
POSITION(c IN abcdef)
- Result = 3
124
Tera-Tom Notes
SELECT Lname
,POSITION( e IN lname )
FROM EMPxx ;
Using the following three names, the results of the
POSITION function are:
Lname
Jones
Davis
Marley
Tera-Tom Notes
POSITION( e IN lname )
4
0
5
125
UPDATE
The UPDATE command updates a table. This can be done through a view or a
self-join also.
For an UPDATE to a table the user must have UPDATE privileges. As a matter
of fact the user must also have READ privileges on the table being updated.
The following page shows the syntax.
126
Tera-Tom Notes
Update
The UPDATE command updates a table. This can be
done through a view or a self-join also.
For an UPDATE to a table the user must have
Tera-Tom Notes
127
Creating a Table
The CREATE TABLE statement is used to create a new table. The Primary
Index is specified at TABLE CREATE time.
Each column in the table can have a definition set. This means that each column
defines the data type definition. This follows the column name.
128
Tera-Tom Notes
Creating a Table
The CREATE TABLE statement is used to create a new
table. The Primary Index is specified at TABLE CREATE
time.
Each column in the table can have a definition set.
This means that each column defines the data type
definition. This follows the column name
Create Table EmpXX
(
emp
Integer
,dept
Integer
,lname
Char(20)
,fname
Char(20)
,Sal
Decimal (10,2)
)
Unique Primary Index (emp);
Tera-Tom Notes
129
130
Tera-Tom Notes
CASE <column-name>
WHEN <value1> THEN <true-result1>
WHEN <value2> THEN <true-result2>
WHEN <valueN> THEN <true-resultN>
[ ELSE <false-result> ]
END
Example
SELECT
Course_Name
,CASE Credits
WHEN 1 THEN 1 Credit
WHEN 2 THEN 2 Credits
WHEN 3 THEN 3 Credits
ELSE More than 3 Credits
END
Number of Credits
FROM Course_table
ORDER BY credits, 1;
Course_name
Logical Database Design
V2R3 SQL Features
Advanced SQL
Tera-Tom Notes
Number of Credits
2 Credits
2 Credits
3 Credits
131
132
Tera-Tom Notes
Tera-Tom Notes
133
COALESCE Option
The COALESCE option will allow you to have options to manipulate nulls.
A situation where COALESCE can help, relates to the use of aggregates, in
particular the AVG function. Since aggregates ignore NULLs in the data, the
average using NULL will be a higher result then when a zero is used. If the
NULL was intended to represent a zero, the result will be incorrect. The
COALESCE can convert the NULL values to zero and use them in the aggregate.
Another use for situation is when there is a potential for a column to contain a
NULL. Then, when it is a NULL another column is to be used to return its value.
The COALESE will continue to look at columns or values until it finds a nonNULL and it will be returned. However, if all of the values checked contain
NULL, it has no choice but to return a NULL.
The following page gives some examples of using the logic.
134
Tera-Tom Notes
COALESCE Option
Coalesce will pick the first non-null value in a list. If every
value in the list is NULL then Coalesce will return NULL.
Think of Coalesce another way:
Tera-Tom Notes
Phone
--------------------(513) 300-0341
No Phone
(643) 888-3939
135
Distinct Option
The Distinct option eliminates duplicate values in an answer set. The number of
expressions used as the argument for an aggregate has unlimited arguments.
136
Tera-Tom Notes
Distinct Operator
The Distinct option eliminates duplicate values in
an answer set. The number of expressions used as the
argument for an aggregate has unlimited
expressions.
Example:
SELECT DISTINCT Class_code
FROM student_table
ORDER BY class_code;
Class_code
FR
JR
SO
SR
Tera-Tom Notes
137
138
Tera-Tom Notes
Dept
10
10
10
20
Lname
Sal
Smith
Jones
Wilson
Lane
0
40000
NULL
50000
SELECT Salary
,NULLIFZERO(Salary) As NOZERO
,ZEROIFNULL(Salary) AS NONULL
FROM Employee;
SALARY
-------------0
40000
NULL
50000
Tera-Tom Notes
NOZERO
-------------NULL
40000
NULL
50000
NONULL
-------------0
40000
0
50000
139
SQL Flag
The SQLFLAG command enables or disables the SQL Flagger. The SQL Flagger
generates a warning message when nonstandard SQL is used.
The SQL Flag will display NON-ANSI SQL. The SQL FLAG can be set to:
FULL
INTERMEDIATE
NONE
ENTRY
Remember the letters FINE. They stand for FULL, INTERMEDIATE, NONE,
AND ENTRY.
140
Tera-Tom Notes
SQL Flag
The SQLFLAG command enables or disables the SQL
Flagger. The SQL Flagger generates a warning message
when nonstandard SQL is used.
The SQL Flag will display NON-ANSI SQL. The SQL
FLAG can be set to:
FULL
INTERMEDIATE
NONE
ENTRY
Remember the letters FINE. They stand for FULL,
INTERMEDIATE, NONE, AND ENTRY.
Tera-Tom Notes
141
142
Tera-Tom Notes
01
02
03
04
05
06
Mason
Doctor
Lawyer
Teacher
Nurse
Baker
EmpXX Table
8888
9333
8854
8121
0043
4320
01
01
03
04
01
06
Skill Skill
Emp
Skill
No
No
SELECT Skills.skill, EmpXX.emp
FROM Skills LEFT OUTER JOIN empxx
ON skills.skillno = Empxx.Skillno;
Outer Join Results
Mason
Mason
Mason
Doctor
Lawyer
Teacher
Nurse
Baker
Tera-Tom Notes
8888
9333
0043
NULL
8854
8121
NULL
4320
143
144
Tera-Tom Notes
01
02
03
04
05
06
Mason
Doctor
Lawyer
Teacher
Nurse
Baker
EmpXX Table
8888
9333
8854
8121
0043
4320
01
01
03
04
07
06
Skill Skill
Emp
Skill
No
No
SELECT Skills.skill, EmpXX.emp
FROM Skills Right OUTER JOIN EmpXX
ON skills.skillno = Empxx.skillno;
Outer Join Results
Mason
Mason
Lawyer
Teacher
Baker
NULL
Tera-Tom Notes
8888
9333
8854
8121
4320
0043
145
146
Tera-Tom Notes
01
02
03
04
05
06
Skill
No
Mason
Doctor
Lawyer
Teacher
Nurse
Baker
Skill
EmpXX Table
8888
9333
8854
8121
0043
4320
01
01
03
04
07
06
Emp
Skill
No
Mason
Mason
Doctor
Lawyer
Teacher
Nurse
Baker
NULL
Tera-Tom Notes
8888
9333
NULL
8854
8121
NULL
4320
0043
147