Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Teradata SQL
Certification
Tera-Tom Notes 1
First Edition 2001
Teradata, NCR, and BYNET are registered trademarks of NCR Corporation, Dayton,
Ohio, U.S.A., IBM and DB2 are registered trademarks of IBM Corporation, ORACLE is a
registered trademark of Oracle, SYBASE is a registered trademark of SYBASE, ANSI is a
registered trademark of the American National Standards Institute. In addition to these products
names, all brands and product names in this document are registered names or trademarks of
their respective holders.
Coffing Data Warehousing shall have neither liability nor responsibility to any person or entity
with respect to any loss or damages arising from the information contained in this book or from
the use of programs or program segments that are included. The manual is not a publication of
NCR Corporation, nor was it produced in conjunction with NCR Corporation.
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or
transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise,
without written permission from the publisher. No patent liability is assumed with respect to the
use of information contained herein. Although every precaution has been taken in the
preparation of this book, the publisher and author assume no responsibility for errors or
omissions, neither is any liability assumed for damages resulting from the use of information
contained herein. For information, address:
Coffing Publishing
7810 Kiester Rd.
Middletown, OH 45042
All terms mentioned in this book that are known to be trademarks or service have been stated.
Coffing Publishing cannot attest to the accuracy of this information. Use of a term in this book
should not be regarded as affecting the validity of any trademark or service mark.
Tera-Tom Notes 3
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
Tera-Tom Notes 5
6 Tera-Tom Notes Copyright OSS 2001
Module 1
A A A A
M M M M
P P P P
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Tera-Tom Notes 7
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 9
A Table has Rows and Columns
In yesterdays programming languages we referred to files, records, and fields.
This is replaced in SQL and relational databases as tables, rows, and columns.
Data is stored in the Teradata DBS according to the relational model, which is
based on tables with rows and columns. Each row of a table is composed of a
number of fields identified by column name. Each field contains a data item with
a single data type.
A row is the smallest unit that can be inserted into, or deleted from, a relational
table. Rows can be inserted interactively or automatically. When building a new
database, you can use one of the load utilities (for example, FastLoad) to populate
several large tables automatically. You modify the contents of a table by
inserting rows into, deleting rows from the table, or updating (changing) row data.
Tera-Tom Notes 11
Retrieving Data From A Table
To retrieve data from a table you will primarily use four key words. They are:
SELECT
FROM
WHERE
ORDER BY
At a minimum you must use the keywords SELECT and FROM. Lets talk about
all of these.
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 don’t use a WHERE clause then all rows from the table will be returned.
ORDER BY: The ORDER BY statement sorts the data. If you don’t use the
ORDER BY statement then the data comes back in random order.
To retrieve data from a table users use the four key words
SELECT, FROM, WHERE, and ORDER BY.
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.
Tera-Tom Notes 13
Example of Selecting Data From A Table
In the example on the following page we have SELECTed three columns.
Remember that after the word SELECT we will list the columns we want to
retrieve. A comma separates each column requested. After the FROM clause is
the table in which the data resides.
SELECT emp
,dept
,lname
FROM Employee;
Tera-Tom Notes 15
Example of Selecting All Columns in a table
In the example on the following page we have SELECTed all columns in the
table. The * represents all columns. Remember that after the word SELECT we
will list the columns we want to retrieve and the * means every column. After
the FROM clause is the table in which the data resides.
SELECT *
FROM Employee;
Tera-Tom Notes 17
Example of Selecting Only Certain Rows
In the example on the following page we have SELECTed all columns in the
table, but have limited the number of rows returned. This is done with the
WHERE clause. The WHERE clause will decide what rows are returned. In our
example we have asked for only the rows where the DEPT equals 10. We have
two rows returned.
SELECT *
FROM Employee
WHERE Dept = 10;
Tera-Tom Notes 19
Example of Sorting the Data
In the example on the following page we have SELECTed all columns in the table
and all rows. We have also sorted the data by using the ORDER BY clause.
SELECT *
FROM Employee
ORDER BY LNAME;
Tera-Tom Notes 21
Checking for NULL Data
NULL data is data that is an undetermined value. It is not zeros and it is not
spaces, but undetermined. Because NULL data is undetermined you cannot check
for it with an equality statement. For example, if you were to write:
SELECT *
FROM Employee
WHERE DEPT = NULL;
You would never get rows to return because you can’t check to see if an
undetermined value is equal to something.
To check if a value is NULL you can only use two statements. They are:
IS NULL
IS NOT NULL
Employee Table
EMP DEPT LNAME FNAME SAL
Primary
Key
1 10 JONES DAVE 45000.00
2 20 SMITH MARY 50000.00
3 30 CHANG VU 65000.00
4 10 WILSON SUE 44000.00
99 NULL NULL JIM 99000.00
Tera-Tom Notes 23
Examples of NULL Data
In the examples on the following page you will notice that no data is ever
returned when we check to see if something is equal to NULL. Data is returned
however when we use either the IS NULL or IS NOT NULL commands.
EMP FNAME
99 JIM
Tera-Tom Notes 25
How Sorting Works with NULL Data
NULL data sorted in Ascending Order will always be before all positive and
negative values and before blank values.
SELECT EMP
,DEPT
FROM EMPLOYEE
ORDER BY Dept;
Five Rows Returned
EMP DEPT
99 NULL
1 10
4 10
2 20
3 30
Tera-Tom Notes 27
AND, OR, and NOT
The Order of Precedence is NOT, AND, and then OR. One way to remember this
is that NOT comes first. After that it is done by alphabetic order. AND comes
before OR because A comes before O.
You can change the order of precedence with parenthesis. Parenthesis are always
read first. If there are multiple parenthesis then they are evaluated from left to
right.
Employee Table
EMP DEPT LNAME FNAME SAL
Primary
Key
1 10 JONES DAVE 45000.00
2 20 SMITH MARY 50000.00
3 30 CHANG VU 65000.00
4 10 WILSON SUE 44000.00
99 NULL NULL JIM 99000.00
SELECT EMP
,DEPT
,FNAME
FROM EMPLOYEE
WHERE Dept = 10
AND Dept = 20
OR Sal > 80000.00;
One Row Returned
EMP DEPT FNAME
99 NULL 99000.00
IN the above example the only thing that comes back is
anyone making a SAL over 80000.00.
Tera-Tom Notes 29
Valid Table Names
Teradata allows you to name tables anyway you want as long as you follow the
rules. Here are the rules:
No two databases or users may have the same name in the entire system.
No two tables in the same database or user may have the same name.
No two columns in the same table may have the same name.
• Integers
Tera-Tom Notes 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.
Sel ABS(-1.2)
One Row Returned
1.2
Sel ABS(-8.1)
One Row Returned
8.1
Tera-Tom Notes 33
The Extract Function
The extract function allows you to extract date information from a date field.
Employee Table
EMP HIRE_DATE LNAME FNAME SAL
Primary
Key
1 01-10-85 JONES DAVE 45000.00
2 02-20-90 SMITH MARY 50000.00
3 02-30-95 CHANG VU 65000.00
4 04-20-99 WILSON SUE 44000.00
99 05-06-01 NULL JIM 99000.00
SELECT *
FROM Employee
WHERE EXTRACT(month from HIRE_DATE) = 5;
Tera-Tom Notes 35
The Date Function
The DATE function allows you to select the DATE.
Employee Table
EMP HIRE_DATE LNAME FNAME SAL
Primary
Key
1 01-10-85 JONES DAVE 45000.00
2 02-20-90 SMITH MARY 50000.00
3 02-30-95 CHANG VU 65000.00
4 04-20-99 WILSON SUE 44000.00
99 05-06-01 NULL JIM 99000.00
YRS_OF_SERVICE
17
12
7
3
1
Tera-Tom Notes 37
The Between Statement
The BETWEEN statement is used in the where clause to retrieve rows that are
between a certain value. The BETWEEN statement is inclusive. If you asked if
X was BETWEEN Y and Z the logic would be:
Employee Table
EMP HIRE_DATE LNAME FNAME SAL
Primary
Key
1 01-10-85 JONES DAVE 45000.00
2 02-20-90 SMITH MARY 50000.00
3 02-30-95 CHANG VU 65000.00
4 04-20-99 WILSON SUE 44000.00
99 05-06-01 NULL JIM 99000.00
SELECT *
FROM Employee
WHERE SAL BETWEEN 45000.00 AND 65000.00;
Three Rows Returned
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.
Employee Table
EMP HIRE_DATE LNAME FNAME SAL
Primary
Key
1 01-10-85 JONES DAVE 45000.00
2 02-20-90 SMITH MARY 50000.00
3 02-30-95 CHANG VU 65000.00
4 04-20-99 WILSON SUE 44000.00
99 05-06-01 NULL JIM 99000.00
Sel Add_months(Hire_Date, 12 * 5)
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.
SELECT *
FROM Employee
WHERE DEPT IN (20,30);
Tera-Tom Notes 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.
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:
30 is passed to the top query. The top query in a sense is now asking:
Department Table
DEPT DEPT_NAME
PK
10 SALES
20 MARKETING
30 FINANCE
40 HUMAN RESOURCES
Tera-Tom Notes 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.
Tera-Tom Notes 47
Joining Two Tables Using Teradata Syntax
A join allows you to select columns and rows from two or more tables and views.
Up to 64 tables and views may be joined. An inner join selects data from two or
more tables or views. Each source must be named and the join condition, the
common relationship between the tables or views to be joined, specified in a
WHERE clause.
Remember, The key to joins is in the WHERE or ON clause. When you are
joining information from two tables you will be SELECTing fields from both
tables. To do this you are joining together information from two separate rows
from two separate tables. That means you must match the two rows from the
different tables. The match will usually occur where there is a PRIMARY KEY
and a FOREIGN KEY relationship. This is because this was how the tables were
logically defined. The FOREIGN KEY from one table is a PRIMARY KEY in
another table
The following page uses an SQL statement that utilizes information from both the
employee table and department table. This is a classic two-table join. The query
is looking for columns from both tables.
We have listed both syntax options. The first is the Teradata Join Syntax and the
second is the ANSI Join Syntax.
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 don’t 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.
AMP 1 AMP 2
Department_Table Department_Table
& Employee_Table & Employee_Table
PI PI
Dept DeptName Dept DeptName
10 Sales 30 Finance
20 Mrkt 40 IT
PI PI
Emp Dept Name Salary Emp Dept Name Salary
1 10 Bo Doe 50000 2 10 Vu Too 60000
4 20 Jo Noe 60000 3 30 Lu Koo 70000
Tera-Tom Notes 49
Joining Two Tables Using ANSI Syntax
A join allows you to select columns and rows from two or more tables and views.
Up to 64 tables and views may be joined. An inner join selects data from two or
more tables or views. Each source must be named and the join condition, the
common relationship between the tables or views to be joined, specified in a
WHERE clause.
Remember, The key to joins is in the WHERE or ON clause. When you are
joining information from two tables you will be SELECTing fields from both
tables. To do this you are joining together information from two separate rows
from two separate tables. That means you must match the two rows from the
different tables. The match will usually occur where there is a PRIMARY KEY
and a FOREIGN KEY relationship. This is because this was how the tables were
logically defined. The FOREIGN KEY from one table is a PRIMARY KEY in
another table
The following page uses an SQL statement that utilizes information from both the
employee table and department table. This is a classic two-table join. The query
is looking for columns from both tables.
We have listed both syntax options. The first is the Teradata Join Syntax and the
second is the ANSI Join Syntax.
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
1 3
2 4
3 5
SELECT * FROM TableA Title ‘ANSWER’
UNION
SELECT * FROM TableB;
ANSWER
1
2
3
4
5
Tera-Tom Notes 53
SET Operators Continued
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
TableA TableB
1 3
2 4
3 5
ANSWER
1
2
3
4
5
Tera-Tom Notes 55
Macros
Users can create macros even if they don’t have PERM space because MACROS
are stored in the DATA DICTIONARY. Macros don’t 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.
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:
Tera-Tom Notes 59
Macros
Users can create macros even if they don’t have PERM space because MACROS
are stored in the DATA DICTIONARY. Macros don’t 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.
Tera-Tom Notes 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.
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.
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.
Department Table
DEPT DEPT_NAME
PK
10 SALES
20 MARKETING
30 FINANCE
40 HUMAN RESOURCES
Tera-Tom Notes 67
Traditional Subqueries Continued
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.
Department Table
DEPT DEPT_NAME
PK
10 SALES
20 MARKETING
30 FINANCE
40 HUMAN RESOURCES
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.
Tera-Tom Notes 71
How Correlated Subqueries Work
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 use a shared
spool technique that can speed up processing.
The following page shows a typical correlated subquery. The subquery executes
by:
2. Gets the max salary for the deptxx from the subquery
Tera-Tom Notes 73
Insert Select
You can populate one table directly from another table with an INSERT SELECT
statement.
Tera-Tom Notes 75
Insert Select Continued
You can populate one table directly from another table with an INSERT SELECT
statement. If the two tables have the same number of columns and compatible
data types you can say:
The key here is the SELECT * FROM OLD_TABLE. This takes each column
and row from the OLD_TABLE and INSERTS them into the new table.
SELECT
INSERT INTO EMPXX
Emp, dept, lname FROM Employee;
EMPXX Table
EMP DEPT LNAME
Primary Foreign
Key Key *
1 10 JONES
2 20 SMITH
3 30 CHANG
4 10 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 CONTROL;
(Displays BTEQ format information)
Results:
Tera-Tom Notes 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.
Other helpful command that provides information including the Current Database and
Transaction Semantics: HELP SESSION;
Tera-Tom Notes 81
CREATE a Secondary INDEX
Primary indexes are created with a CREATE table statement. Secondary indexes can
also be made during the CREATE table statement or can be made at a later time.
Indexes can be unique or non-unique. If you create a unique index then that column
will not allow duplicates.
Secondary indexes can improve system performance; note however, that creating a
secondary index causes the Teradata DBS to build a separate internal subtable.
A secondary index is a subtable that is stored separately from the primary table. Each
subtable row contains a secondary index value, plus one or more row identifiers (IDs)
that point to the primary table row(s) containing that value.
Secondary indexes are optional. You can define one or more secondary indexes in
the CREATE TABLE statement, or add them to an existing table using the CREATE
INDEX statement.
An index may be given a name. This allows several table, index, and statistical
statements to address indexes by their assigned names.
The Teradata SQL statements that may reference named indexes are:
• 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.
Tera-Tom Notes 83
The NULLIF Command
The NULLIF command is an ANSI compliant command that compares two values.
IF the values are equal then the result will be NULL. If the values are not equal then
the result will be the first value in the list.
SELECT NULLIF(0,0);
The result is NULL. This is because the two values in the list are equal.
SELECT NULLIF(3,0);
The result is 3. This is because the two values in the list are not equal. Thus
Teradata returns the first value in the list.
IF the values are equal then the result will be NULL. If the
values are not equal then the result will be the first value
in the list.
SELECT NULLIF(0,0);
SELECT NULLIF(3,0);
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 one-
line report per the GROUP.
SUM
AVERAGE
COUNT
MINIMUM
MAXIMUM
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.
AVG(Salary)
------------------
$50,000
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 following page shows the GROUP BY options. The pages following will
provide examples.
Dept Sum(Sal)
------ ----------------------
001 180,500.00
002 143,000.00
003 268,000.00
Tera-Tom Notes 89
GROUP BY and HAVING Conditions
The GROUP BY and HAVING conditions are often used to group and select via a
criteria. The following page will look at each department and select totals from the
departments that have an average salary of over 40000000.
Tera-Tom Notes 91
Some Aggregate examples
The following page shows examples of aggregates.
AVG(Salary)
------------------
100000
Count(Salary)
--------------------
3
Tera-Tom Notes 93
Some Aggregate examples Continued
The following page shows examples of aggregates.
COUNT(*)
------------------
4
Tera-Tom Notes 95
Some Aggregate examples Continued
The following page shows examples of aggregates.
COUNT(*)
------------------
4
The reason the answer is 4 is because the COUNT(*) counts the entire
row. Since the entire row is not NULL the count is 4.
Tera-Tom Notes 97
Advanced Aggregate example
The following page shows examples of aggregates.
Tera-Tom Notes 99
Using WITH… BY for Subtotals
The following page lists the fundamentals for the WITH…BY command.
Note: These commands may not work with Queryman and other ODBC related
tools. These are report writing features, BTEQ is a report writer.
WITH…By:
• Is a Teradata extension
The WITH….BY performs a sort to put all the same values of the BY column
together for display and aggregation. The multiple WITH…BY subtotals may be
requested in the same SELECT. When this is done, the last WITH…BY is the major
sort.
The ORDER BY can be used with a WITH…BY. When it is used, it is the most
minor sort sequence.
Empxx Table
EMP DEPT LNAME FNAME SAL
Primary Foreign
Key Key *
1 10 JONES DAVE 45000.00
2 10 SMITH MARY 50000.00
3 20 CHANG VU 65000.00
4 20 WILSON SUE 44000.00
3 20 Chang 65000.00
4 20 Wilson 44000.00
----------------------
Sum(sal) 109000.00
Empxx Table
EMP DEPT LNAME FNAME SAL
Primary Foreign
Key Key *
1 10 JONES DAVE 45000.00
2 10 SMITH MARY 50000.00
3 20 CHANG VU 65000.00
4 20 WILSON SUE 44000.00
3 20 Chang 65000.00
4 20 Wilson 44000.00
----------------------
Sum(sal) 109000.00
Avg(sal) 54500.00
Empxx Table
EMP DEPT LNAME FNAME SAL
Primary Foreign
Key Key *
1 10 JONES DAVE 45000.00
2 10 SMITH MARY 50000.00
3 20 CHANG VU 65000.00
4 20 WILSON SUE 44000.00
SELECT WRKS.Emp
,WRKS.Dept
,WRKS,Lname
,WRKS.Sal
,MGRS.Lname
,MGRS.Sal
From Employee WRKS
,Employee MGRS
WHERE MGRS.dept = WRKS.dept
AND MGRS.Mgr = ‘Y’
AND WRKS.Sal > MGRS.Sal ;
Lname Name_Length
------------- --------------------
Smith 5
Jones 5
Wilson 6
Lane 4
The following are the four different syntax options for the TRIM function:
Example:
Results: ABCDE
No two rows in the table can have the same value for the
column or columns utilizing the UNIQUE constraint.
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.
S1 S2
ell ello
The INDEX function returns a number that represents the location of one or more
characters in a string when compared to the second string. The following would
return 3 due to the ‘c’ being the third character in the string:
INDEX(‘abcdef’,’c’) - 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:
The page also shows the exact same operation using the CASE as an alternative.
SELECT Lname
,POSITION( ‘e’ IN lname )
FROM EMPxx ;
Using the following three names, the results of the
POSITION function are:
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.
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.
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;
Grade_Point_Average
High Decimal value
4.0 GPA
High Decimal value
4.0 GPA
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 non-
NULL and it will be returned. However, if all of the values checked contain
NULL, it has no choice but to return a NULL.
Name Phone
--------------- ---------------------
Jim Blue (513) 300-0341
Jane Green No Phone
Bill Davis (643) 888-3939
Class_code
FR
JR
SO
SR
SELECT Salary
,NULLIFZERO(Salary) As NOZERO
,ZEROIFNULL(Salary) AS NONULL
FROM Employee;
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.
FULL
INTERMEDIATE
NONE
ENTRY
Remember the letters FINE. They stand for FULL,
INTERMEDIATE, NONE, AND ENTRY.
LEFT OUTER - Left means the first table listed in the FROM clause. The rows
from the left table that are not returned in the result of the inner join of the tables
be included in the result, but contain NULLs in the rows with no match.
The type of outer join (in this case, left), specified by the keyword LEFT indicates
the source of the rows not returned in the result of the inner join. These are called
non-matching rows. The other outer join types are right and full, specified by the
key words RIGHT and FULL.
Nulls:
The key feature of the outer join is that in returning rows from the "left" join
table, the "right" join table, or both tables, the outer join extends the rows that
have no matching values with nulls, as if these values came from the
corresponding table.
01 Mason 8888 01
02 Doctor 9333 01
03 Lawyer 8854 03
04 Teacher 8121 04
05 Nurse 0043 01
06 Baker 4320 06
Skill Skill Emp Skill
No No
SELECT Skills.skill, EmpXX.emp
FROM Skills LEFT OUTER JOIN empxx
ON skills.skillno = Empxx.Skillno;
Mason 8888
Mason 9333
Mason 0043
Doctor NULL
Lawyer 8854
Teacher 8121
Nurse NULL
Baker 4320
RIGHT OUTER - Right means the second table listed in the FROM clause. The
rows from the right table that are not returned in the result of the inner join of the
tables be included in the result, but contain NULLs in rows with no match.
The type of outer join (in this case, right), specified by the keyword RIGHT
indicates the source of the rows not returned in the result of the inner join. These
are called non-matching rows. The other outer join types are left and full,
specified by the key words LEFT and FULL.
Nulls:
The key feature of the outer join is that in returning rows from the "right" join
table, the "left" join table, or both tables, the outer join extends the rows that have
no matching values with nulls, as if these values came from the corresponding
table.
01 Mason 8888 01
02 Doctor 9333 01
03 Lawyer 8854 03
04 Teacher 8121 04
05 Nurse 0043 07
06 Baker 4320 06
Skill Skill Emp Skill
No No
SELECT Skills.skill, EmpXX.emp
FROM Skills Right OUTER JOIN EmpXX
ON skills.skillno = Empxx.skillno;
Mason 8888
Mason 9333
Lawyer 8854
Teacher 8121
Baker 4320
NULL 0043
FULL OUTER - Rows from both tables that have not been returned in the result
of the inner join will be returned in the outer join result and extended with NULL
values.
01 Mason 8888 01
02 Doctor 9333 01
03 Lawyer 8854 03
04 Teacher 8121 04
05 Nurse 0043 07
06 Baker 4320 06
Skill Skill Emp Skill
No No
SELECT Skills.skill, Empxx.emp
FROM Skills FULL OUTER JOIN EmpXX
ON skills.skillno = Empxx.skillno;
Mason 8888
Mason 9333
Doctor NULL
Lawyer 8854
Teacher 8121
Nurse NULL
Baker 4320
NULL 0043