Tera-Cram for Teradata SQL Certification

Tera-Tom Notes

1

First Edition 2001 Written by Tom Coffing III Web Page: www.Tera-Tom.com E-Mail addresses: Tom: Tcoffing3@aol.com
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. Copyright 2001 by Coffing Publishing 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 International Standard Book Number: ISBN 0-9704980-3-9

Printed in the United States of America
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.

2

Tera-Tom Notes

Copyright OSS 2001

Acknowledgements and Special Thanks
This book is dedicated the Coffing Data warehousing team. Tom Coffing Jr. Morgan Jones Mike Larkins Jamar Boyd Randy Volters Chris Coffing Robert Hines Gareth Walter Steve Wilmes Todd Carroll Tom Coffing Sr. Leona Coffing Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Master Teradata Certified Professional

Tera-Tom Notes

3

......................... and NOT ..............................................36 The Between Statement ........................................78 HELP Command..44 Aliasing...........................................................................8 A Table has Rows and Columns................................92 4 Tera-Tom Notes Copyright OSS 2001 ......................................................................................................Table of Contents Module 1 – Teradata Basics .........................................................................64 Traditional Subqueries.............................................................74 Insert Select Continued..................46 Joining Two Tables Using Teradata Syntax.........................16 Example of Selecting Only Certain Rows .....................................................................................................................................................................38 ADD_MONTHS Command ..........26 AND..................................20 Checking for NULL Data .........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................54 Macros .................................................................................................................................................................32 The Extract Function ...............................58 Macros .......................................30 Absolute Function...................................................62 Cast ..................................................................................................................56 Derived Tables...............................................................................................................................................................80 CREATE a Secondary INDEX.......................................................................................52 SET Operators Continued.........................................................................................................................................................................................................................................................................................................12 Example of Selecting Data From A Table.........................................................................................76 SHOW Commands ............................................................................................................................22 Examples of NULL Data .........................................14 Example of Selecting All Columns in a table.............................................................................18 Example of Sorting the Data..................82 The NULLIF Command .....................................................60 What is a View?.................................24 How Sorting Works with NULL Data.....34 The Date Function ................................................7 Introduction .................................... OR...........................................................................................10 Retrieving Data From A Table ..........................................................28 Valid Table Names ....40 IN Command ...............................................................................................84 Aggregate Functions.....................................................................................................................................................68 Correlated Subqueries..............................................................................70 How Correlated Subqueries Work......................................66 Traditional Subqueries Continued ......................90 Some Aggregate examples .......................42 Subqueries.....48 Joining Two Tables Using ANSI Syntax......................................86 GROUP BY ..................72 Insert Select ....88 GROUP BY and HAVING Conditions ...................................................................................................................................................................................50 SET Operators ........................................................................................................................................................................................

........................................................................................................................................................................................Some Aggregate examples Continued ..................................................................................................................... 122 INDEX and POSITION functions .................... 132 COALESCE Option ........................................................................................................... 100 Creating a Report Using WITH …BY........................................................ 108 What type of join is this? .......................................................................................................................................................................................................................................................... 98 Using WITH… BY for Subtotals..... 120 Substring . 126 Creating a Table ......... 94 Some Aggregate examples Continued ..................... 96 Advanced Aggregate example ........................................................................................................................................................................................................................................................................................................................................................................................................................................ 116 Unique Constraint ................. 102 WITH …BY Multiple Aggregates............................ 140 Left Outer Join .................................................................................................................................................... 112 Trim............................................................... 130 CASE Statement (Option 2)....................................................... 114 Trim and Characters Combined .................................................. 104 WITH for a final total ...................... 118 Compress........................................................................... 134 Distinct Option..................................... 136 NULLIFZERO and ZEROIFNULL..................................................................................................... 110 Characters Functions............ 124 UPDATE ....................................... 128 CASE Statement (Option 1).......................................................................................................................................................... 146 Tera-Tom Notes 5 ............................................................................................................................... 138 SQL Flag ....................... 144 Full Outer Join ...................................... 142 Right Outer Join ................................................................................. 106 Multiple WITH BY Statements .............................................................................................

6 Tera-Tom Notes Copyright OSS 2001 .

Module 1 Module 1 – Teradata Basics A M P A M P A M P A M P 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 Tera-Tom Notes 7 .

Look for the BOLD and enlarged print that jumps out at you on the right pages. This book is your guide to passing the Teradata Basics Certification exam. The Tera-Cram series is designed to teach readers Teradata and help them pass their Teradata exams. 8 Tera-Tom Notes Copyright OSS 2001 .Introduction Welcome to the Tera-Cram series. Know this information especially well and your chances for success go way up.

Tera-Tom Notes 9 .Com.Introduction You can also take practice tests on the website Tera-Tom.

Rows can be inserted interactively or automatically. Data is stored in the Teradata DBS according to the relational model. Each field contains a data item with a single data type. or updating (changing) row data. A database consists of a collection of related tables. A row is the smallest unit that can be inserted into. and columns. which is based on tables with rows and columns. a relational table. The rows of a table can be considered an unordered set. you can use one of the load utilities (for example. 10 Tera-Tom Notes Copyright OSS 2001 . deleting rows from the table. Each row of a table is composed of a number of fields identified by column name. or deleted from. You modify the contents of a table by inserting rows into. rows. When building a new database. FastLoad) to populate several large tables automatically. and fields.A Table has Rows and Columns In yesterdays programming languages we referred to files. This is replaced in SQL and relational databases as tables. records.

00 Data is stored on Teradata in tables.00 50000. On row represents a single record. the two people in dept 10 are Dave Jones and Sue Wilson.00 44000. Each table is comprised of rows and columns. Tera-Tom Notes 11 .00 65000. The table above has four rows and five columns. For example.A Table has Rows and Columns Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000.

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.Retrieving Data From A Table To retrieve data from a table you will primarily use four key words. Lets talk about all of these. They are: SELECT FROM WHERE ORDER BY At a minimum you must use the keywords SELECT and FROM. If you don’t use the ORDER BY statement then the data comes back in random order. ORDER BY: The ORDER BY statement sorts the data. 12 Tera-Tom Notes Copyright OSS 2001 . If you don’t use a WHERE clause then all rows from the table will be returned. SELECT: After the word SELECT you will name all the columns you would like to retrieve.

Tera-Tom Notes 13 .00 65000.00 50000. WHERE: The WHERE is designed to limit the number of rows coming back.00 44000. ORDER BY: The ORDER BY statement sorts the data. WHERE. and ORDER BY.Retrieving Data From A Table Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000. FROM: After the word FROM you will name the table or tables in which the information will be retrieved.00 To retrieve data from a table users use the four key words SELECT. FROM. If you don’t use a WHERE clause then all rows from the table will be returned. If you don’t use the ORDER BY statement then the data comes back in random order. SELECT: After the word SELECT you will name all the columns you would like to retrieve. You must use the keywords SELECT and FROM.

14 Tera-Tom Notes Copyright OSS 2001 . Remember that after the word SELECT we will list the columns we want to retrieve. After the FROM clause is the table in which the data resides. A comma separates each column requested.Example of Selecting Data From A Table In the example on the following page we have SELECTed three columns.

00 50000. Each column after the SELECT is separated by a comma.00 65000.Examples of Selecting Data From A Table Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000. Tera-Tom Notes 15 .00 44000.lname FROM Employee.dept . Notice that we asked for three columns. Four Rows Returned EMP 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON In the above query all rows were returned. This is because there was no WHERE clause.00 SELECT emp .

The * represents all columns. 16 Tera-Tom Notes Copyright OSS 2001 .Example of Selecting All Columns in a table In the example on the following page we have SELECTed all columns in the table. After the FROM clause is the table in which the data resides. Remember that after the word SELECT we will list the columns we want to retrieve and the * means every column.

00 50000.Example of Selecting All Columns in a Table Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000.00 65000.00 44000.00 SELECT * FROM Employee.00 65000. 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 In the above query all columns were returned.00 44000. Notice that all rows were also returned. This is because there was no WHERE clause.00 50000. The * means all columns in the table. Tera-Tom Notes 17 .

The WHERE clause will decide what rows are returned. This is done with the WHERE clause. but have limited the number of rows returned. We have two rows returned.Example of Selecting Only Certain Rows In the example on the following page we have SELECTed all columns in the table. In our example we have asked for only the rows where the DEPT equals 10. 18 Tera-Tom Notes Copyright OSS 2001 .

00 65000.Example of Selecting only Certain Rows Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000.00 50000.00 SELECT * FROM Employee WHERE Dept = 10.00 44000. Two Rows Returned EMP 1 4 DEPT 10 10 LNAME JONES WILSON FNAME Dave Sue SAL 45000. Tera-Tom Notes 19 . Think of the WHERE clause as a filter.00 44000.00 The WHERE clause only retrieves rows that are requested in the WHERE Clause.

We have also sorted the data by using the ORDER BY clause. 20 Tera-Tom Notes Copyright OSS 2001 .Example of Sorting the Data In the example on the following page we have SELECTed all columns in the table and all rows.

Tera-Tom Notes 21 .Example of Sorting the Data Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000.00 50000.00 44000.00 44000. 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 The above result set was sorted in ascending order by the column LNAME.00 65000.00 45000.00 SELECT * FROM Employee ORDER BY LNAME.00 50000.

To check if a value is NULL you can only use two statements. For example. Zero Rows Returned You would never get rows to return because you can’t check to see if an undetermined value is equal to something. They are: IS NULL IS NOT NULL 22 Tera-Tom Notes Copyright OSS 2001 . 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. if you were to write: SELECT * FROM Employee WHERE DEPT = NULL.Checking for NULL Data NULL data is data that is an undetermined value.

NULL. 99000 ).00 50000. NULL. SELECT * FROM EMPLOYEE.00 Since a NULL value is undetermined data you can never check for a NULL value with an equality condition. You can only check for NULL by using: IS NULL IS NOT NULL Tera-Tom Notes 23 .00 44000.00 99000.Checking for NULL Data Lets insert some NULL data into our table. Employee Table EMP DEPT Primary Key 10 1 20 2 30 3 10 4 NULL 99 LNAME JONES SMITH CHANG WILSON NULL FNAME DAVE MARY VU SUE JIM SAL 45000.00 65000. ‘JIM’. INSERT INTO EMPLOYEE ( 99.

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. 24 Tera-Tom Notes Copyright OSS 2001 . Data is returned however when we use either the IS NULL or IS NOT NULL commands.

SELECT EMP.00 65000. EMP 1 2 3 4 FNAME Dave Mary Vu Sue Tera-Tom Notes 25 .Examples of NULL Data Employee Table EMP Primary Key 1 2 3 4 99 DEPT LNAME FNAME SAL 10 20 30 10 NULL JONES SMITH CHANG WILSON NULL DAVE MARY VU SUE JIM 45000.00 44000. EMP 99 FNAME JIM SELECT EMP. FNAME FROM EMPLOYEE WHERE DEPT IS One Row Returned NULL. FNAME FROM EMPLOYEE WHERE DEPT IS Four Rows Returned NOT NULL.00 50000.00 99000.00 SELECT * FROM EMPLOYEE WHERE DEPT = No Rows Returned NULL.

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. 26 Tera-Tom Notes Copyright OSS 2001 .

How Sorting Works with NULL Data
Employee Table
EMP Primary Key 1 2 3 4 99 DEPT LNAME FNAME SAL

10 20 30 10 NULL

JONES SMITH CHANG WILSON NULL

DAVE MARY VU SUE JIM

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

NULL data sorted in Ascending Order will always be

before all positive and negative values and before blank values.

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.

28

Tera-Tom Notes

Copyright OSS 2001

AND, OR, and NOT
The Order of Precedence is NOT, AND, and then OR. Think of it as NOT first and then in Alphabetic order. AND is before OR because A comes before O. Employee Table
EMP Primary Key 1 2 3 4 99 DEPT LNAME FNAME SAL

10 20 30 10 NULL

JONES SMITH CHANG WILSON NULL

DAVE MARY VU SUE JIM

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

IN the above example the only thing that comes back is anyone making a SAL over 80000.00.

Tera-Tom Notes

29

Here are the rules: No two databases or users may have the same name in the entire system. A table can be a maximum of 30 characters. No two tables in the same database or user may have the same name.Valid Table Names Teradata allows you to name tables anyway you want as long as you follow the rules. No two columns in the same table may have the same name. These include: Upper and lowercase alphabetic characters Integers These special characters: _ # $ 30 Tera-Tom Notes Copyright OSS 2001 .

• No two columns in the same table may have the same name. Here are the rules: • No two databases or users may have the same name in the entire system.Valid Table Names Teradata allows you to name tables anyway you want as long as you follow the rules. • No two tables in the same database or user may have the same name. These include: • Upper and lowercase alphabetic characters • Integers • These special characters: _ # $ Tera-Tom Notes 31 . A table can be a maximum of 30 characters.

32 Tera-Tom Notes Copyright OSS 2001 .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.

Absolute Function The ABS function looks for the Absolute functions.2) One Row Returned 1.2 Sel ABS(-8. It can even look at negative numbers and return the absolute value which is positive.1) One Row Returned 8. Sel ABS(-1.1 Tera-Tom Notes 33 .

The Extract Function
The extract function allows you to extract date information from a date field.

34

Tera-Tom Notes

Copyright OSS 2001

The Extract Function
If you want to find the people who were hired during the month of May you would use the extract function. Employee Table
EMP Primary Key 1 2 3 4 99 HIRE_DATE LNAME FNAME SAL

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

45000.00 50000.00 65000.00 44000.00 99000.00

SELECT * FROM Employee WHERE EXTRACT(month from HIRE_DATE) = 5;
One Row Returned

EMP 99

HIRE_DATE

LNAME FNAME NULL JIM

SAL 99000.00

05-06-01

Tera-Tom Notes

35

The Date Function
The DATE function allows you to select the DATE.

36

Tera-Tom Notes

Copyright OSS 2001

00 44000.00 65000. Tera-Tom Notes 37 .00 50000.The Date Function The DATE function allows you to select today’s date. Because the DATE is stored as an integer you can: • Utilize math to select certain portions of the date • Subtract different dates to find the difference • Add or subtract days to get a different date Employee Table EMP Primary Key 1 2 3 4 99 HIRE_DATE LNAME FNAME SAL 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 45000.00 SELECT (Date – Hire_Date) / 365 as YRS_OF_SERVICE FROM Employee. 5 Rows Returned YRS_OF_SERVICE 17 12 7 3 1 The above query gave us Years since Hire_date for all employees in the table.00 99000.

The Between Statement The BETWEEN statement is used in the where clause to retrieve rows that are between a certain value. If you asked if X was BETWEEN Y and Z the logic would be: X >= y AND X <= Z 38 Tera-Tom Notes Copyright OSS 2001 . The BETWEEN statement is inclusive.

The Between Statement The Between statement is inclusive.00 99000.00 50000.00 AND 65000.00 44000.00 65000. 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 SELECT * FROM Employee WHERE SAL BETWEEN 45000.00 50000.00. Employee Table EMP Primary Key 1 2 3 4 99 HIRE_DATE LNAME FNAME SAL 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 45000.00 65000.00 If you had asked if X was BETWEEN A and C the logic would be: X >= A AND X <= C Tera-Tom Notes 39 .

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 Copyright OSS 2001 .ADD_MONTHS Command and the SQL request uses the Primary Index.

ADD_MONTHS(Hire_date.00 65000. Employee Table EMP Primary Key 1 2 3 4 99 HIRE_DATE LNAME FNAME SAL 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 45000. 12 * 5) Answer: The Hire_Date + 5 years Tera-Tom Notes 41 . 2) as Months_Plus2 FROM Employee.00 SELECT Emp.00 99000.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. Hire_date .00 50000. Five Rows Returned 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 What is the Answer Below? Sel Add_months(Hire_Date.00 44000.

IN Command The IN command provides a list of values to the query as input. 42 Tera-Tom Notes Copyright OSS 2001 . It is looked at like a OR situation.

00 65000.00 Tera-Tom Notes 43 .00 SELECT * FROM Employee WHERE DEPT IN (20. It is also used when a column is used in a SET OF VALUES.00 50000. Two Rows Returned EMP 3 2 DEPT 30 20 LNAME CHANG SMITH FNAME Vu Mary SAL 65000.IN Command The IN OPERATOR is used in the WHERE CLAUSE.00 50000. Employee EMP Primary Key 1 2 3 4 DEPT 10 20 30 10 LNAME JONES SMITH CHANG WILSON FNAME DAVE MARY VU SUE SAL 45000.00 44000.30).

It delivers a distinct list of values that are used as input to the top query.30). 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. A subquery is similar except it builds the list (which was 20 or 30) on the fly. The above query will select all columns from the employee table where the DEPT is equal to 20 or 30.Subqueries A subquery involves two queries which are the top query and the bottom query. Here is another way of thinking about subqueries. Here is an example: SELECT * FROM Employee WHERE DEPT IN (20. 44 Tera-Tom Notes Copyright OSS 2001 . It is easy to understand the IN Operator. 30 is passed to the top query. On the following page you will notice that the bottom query asks: SELECT DEPT from Department WHERE Dept_name = ‘Finance’. The top query in a sense is now asking: SELECT * FROM EMPLOYEE WHERE DEPT IN (30). The DEPT that has a Dept_name = ‘Finance’ is DEPT 30. The bottom query runs first.

00 Tera-Tom Notes 45 . but data selected in the subquery will NOT be in the Answer Set.Subqueries A Subquery involves two queries.00 50000.00 65000. The bottom query fully qualifies which rows will be in the answer set.00 44000. Employee Table EMP DEPT Primary Foreign Key Key * 1 10 2 20 3 30 4 10 Department Table DEPT PK 10 20 30 40 DEPT_NAME SALES MARKETING FINANCE HUMAN RESOURCES LNAME FNAME SAL which is the subquery runs first.00 SELECT * FROM EMPLOYEE WHERE DEPT IN (SELECT DEPT FROM Department WHERE DEPT_NAME = ‘FINANCE’). One Row Returned EMP 3 DEPT 30 LNAME CHANG FNAME Vu SAL 65000. The Subquery JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.

46 Tera-Tom Notes Copyright OSS 2001 . Once you alias a column or a table you must use the alias throughout the SQL.Aliasing To give an alias is to give a column or table a new name.

Aliasing You can alias a column or a table by giving them a new name. Tera-Tom Notes 47 .00 SELECT LNAME AS LAST_NAME FROM EMPLOYEE AS EMP_Table WHERE DEPT IN (20.00 44000.00 50000. Employee Table EMP DEPT Primary Foreign Key Key * 1 10 2 20 3 30 4 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.30) ORDER BY LAST_NAME DESC.00 65000. Notice the ORDER BY statement. Two Rows Returned LAST_NAME SMITH CHANG The above Query uses LAST_NAME as an alias for LNAME and EMP_Table as an alias for EMPLOYEE. It uses LAST_NAME as the sort key. A golden rule is that once you alias you must use the alias throughout the SQL. We have followed the golden rule.

Even though the result might be the same from either table. The key to joins is in the WHERE or ON clause. This means the system is not sure which table you want to get the column from. the system still needs you to tell it which table you want the duplicate column name to come from. “Column Ambiguous”. This is a classic two-table join. Up to 64 tables and views may be joined. We have listed both syntax options. The match will usually occur where there is a PRIMARY KEY and a FOREIGN KEY relationship. Each source must be named and the join condition. 48 Tera-Tom Notes Copyright OSS 2001 . This is because this was how the tables were logically defined. 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. That means you must match the two rows from the different tables. The query is looking for columns from both tables. 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. When you are joining information from two tables you will be SELECTing fields from both tables.DEPT? The reason is that the column DEPT is in both the EMPLOYEE_TABLE AS E and DEPARTMENT_TABLE AS D. Do you know why we called it E. Remember. An inner join selects data from two or more tables or views. To do this you are joining together information from two separate rows from two separate tables.Joining Two Tables Using Teradata Syntax A join allows you to select columns and rows from two or more tables and views. specified in a WHERE clause. If you don’t qualify the column name when the column name exists in both tables you will get an error message saying. the common relationship between the tables or views to be joined.

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 49 .E.Dept = D.Department_Table D WHERE E.DeptName FROM Employee_Table E .Dept .Name .Joining Two Tables Using Teradata Syntax AMP 1 Department_Table & Employee_Table Dept 10 20 PI PI AMP 2 Department_Table & Employee_Table Dept 30 40 PI PI DeptName Sales Mrkt DeptName Finance IT Emp Dept Name Salary 1 10 Bo Doe 50000 4 20 Jo Noe 60000 Emp Dept Name Salary 2 10 Vu Too 60000 3 30 Lu Koo 70000 The first example join is done using Teradata syntax SELECT Emp .

This is a classic two-table join. 50 Tera-Tom Notes Copyright OSS 2001 . That means you must match the two rows from the different tables. The first is the Teradata Join Syntax and the second is the ANSI Join Syntax. specified in a WHERE clause. The match will usually occur where there is a PRIMARY KEY and a FOREIGN KEY relationship. We have listed both syntax options. the common relationship between the tables or views to be joined. Up to 64 tables and views may be joined. Remember. To do this you are joining together information from two separate rows from two separate tables. 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. Each source must be named and the join condition.Joining Two Tables Using ANSI Syntax A join allows you to select columns and rows from two or more tables and views. The query is looking for columns from both tables. This is because this was how the tables were logically defined. When you are joining information from two tables you will be SELECTing fields from both tables. The key to joins is in the WHERE or ON clause. An inner join selects data from two or more tables or views.

Name .DeptName FROM Employee_Table AS E INNER JOIN Department_Table AS D ON E.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 The ON Clause is required when the keyword JOIN.Joining Two Tables using ANSI syntax SELECT Emp . There are two join condition options for an inner join: (1) The WHERE Clause for Teradata Syntax (2) The ON Clause for ANSI Syntax Tera-Tom Notes 51 .Dept = D. INNER JOIN.E.Dept . or OUTER JOIN is specified.

and EXCEPT.SET Operators The SET Operators are UNION. SET Operators 52 Tera-Tom Notes Copyright OSS 2001 . The word MINUS is also acceptable and it means the exact same thing as EXCEPT. INTERSECT.

The SET Operators are two queries that are separated by the word UNION or INTERSECT or EXCEPT. Five Rows Returned ANSWER 1 2 3 4 5 Tera-Tom Notes 53 . TableB TableA 1 2 3 3 4 5 SELECT * FROM TableA Title ‘ANSWER’ UNION SELECT * FROM TableB. and EXCEPT/MINUS.Set Operators The SET Operators are UNION. Both Queries run simultaneously and the answer sets are combined eliminating duplicates. INTERSECT.

and EXCEPT. The word MINUS is also acceptable and it means the exact same thing as EXCEPT. INTERSECT.SET Operators Continued The SET Operators are UNION. SET Operators 54 Tera-Tom Notes Copyright OSS 2001 .

Set Operators Continued TableA TableB 1 2 3 3 4 5 SELECT First_column FROM TableA Title ‘ANSWER’ UNION SELECT Column_One FROM TableB. Tera-Tom Notes 55 . Five Rows Returned ANSWER 1 2 3 4 5 What did the above query deliver? All rows from TableA and TableB with duplicates eliminated.

56 Tera-Tom Notes Copyright OSS 2001 . views. All of the above information is important to know.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. or other macros. You can have multiple SQL statements in a macro and you can place comments inside a macro.

comments by placing them inside /* You can create */. Security and a simplified operation are goods reason to use parameterized macros. views. The above MACRO contains multiple SQL statements and a comment.Macros Users can create macros even if they don’t have PERM space because MACROS are stored in the DATA DICTIONARY. SELECT * FROM Department. Macros don’t need privileges on underlying tables. 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. Tera-Tom Notes 57 .). or other macros.

They are built dynamically using an additional SELECT within the query. Derived tables are always local to a single SQL request. Notice how the second query selects Max(sal) from the employee_table and places it into a table called Derived_tbl. Therefore. Example: SELECT employee_number. maxsal From EMPLOYEE_TABLE. no extra privileges are necessary. dept. The DD has no knowledge of derived tables. and salary from the employee_table. 58 Tera-Tom Notes Copyright OSS 2001 . (SELECT max(salary) from EMPLOYEE_TABLE) derived_tbl(maxsal). dept. We created a derived table to get the Maxsal field. In the example above we pulled employee_number. Its space comes from the users spool space. salary. The rows of the derived table are stored in spool and discarded as soon as the query finishes. Inside Derived_tbl we name the column we just selected as maxsal.Derived Tables Derived tables are a fantastic way for users to create temporary tables inside their query.

(SELECT max(salary) from EMPLOYEE_TABLE) derived_tbl(maxsal). Derived tables are always created in the users SPOOL Space.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. SELECT employee_number. value can be generated in a derived table. salary. maxsal From EMPLOYEE_TABLE. dept. Derived tables cannot be shared between users and do not affect the data dictionary. Derived tables cannot have secondary indexes and they are NOT created from Perm Space. A referenced Tera-Tom Notes 59 . Derived tables allow for aggregates to be used in the WHERE clause.

All of the above information is important to know. 60 Tera-Tom Notes Copyright OSS 2001 . Macros don’t need privileges on underlying tables.Macros Users can create macros even if they don’t have PERM space because MACROS are stored in the DATA DICTIONARY. or other macros. You can have multiple SQL statements in a macro and you can place comments inside a macro. views.

SELECT * FROM Department. or other macros.Macros Users can create macros even if they don’t have PERM space because MACROS are stored in the DATA DICTIONARY. views. comments by placing them inside /* You can create */. 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. Tera-Tom Notes 61 . The above MACRO contains multiple SQL statements and a comment.). Macros don’t need privileges on underlying tables.

This provides a window into tables that have sensitive data. they display data in columns and rows and. only their column definitions are stored. may be used as if they were tables. but are SQL statements that are stored in the DD/D. Some operations used on tables are not valid on views. and can include conditional expressions and aggregate operators to limit the row retrieval. A view is used to retrieve portions of one or more tables and/or other views. Management can define what columns employees can see and what columns they cannot. However. depending on how the view is defined. but would like these individuals to have access to much of the other information in a table. and other operations are restricted. A view is not assembled until it is referenced by a statement. A view does not contain data. 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 is the purpose of views. in general. There is information in some tables such as SALARY that employers do not want individuals to see. defines a SELECT of one or more columns from one or more underlying tables and/or views. Views do not actually store the data.What is a View? A view can be compared to a window through which you can see selected portions of a database. Views look like tables. 62 Tera-Tom Notes Copyright OSS 2001 . The CREATE VIEW statement defines a view. The statement names the view and its columns.

fname FROM Employee_table. Tera-Tom Notes 63 . 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 concurrent access is to create views with Locking for Access. EMPXXView . lname.A typical view EMP DEPT LNAME 1 10 Jones 2 20 Smith 3 30 Chang 4 10 Wilson FNAME SAL Dave XXXXX Mary XXXXX Vu XXXXX Sue XXXXX Create view Emp_View as locking employee_table for access SELECT emp.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. dept.

This allows you to compare apples to apples and oranges to oranges. 64 Tera-Tom Notes Copyright OSS 2001 . That is where the CAST statement comes into play. However. You can use the CAST statement to temporarily convert data into a different data type. the data types defined and stored in a table should be appropriate.Cast Under most conditions. sometimes it is neither convenient nor desirable to use the defined type.

Tera-Tom Notes 65 .53 AS SMALLINT) AS chop .CAST(151.CAST(127 AS INTEGER ) AS Big .0) or any decimal with a 0 for the number of decimals. You can utilize CAST to change column data types temporarily. Because the cast has requested no decimals the system rounds the answer.0)) AS Round . ONE ROW RETURNED ALPH A 128 Big 128 chop 127 Round 151 152 Notice that when you cast something as a Decimal(3. The reason is the 0 in Decimal(3.CAST(151. This example uses literals to show actual conversions.0) the system will round the result.CAST(128 AS CHAR(3) ) AS 128 .53 AS DECIMAL(3.0).CAST The CAST statement stands for Convert And Store. This is also the same if you were to cast to: Decimal(10. but you can also use column names: SELECT CAST(‘ABC’ AS CHAR(1) ) AS Alph .

Traditional Subqueries Traditional subqueries are generally read from the bottom to the top. They are usually the object of an IN or NOT IN clause. 66 Tera-Tom Notes Copyright OSS 2001 . They will always generate a distinct list of values. thus resulting in up to 16 subquery levels. Remember some simple keys about subqueries: Subqueries can be nested. 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.

The top query uses that list for input. lname from Employee WHERE Dept in (SELECT d.00 44000. Dept.00 65000. Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.Dept from department d where Dept_name Like ‘Sales’). The bottom query runs first and delivers a list of values to the top query.00 Department Table DEPT PK 10 20 30 40 DEPT_NAME SALES MARKETING FINANCE HUMAN RESOURCES SELECT Emp. Tera-Tom Notes 67 .00 50000.Traditional Subqueries A subquery is two queries in one. Two rows returned EMP -------1 4 DEPT --------10 10 LNAME ---------Jones Wilson The above query finds all employees in the sales dept.

68 Tera-Tom Notes Copyright OSS 2001 . Remember some simple keys about subqueries: Subqueries can be nested. An SQL statement may reference up to 16 tables or views. The lowest or bottom query is answered and the results are put to the next level of query. thus resulting in up to 16 subquery levels. They will always generate a distinct list of values.Traditional Subqueries Continued Traditional subqueries are generally read from the bottom to the top. They are usually the object of an IN or NOT IN clause.

00 50000. Three rows returned EMP -------1 2 3 DEPT --------10 20 30 LNAME ---------Jones Smith Chang The above query lists all employees with valid department numbers. Notice that employee 4 did not come back. WHY? There is no Dept 50 in the department table.00 Department Table DEPT PK 10 20 30 40 DEPT_NAME SALES MARKETING FINANCE HUMAN RESOURCES SELECT Emp.00 65000. lname from Employee WHERE Dept in (SELECT Dept from department). Dept.00 44000.Traditional Subqueries Continued Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 LNAME FNAME SAL 50 JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000. Tera-Tom Notes 69 .

Each row of the outer query is selected and is compared to the criteria in the subquery. Usually. correlated subqueries involve aggregates. Correlated subqueries allow the SQL user to write one query instead of having to write two. 70 Tera-Tom Notes Copyright OSS 2001 . In the past the user would have to write a query and build a table to run the second result against.Correlated Subqueries Correlated subqueries are processed differently from traditional subqueries. although they may involve expressions and other computed columns.

00 SELECT EMP. Three rows returned EMP ------4 2 3 DEPT --------10 20 30 LNAME -----------Wilson Smith Chang Notice that the above Correlated subquery returns the employees with the lowest salary in their respective departments. Notice that employee 1 did not come back because they don’t have the minimum salary in department 10. DEPT.00 65000. LNAME FROM Employee e WHERE sal = (SEL MIN (Sal) FROM Employee ee WHERE e.00 50000.dept = ee.Correlated Subqueries Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.00 44000. Tera-Tom Notes 71 .dept).

2. Gets the max salary for the deptxx from the subquery 3. If equal. Each row of the outer query is selected and is compared to the criteria in the subquery. Usually. Compares the salary to the max salary 4. go to step 1. The following page shows a typical correlated subquery. correlated subqueries involve aggregates. Correlated subqueries use a shared spool technique that can speed up processing. 72 Tera-Tom Notes Copyright OSS 2001 . although they may involve expressions and other computed columns. If not equal. Read a row from the table.How Correlated Subqueries Work Correlated subqueries are processed differently from traditional subqueries. output the row. The subquery executes by: 1.

If not equal. Tera-Tom Notes 73 . Compare the salary to the min 4. 2. Gets the min or inner query.00 65000. If equal.How Correlated Subqueries Work Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.Read a row from the table from the top query (outer query). DEPT. LNAME FROM Employee e WHERE sal = (SEL MIN (Sal) FROM Employee ee WHERE e. output the row.00 50000.sal = ee. 1.sal).00 SELECT EMP.00 44000. go to step 1. salary for the dept from the subquery salary 3.

Insert Select You can populate one table directly from another table with an INSERT SELECT statement. 74 Tera-Tom Notes Copyright OSS 2001 .

lname Char(20) . Tera-Tom Notes 75 .00 65000. INSERT INTO EMPXX EMPXX Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000. The above INSERT SELECT utilizes the SELECT * from Employee because both tables have the same number of columns with compatible data types.Sal Decimal(10.00 65000. CREATE TABLE EMPXX ( emp integer .00 50000. I will create another table called EMPXX.fname Char(20) . EMPXX is empty until we do an insert select.00 The Employee table exists and it has four rows.dept integer .2) ) Unique Primary Index(emp).00 44000.00 SELECT * FROM Employee.Insert Select Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.00 44000.00 50000.

76 Tera-Tom Notes Copyright OSS 2001 . If however. To INSERT into the new table you must list the columns you want to place into the new table. If our OLD_TABLE had 5 columns and our NEW_TABLE had 3 columns we would have to do the INSERT SELECT by SELECTING the exact columns that are to be moved. the tables have a different number of columns or incompatible data types you can’t say SELECT * FROM OLD_TABLE. LNAME FROM OLD_TABLE.Insert Select Continued You can populate one table directly from another table with an INSERT SELECT statement. This takes each column and row from the OLD_TABLE and INSERTS them into the new table. DEPT. For example: INSERT INTO NEW_TABLE SELECT EMP. The NEW_TABLE having only 3 columns is expecting to only receive 3 columns. The key here is the SELECT * FROM OLD_TABLE. By selecting the 3 columns we want to move Teradata knows how to populate the NEW_TABLE. If the two tables have the same number of columns and compatible data types you can say: INSERT INTO NEW_TABLE SELECT * FROM OLD_TABLE.

Insert Select Continued
Employee Table
EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL

JONES SMITH CHANG WILSON

DAVE MARY VU SUE

45000.00 50000.00 65000.00 44000.00

The Employee table exists and it has four rows. I will create another table called EMPXX, but this time the two tables will have a different number of columns.
CREATE TABLE EMPXX2 ( emp integer ,dept integer ,lname Char(20) ) Unique Primary Index(emp);

EMPXX is empty until we do an insert select.

SELECT Emp, dept, lname FROM Employee;
INSERT INTO EMPXX EMPXX Table
EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME JONES SMITH CHANG WILSON

Because the two tables have a different number of columns we must do the INSERT SELECT by selecting specific columns. SELECT * Won’t Work.

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

Copyright OSS 2001

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)

To use the SHOW command on a table the user must have a privilege on the table contains it.

or database that

Tera-Tom Notes

79

statistics. viewname. (Shows MACRO parameters) HELP COLUMN tablename.*. You only see comment information if the customer has built the comments themselves. view. that you want to see. Character Variable.colname. column types. and triggers in a particular database) HELP TABLE tablename. Here is the syntax for help: HELP DATABASE databasename. 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. When you use help you will be able to see help information about the table. CV. (Gives help on indexes of a particular table) HELP STATISTICS tablename. Character Fixed. The following page shows the help command on a table. SQL Help: HELP ‘SQL’ and HELP ‘SQL <sqlcommand>’.colname.HELP Command The HELP command is used to provide help with databases. (This command shows the columns in a view that are accessible) HELP MACRO macroname. indexes. macros. viewname. and D in the type column stand for Integer. and sessions.*. The I. etc. views. tables. columns. 80 Tera-Tom Notes Copyright OSS 2001 . and Decimal. and a comment. macros. (This command shows all the tables. tablename. (Gives help on number or rows and duplicates. You can then see information about the table columns.CF. views. (Gives help on columns) HELP INDEX tablename. (This command shows all the columns in a particular table) HELP VIEW viewname.

Column Name -------------------EMP DEPT LNAME FNAME SAL Type ------I I CF CV D Comment ---------------------EMPLOYEE NUMBER DEPARTMENT No Surname First Name Pay Tera-Tom Notes 81 . index or statistics. column. macro.HELP Command The HELP command is a Teradata extension that can be used to get information about a table. The HELP TABLE COMMAND will show a user three things about a table: • Column names • Data types • Any comments HELP TABLE Empxx. database. The HELP command reports information from the Teradata Data Dictionary. view.

Indexes can be unique or non-unique. and statistical statements to address indexes by their assigned names. or add them to an existing table using the CREATE INDEX statement. Secondary indexes can improve system performance. If you create a unique index then that column will not allow duplicates. A secondary index is a subtable that is stored separately from the primary table. that creating a secondary index causes the Teradata DBS to build a separate internal subtable. 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 allows several table. An index may be given a name. Each subtable row contains a secondary index value. The name allows the index to be dropped using the name instead of repeating all the column names. plus one or more row identifiers (IDs) that point to the primary table row(s) containing that value. Secondary indexes can also be made during the CREATE table statement or can be made at a later time. You can define one or more secondary indexes in the CREATE TABLE statement. Secondary indexes are optional. 82 Tera-Tom Notes Copyright OSS 2001 .CREATE a Secondary INDEX Primary indexes are created with a CREATE table statement. This is a good idea when the index is a composite (multi-column) index. index. note however.

When creating an index ensure that there is space available for up to four times the expected index size. fname) on EMPLOYEE. To create a Value-Ordered NUSI the indexed column can only be a four-byte column. To create a non-unique secondary index use the format: CREATE INDEX(Dept) on EMPLOYEE. Tera-Tom Notes 83 .CREATE a Secondary INDEX Secondary indexes can be defined with the CREATE INDEX or CREATE TABLE statements. CREATE INDEX uses table permanent space as workspace. Here is the syntax: CREATE INDEX(Hire_Date) on EMPLOYEE ORDER BY VALUES. To create a unique secondary index use this format: CREATE UNIQUE INDEX(lname.

IF the values are equal then the result will be NULL. Here is an example using literals. SELECT NULLIF(0. Thus Teradata returns the first value in the list. The result is NULL. Here is another example: SELECT NULLIF(3.0). The result is 3.The NULLIF Command The NULLIF command is an ANSI compliant command that compares two values. Here is another way of looking at the NULLIF logic: When x = y then Null else X 84 Tera-Tom Notes Copyright OSS 2001 . This is because the two values in the list are not equal.0). This is because the two values in the list are equal. If the values are not equal then the result will be the first value in the list.

0). Here is an example using literals. This is because the two values in the list are not equal. Thus Teradata returns the first value in the list. Here is another way of looking at the NULLIF logic: When x = y then Null else X Tera-Tom Notes 85 . SELECT NULLIF(0. Here is another example: SELECT NULLIF(3.0). This is because the two values in the list are equal. IF the values are equal then the result will be NULL.The NULLIF Command The NULLIF command is an ANSI compliant command that compares two values in a list. The result is NULL. If the values are not equal then the result will be the first value in the list. The result is 3.

MINIMUM. MAXIMUM. An aggregate operator is used to perform a computation for the values in a group. The COUNT operator has two forms. The group used is the entire table unless a GROUP BY clause is specified. Both forms of COUNT operate on any data type. MIN may be used to return the lowest sort order of a character expression. You are getting a one-line report that shows the SUM of the entire table. All aggregate operators can be applied to numeric data. If you use the GROUP BY statement you can get a oneline report per the GROUP. 86 Tera-Tom Notes Copyright OSS 2001 .Aggregate Functions Aggregate operators can be used in arithmetic expressions. Aggregates do not give you detail lines. and COUNT operate on character as well as numeric data. COUNT(value) and COUNT(*). These are: SUM AVERAGE COUNT MINIMUM MAXIMUM It is legal to apply AVERAGE. MAX. or COUNT to Date. but it is not legal to do SUM(Date). MAX the highest. Aggregate operators are often used for reports. MIN.

AGGREGATES can ONLY produce SINGLE-LINE answers.AVG(column) . One row returned AVG(Salary) -----------------$50.Aggregate Functions Aggregate functions are: COUNT. AGGREGATE operations ignore SELECT COUNT(column) . SUM. AND MIN. MAX. Select AVG (Salary) from Employee.MAX(column) .MIN(column) FROM table.000 Tera-Tom Notes 87 .SUM(column) . NULLs. AVG.

The GROUP BY clause creates summary information for a table. When an aggregate operation (SUM. or COUNT) is specified. GROUP BY can be used to return a summary row for each group. 88 Tera-Tom Notes Copyright OSS 2001 . Each col_name in a GROUP BY clause is the name of a column referenced in the SELECT expression list. MAX. MIN. If an ORDER BY clause is used. The following page shows the GROUP BY options.GROUP BY The GROUP BY clause of the SELECT statement groups result rows by the values in one or more columns. The pages following will provide examples. All non-aggregate groups in a SELECT expression list must be included in the GROUP BY clause. AVERAGE. Aggregate operators can be used only in the SELECT expression list or in the optional HAVING clause. any group contained in the ORDER BY clause must also be included in the GROUP BY clause.

00 268.GROUP BY The GROUP BY clause will produce aggregates by GROUP. SUM(Sal) FROM EmpXX GROUP BY Dept.00 143. The Group By statement does NOT support the display of detail data and summary data ever! Tera-Tom Notes 89 . Also notice that the query works because DEPT was placed in the GROUP BY statement.00 In the above example we get a sum of all salaries by Department. Dept -----001 002 003 Sum(Sal) ---------------------180.000.000. The following statement is used to generate a report of salary totals by department: SELECT Dept. Any non-aggregated attribute in a SELECT List must be part of the GROUP BY Clause. Notice that DEPT is a non-aggregate.500.

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. 90 Tera-Tom Notes Copyright OSS 2001 .

00 50000.00 SELECT DEPT.00 MAX(SAL) -------------45000.00 AVG(SAL) -------------44500. Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 20 30 10 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000. MAX(SAL). One row returned DEPT --------10 SUM(SAL) ------------89000. AVG(SAL) FROM EMPXX GROUP BY DEPT HAVING AVG(SAL) < 45000.00 Tera-Tom Notes 91 .GROUP BY and HAVING Conditions The HAVING clause can eliminate some or all of the groupings in an SQL statement.00 44000. WHERE will exclude rows before the GROUP BY and HAVING will exclude groups after the totals have been grouped. SUM(SAL).00 65000.

Some Aggregate examples The following page shows examples of aggregates. 92 Tera-Tom Notes Copyright OSS 2001 .

SELECT COUNT(Salary) from EMPxx. Tera-Tom Notes 93 . One row returned AVG(Salary) -----------------100000 The reason the answer is 100000 is because aggregates ignore nulls.Some Aggregate Examples EmpXX Table EMP 1 2 3 4 Salary 100000 100000 100000 NULL SELECT AVG(Salary) from Empxx. One row returned Count(Salary) -------------------3 The count above was on Salary and since aggregates ignore NULLs the answer is 3.

Some Aggregate examples Continued The following page shows examples of aggregates. 94 Tera-Tom Notes Copyright OSS 2001 .

One row returned COUNT(*) -----------------4 The reason the answer is 4 is because the Since the entire COUNT(*) counts the entire row.Some Aggregate Examples Continued EmpXX Table EMP 1 2 3 4 Salary 100000 100000 100000 NULL SELECT COUNT(*) from Empxx. row is not NULL the count is 4. Tera-Tom Notes 95 .

96 Tera-Tom Notes Copyright OSS 2001 .Some Aggregate examples Continued The following page shows examples of aggregates.

Some Aggregate Examples Continued EmpXX Table EMP 1 2 3 4 Salary 100000 100000 100000 NULL SELECT COUNT(*) from Empxx. One row returned COUNT(*) -----------------4 The reason the is because the row. answer is 4 COUNT(*) counts the entire Tera-Tom Notes 97 . Since the entire row is not NULL the count is 4.

Advanced Aggregate example The following page shows examples of aggregates. 98 Tera-Tom Notes Copyright OSS 2001 .

One row returned Dept -------10 Lname ---------Wilson Count(*) -----------3 Notice that only one row is returned.00 44000. Tera-Tom Notes 99 . Lname Having COUNT(*) > 2. COUNT(*) FROM EMPLOYEE GROUP by Dept.00 SELECT Dept.Advanced Aggregate Example Employee Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 10 30 10 LNAME FNAME SAL Wilson Wilson CHANG WILSON DAVE MARY VU SUE 45000. This is because of the having clause. Lname.00 50000. For a row to be returned more than 2 people had to have the same last name and be in the exact same department.00 65000.

Note: These commands may not work with Queryman and other ODBC related tools. 100 Tera-Tom Notes Copyright OSS 2001 . These are report writing features. BTEQ is a report writer.Using WITH… BY for Subtotals The following page lists the fundamentals for the WITH…BY command.

within groupings.Using WITH…By for Subtotals WITH…By: • Creates subtotal lines. for a detail list. • Allows subtotals “breaks” on more than one column. • Automatically gives order results. • Differs from GROUP BY in that detail lines are not eliminated. • Is a Teradata extension • WITH BY does not work with Queryman! Tera-Tom Notes 101 .

The ORDER BY can be used with a WITH…BY. it is the most minor sort sequence. the last WITH…BY is the major sort.BY command. 102 Tera-Tom Notes Copyright OSS 2001 . When this is done. The WITH…. The multiple WITH…BY subtotals may be requested in the same SELECT.Creating a Report Using WITH …BY The following page shows an example of the WITH.. When it is used.BY performs a sort to put all the same values of the BY column together for display and aggregation.

00 10 Smith 50000.Creating a Report Using WITH…BY Empxx Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 10 20 20 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.00 44000. Tera-Tom Notes 103 .00 50000.------------10 Jones 45000.00 ---------------------Sum(sal) 95000. dept.00 3 4 Notice that the With By allows for detailed information as well as subtotals on breaks by Dept.00 65000. Dept Lname Sal --------.00 65000. sal FROM Empxx WITH Emp -------1 2 SUM(sal) by dept.----------.00 20 Chang 20 Wilson ---------------------Sum(sal) 109000.00 44000. lname.00 SELECT emp.

WITH …BY Multiple Aggregates You can use the WITH…BY command with multiple aggregates as seen on the following page. 104 Tera-Tom Notes Copyright OSS 2001 .

Dept Lname Sal --------. sal FROM Empxx WITH SUM(sal).00 65000.00 Avg(sal) 54500.00 Avg(sal) 47500.00 50000. AVG(sal) by dept.00 ---------------------Sum(sal) 95000.WITH…BY Multiple Aggregates Empxx Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 10 20 20 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.00 44000.00 20 Chang 20 Wilson ---------------------Sum(sal) 109000.00 10 Smith 50000. lname.00 44000. dept.00 Emp -------1 2 3 4 Tera-Tom Notes 105 .------------10 Jones 45000.----------.00 65000.00 SELECT emp.

WITH for a final total You can use the WITH command by itself to provide a final total as seen on the following page. 106 Tera-Tom Notes Copyright OSS 2001 .

The WITH statement gives a grand of the report.00 10 Smith 50000.----------.00 ---------------------Sum(sal) 204.00 BY statement gives detail lines and subtotals.00 44000. Dept Lname Sal --------. dept.00 20 Chang 65000.000. The WITH total at the end Tera-Tom Notes 107 .------------10 Jones 45000.00 65000.WITH for a Final Total Empxx Table EMP Primary Key 1 2 3 4 DEPT Foreign Key * 10 10 20 20 LNAME FNAME SAL JONES SMITH CHANG WILSON DAVE MARY VU SUE 45000.00 20 Wilson 44000. lname. sal FROM Empxx WITH Emp -------1 2 3 4 SUM(sal) .00 50000.00 SELECT emp.

Multiple WITH BY Statements Multiple With By statements can be utilized during a query. 108 Tera-Tom Notes Copyright OSS 2001 .

Sales.Multiple With By Statements Empxx Table Store_No 1 2 3 4 Sales 50000 100000 40000 200000 City Dayton Dayton Cincinnati Cincinnati State OHIO OHIO OHIO OHIO Country USA USA USA USA SELECT Store_No.----------50000 Dayton 100000 Dayton State ------------Ohio Ohio Sum(Sales) by City 150000 3 4 40000 200000 Cincinnati Cincinnati Ohio Ohio Sum(Sales) by City 240000 ---------------------Sum(sales) By State 390. WITH Store_no -------------1 2 Sales City --------.000. Tera-Tom Notes 109 .00 This query shows detail lines with subtotals by city within state and subtotals by State. City. State FROM Empxx SUM(sales) BY City With SUM(sales) BY State.

Answer the questions also on the following page.What type of join is this? Run the query on the following page. 110 Tera-Tom Notes Copyright OSS 2001 .

Mgr = ‘Y’ AND WRKS.-------.What type of join is this? Employee Table Emp 1 2 3 4 Dept 10 10 10 20 Lname Smith Jones Wilson Lane Sal 50000 40000 100000 50000 Y N N Y Mgr SELECT WRKS.Employee MGRS WHERE MGRS.Sal .Sal .Lname .MGRS.-------.Emp .WRKS.WRKS. Tera-Tom Notes 111 . Emp Dept Lname Sal Lname Sal -------.dept = WRKS.Dept .----------.dept AND MGRS.Lname .--------------3 10 Wilson 100000 Smith 50000 The above Query is a SELF JOIN.MGRS. Notice that the two tables being joined are both the same table. The Employee table is given the aliases WRKS and MGRS.Sal From Employee WRKS .Sal > MGRS.WRKS.

The following page shows and excellent example. 112 Tera-Tom Notes Copyright OSS 2001 .Characters Functions The Characters function works with Varchar data types and returns the length of the column.

Lname Name_Length ------------.CHARACTERS(Lname) AS Name_Length FROM Employee.-------------------Smith 5 Jones 5 Wilson 6 Lane 4 Tera-Tom Notes 113 .Characters Function Employee Table Emp 1 2 3 4 Dept 10 10 10 20 Lname Smith Jones Wilson Lane Sal 50000 40000 100000 50000 Y N N Y Mgr SELECT Lname /* A VARCHAR 20 Column */ .

Trim The TRIM function is used to eliminate either leading. 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 */ */ TRIM( BOTH FROM <column-name> ) /* spaces before and after */ /* Trims all spaces stored before and after all text characters */ TRIM( <column-name> ) /* defaults to BOTH */ 114 Tera-Tom Notes Copyright OSS 2001 . trailing spaces or both leading and trailing spaces from character data.

trailing spaces or both leading and trailing spaces from character data. Example: Select Trim(‘ ABCDE ’) Results: ABCDE PAD The leading and trailing spaces have been trimmed. Tera-Tom Notes 115 . 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 */ */ TRIM( BOTH FROM <column-name> ) /* spaces before and after */ /* Trims all spaces stored before and after all text characters */ TRIM( <column-name> ) /* defaults to BOTH */ In ANSI mode leading and trailing characters are removed.Trim The TRIM function is used to eliminate either leading.

Because the Characters is run first there is no TRIM that needs to be performed.Trim and Characters Combined The following page shows an example of the TRIM and CHARACTERS functions combined. 116 Tera-Tom Notes Copyright OSS 2001 .

Trim and Characters Combined SELECT TRIM(Both from(Characters(BBBdataBBB’))). Tera-Tom Notes 117 . There are 10 characters. It returns the number of characters. By the time the answer set is interpreted by the TRIM function the spaces are gone. The only answer is 10. Why? The Characters function will be run first. (Note: The BBB stands for Blanks or Spaces) The result of the above query is 10.

118 Tera-Tom Notes Copyright OSS 2001 .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.

Tera-Tom Notes 119 . Constraints can be defined at either the table or column level.UNIQUE Constraint The UNIQUE constraint is used to enforce uniqueness of values stored within the column(s).Sal Integer ) Primary Index (Dept) The UNIQUE Constraint cannot be performed on a column that may have values that are NULL.Dept Integer .Name Character(40) . CREATE TABLE Employee (Emp Integer NOT NULL Constraint EmpUniq UNIQUE . No two rows in the table can have the same value for the column or columns utilizing the UNIQUE constraint.

Compress Compressing a column value can save valuable disk space. 120 Tera-Tom Notes Copyright OSS 2001 . The compress allows you to specify a value in a column and not store that value. 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. For example. You can compress the value CALIFORNIA and instead of storing it on the disk for almost every row you can compress the value. it increases the processing overhead whenever a compressed column is accessed because the location of the data must be computed on the fly. A Volatile Table does not support compression. There are some trade offs with compress. While compression greatly reduces the amount of storage space required. Most of the time you can compress up to about 5 columns in a table before you start to see performance impacts. The value is stored in the table header.

it increases the processing overhead whenever a compressed column is accessed because the location of the data must be computed on the fly. While compression greatly reduces the amount of storage space required. header.Compress Compressing a column value can save valuable disk space. There are some trade offs with compress. Because your business is located in California most of the values in your database have a state code of CALIFORNIA. you might have a State in your database like CALIFORNIA. You can compress the value CALIFORNIA and instead of storing it on the disk for almost every row you can compress the value. The compress allows you to specify a value in a column and not store that value. A Volatile Table does not support compression. The value is stored in the table For example. Most of the time you can compress up to about 5 columns in a table before you start to see performance impacts. Tera-Tom Notes 121 .

Substring The SUBSTRING function is used to extract a portional character string from character data. 122 Tera-Tom Notes Copyright OSS 2001 . The following page shows some examples.

This example uses literals: SELECT SUBSTRING(‘Hello’ FROM 2 FOR 3) AS S1 . SUBSTRING(‘Hello’ FROM 2) AS S2 .Substring Substring extracts a substring from a named string based on position. One row returned S1 ell S2 ello Tera-Tom Notes 123 . You will describe the starting position of the substring and the length of the substing to be extracted from the string expression. The Substring function will be performed on a string expression. The expression can be a column value or a literal.

The following would return 3 due to the ‘c’ being the third character in the string: INDEX(‘abcdef’. Its functionality is exactly the same as INDEX.Result = 3 An advanced usage is shown as an example on the following page.’c’) . 124 Tera-Tom Notes Copyright OSS 2001 . however it is written differently. The INDEX looks for an ‘n’ and when found. The SUBSTRING uses it to return the opposite character – hence converts Y to N and N to Y in a single pass of the rows in the table. The INDEX function returns a number that represents the location of one or more characters in a string when compared to the second string.INDEX and POSITION functions The POSITION and INDEX functions allow you check the contents of character data to determine if a different partial string is a subset of the other. it returns a 1.Result = 3 The newer ANSI standard code for this function is POSITION. Otherwise. The page also shows the exact same operation using the CASE as an alternative. The following would return 3 due to the ‘c’ being the third character in the string: POSITION(’c’ IN ‘abcdef’) . it returns a 0.

POSITION( ‘e’ IN lname ) FROM EMPxx .POSITION and INDEX The POSITION and the INDEX functions are used to determine whether or not a character string is contained in another character string: SELECT Lname . the results of the POSITION function are: Lname Jones Davis Marley POSITION( ‘e’ IN lname ) 4 0 5 Tera-Tom Notes 125 . Using the following three names.

As a matter of fact the user must also have READ privileges on the table being updated. For an UPDATE to a table the user must have UPDATE privileges.UPDATE The UPDATE command updates a table. This can be done through a view or a self-join also. The following page shows the syntax. 126 Tera-Tom Notes Copyright OSS 2001 .

Tera-Tom Notes 127 .Update The UPDATE command updates a table. This can be done through a view or a self-join also. UPDATE Empxx SET Sal = 50000 WHERE Emp = 99. For an UPDATE to a table the user must have UPDATE privileges.000. This example gives employee 99 a new salary of $50. As a matter of fact the user must also have READ privileges on the table being updated.

This means that each column defines the data type definition. The Primary Index is specified at TABLE CREATE time. This follows the column name. Each column in the table can have a definition set. 128 Tera-Tom Notes Copyright OSS 2001 .Creating a Table The CREATE TABLE statement is used to create a new table.

This means that each column defines the data type definition.fname Char(20) . Each column in the table can have a definition set.2) ) Unique Primary Index (emp). Tera-Tom Notes 129 .Sal Decimal (10. The Primary Index is specified at TABLE CREATE time.Creating a Table The CREATE TABLE statement is used to create a new table.lname Char(20) .dept Integer . This follows the column name Create Table EmpXX ( emp Integer .

They are shown on the following pages. 130 Tera-Tom Notes Copyright OSS 2001 .CASE Statement (Option 1) The CASE statement has two different syntax options.

1. The basic syntax of the CASE follows: 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. Course_name Logical Database Design V2R3 SQL Features Advanced SQL Number of Credits 2 Credits 2 Credits 3 Credits Tera-Tom Notes 131 .CASE Statement (Option 1) The CASE function provides an additional level of data testing after a row is accepted by the WHERE clause.

They are shown on the following pages.CASE Statement (Option 2) The CASE statement has two different syntax options. 132 Tera-Tom Notes Copyright OSS 2001 .

IN. Grade_Point_Average High Decimal value 4.9 THEN ‘High Decimal value’ ELSE ‘4. Option two is more flexible. In this option you can only check for equality. SELECT CASE WHEN Grade_pt IN (1.0 GPA Tera-Tom Notes 133 .0 GPA’ END AS Grade_Point_Average FROM Student_table.0 GPA High Decimal value 4. With Option two you can check for <>.3) THEN ‘Integer GPA’ WHEN Grade_pt BETWEEN 1 AND 2 THEN ‘Low Decimal value’ WHEN Grade_pt < 3. between.2. etc. In Option two after the word CASE is the word WHEN.CASE Statement (Option 2) In Option one after the word CASE was an immediate column name.

If the NULL was intended to represent a zero. Since aggregates ignore NULLs in the data. However. The COALESE will continue to look at columns or values until it finds a nonNULL and it will be returned. 134 Tera-Tom Notes Copyright OSS 2001 . in particular the AVG function. the result will be incorrect. Then. Another use for situation is when there is a potential for a column to contain a NULL. if all of the values checked contain NULL.COALESCE Option The COALESCE option will allow you to have options to manipulate nulls. it has no choice but to return a NULL. A situation where COALESCE can help. when it is a NULL another column is to be used to return its value. The following page gives some examples of using the logic. The COALESCE can convert the NULL values to zero and use them in the aggregate. relates to the use of aggregates. the average using NULL will be a higher result then when a zero is used.

HomePhone.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. ‘No Phone’) as Phone From Employee. Think of Coalesce another way: CASE When Y is not null then Y WHEN Z is not null then Z ELSE NULL SELECT Name. Coalesce(WorkPhone. Three Rows Returned Name --------------Jim Blue Jane Green Bill Davis Phone --------------------(513) 300-0341 No Phone (643) 888-3939 Tera-Tom Notes 135 .

136 Tera-Tom Notes Copyright OSS 2001 . The number of expressions used as the argument for an aggregate has unlimited arguments.Distinct Option The Distinct option eliminates duplicate values in an answer set.

Class_code FR JR SO SR Tera-Tom Notes 137 .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.

The ZEROIFNULL converts NULLS to zeros.NULLIFZERO and ZEROIFNULL The NULLIFZERO command converts zeros to NULLS. 138 Tera-Tom Notes Copyright OSS 2001 .

ZEROIFNULL(Salary) AS NONULL FROM Employee.NULLIFZERO(Salary) As NOZERO . SALARY -------------0 40000 NULL 50000 NOZERO -------------NULL 40000 NULL 50000 NONULL -------------0 40000 0 50000 Tera-Tom Notes 139 . The ZEROIFNULL command converts NULLS to zeros.NULLIFZERO and ZEROIFNULL The NULLIFZERO command converts zeros to NULLS. Employee Table Emp 1 2 3 4 Dept 10 10 10 20 Lname Smith Jones Wilson Lane Sal 0 40000 NULL 50000 SELECT Salary .

The SQL Flag will display NON-ANSI SQL. 140 Tera-Tom Notes Copyright OSS 2001 . They stand for FULL. The SQL FLAG can be set to: FULL INTERMEDIATE NONE ENTRY Remember the letters FINE. NONE. AND ENTRY. INTERMEDIATE.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 can be set to: FULL INTERMEDIATE NONE ENTRY Remember the letters FINE. They stand for FULL. Tera-Tom Notes 141 .SQL Flag The SQLFLAG command enables or disables the SQL Flagger. AND ENTRY. INTERMEDIATE. The SQL Flag will display NON-ANSI SQL. The SQL Flagger generates a warning message when nonstandard SQL is used. NONE.

A right outer join returns non-matching rows from its "right" table and extends them with nulls. 142 Tera-Tom Notes Copyright OSS 2001 . The type of outer join (in this case.Left Outer Join An outer join is an extension of an inner join. These are called non-matching rows. and in addition. 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. or both tables. LEFT OUTER . The other outer join types are right and full. Thus. An outer join is two or more tables that perform an inner join. The reserved word OUTER is optional. return rows from the “left” join table.Left means the first table listed in the FROM clause. left). a left outer join. Having a join condition specified in an ON clause within a FROM clause is always required if the keyword JOIN is specified for either an inner join or an outer join. specified by the keyword LEFT indicates the source of the rows not returned in the result of the inner join. the "right" join table. Nulls: The key feature of the outer join is that in returning rows from the "left" join table. or both tables which were not returned in the result of the inner join. specified by the key words RIGHT and FULL. extending these rows with null values. returns non-matching rows from its "left" table (table A) and extends them with null values. but contain NULLs in the rows with no match. the outer join extends the rows that have no matching values with nulls. as if these values came from the corresponding table. or the right join table. A full outer join returns non-matching rows from both its tables and extends them with nulls. as in the example above. in addition to performing an inner join of two or more tables according to a join condition.

emp FROM Skills LEFT OUTER JOIN empxx ON skills.Left Outer Join Skills Table EmpXX Table 01 02 03 04 05 06 Mason Doctor Lawyer Teacher Nurse Baker 8888 9333 8854 8121 0043 4320 01 01 03 04 01 06 Skill Skill Emp Skill No No SELECT Skills. Outer Join Results Mason Mason Mason Doctor Lawyer Teacher Nurse Baker 8888 9333 0043 NULL 8854 8121 NULL 4320 Tera-Tom Notes 143 .skillno = Empxx.Skillno. EmpXX.skill.

return rows from the “left” join table. specified by the key words LEFT and FULL. extending these rows with null values. as if these values came from the corresponding table. These are called non-matching rows. Having a join condition specified in an ON clause within a FROM clause is always required if the keyword JOIN is specified for either an inner join or an outer join. returns non-matching rows from its "right" table (table B) and extends them with null values.Right means the second table listed in the FROM clause. the outer join extends the rows that have no matching values with nulls. the "left" join table. A left outer join returns non-matching rows from its "left" table and extends them with nulls. or both tables. The reserved word OUTER is optional. Nulls: The key feature of the outer join is that in returning rows from the "right" join table. specified by the keyword RIGHT indicates the source of the rows not returned in the result of the inner join. RIGHT OUTER .Right Outer Join An outer join is an extension of an inner join. in addition to performing an inner join of two or more tables according to a join condition. An outer join is two or more tables that perform an inner join. right). Thus. The other outer join types are left and full. 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. and in addition. as in the example. or the right join table. or both tables which were not returned in the result of the inner join. but contain NULLs in rows with no match. A full outer join returns non-matching rows from both its tables and extends them with nulls. 144 Tera-Tom Notes Copyright OSS 2001 . a right outer join. The type of outer join (in this case.

Right Outer Join Skills Table EmpXX Table 01 02 03 04 05 06 Mason Doctor Lawyer Teacher Nurse Baker 8888 9333 8854 8121 0043 4320 01 01 03 04 07 06 Skill Skill Emp Skill No No SELECT Skills.skillno = Empxx.skillno. EmpXX.emp FROM Skills Right OUTER JOIN EmpXX ON skills.skill. Outer Join Results Mason Mason Lawyer Teacher Baker NULL 8888 9333 8854 8121 4320 0043 Tera-Tom Notes 145 .

extending these rows with null values.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. return rows from the “left” join table. 146 Tera-Tom Notes Copyright OSS 2001 . and in addition. FULL OUTER . or both tables which were not returned in the result of the inner join. or the right join table.Full Outer Join An outer join is an extension of an inner join. An outer join is two or more tables that perform an inner join.

skillno = Empxx.FULL Outer Join Skills Table EmpXX Table 01 02 03 04 05 06 Skill No Mason Doctor Lawyer Teacher Nurse Baker Skill 8888 9333 8854 8121 0043 4320 Emp 01 01 03 04 07 06 Skill No SELECT Skills. Outer Join Results Mason Mason Doctor Lawyer Teacher Nurse Baker NULL 8888 9333 NULL 8854 8121 NULL 4320 0043 Tera-Tom Notes 147 .emp FROM Skills FULL OUTER JOIN EmpXX ON skills. Empxx.skill.skillno.

Sign up to vote on this title
UsefulNot useful