SlideShare une entreprise Scribd logo
1  sur  280
undefined
Introduction to Teradata SQL                (Module 1)

Objectives
After completing this module, you should be able to:

       Describe the structure of a Relational Database Management System (RDBMS).
       Explain the role of Structured Query Language (SQL) in accessing a Relational Database.
       List the three categories of SQL statements and describe their function.



What is an RDBMS?

Data is organized into tables in a relational database management system (RDBMS). Rows in the
table represent instances of an entity, in this case an employee or a department. Columns
represent the data fields which comprise the rows. Relations between tables occur when a
column in one table also appears as a column in another.

Here is an example of two related tables:
Can you answer the following questions using the tables above?


   Question 1:      What is the department name for employee 1004?

   Question 2:      Who is the manager of employee 1004?


What is SQL?

Structured Query Language (SQL) is the industry standard language for communicating with
Relational Database Management Systems. SQL is used to look up data in relational tables,
create tables, insert data into tables, grant permissions and many other things.

Structured Query Language is used to define the answer set that is returned from the Teradata
Database.

SQL is a non-procedural language, meaning it contains no procedural-type statements such as
those listed here:

      GO TO
      PERFORM
      DO LOOP
      OPEN FILE
CLOSE FILE
      END OF FILE



SQL Commands

SQL statements commonly are divided into three categories:

   1. Data Definition Language (DDL) - Used to define and create database objects such as
      tables, views, macros, databases, and users.
   2. Data Manipulation Language (DML) - Used to work with the data, including such tasks
      as inserting data rows into a table, updating an existing row, or performing queries on the
      data. The focal point of this course will be on SQL statements in this category.
   3. Data Control Language (DCL) - Used for administrative tasks such as granting and
      revoking privileges to database objects or controlling ownership of those objects. DCL
      statements will not be covered in detail in this course. For complete Data Control
      Language coverage, please see the NCR Customer Education "Teradata Database
      Administration" course.

Data Definition Language (DDL) Examples

   SQL statement                                      Function
        CREATE         Define a table, view, macro, index, trigger or stored procedure.
         DROP          Remove a table, view, macro, index, trigger or stored procedure.
        ALTER          Change table structure or protection definition.

Data Manipulation Language (DML)

   SQL statement                                      Function
       SELECT         Select data from one or more tables.
       INSERT         Place a new row into a table.
       UPDATE         Change data values in one or more existing rows.
       DELETE         Remove one or more rows from a table.

Data Control Language (DCL)

   SQL statement                                      Function
        GRANT         Give user privileges.
       REVOKE         Remove user privileges.
        GIVE          Transfer database ownership.


Relational Concepts
The figure below illustrates six rows of a much larger table.

Some interesting things to note about this table:

       The intersection of a row and a column is a data value. Data values come from a
       particular domain. Domains represent the pool of legal values for a column. For example,
       the data values in the EMPLOYEE NUMBER and MANAGER EMPLOYEE NUMBER come from the
       same domain because both columns come from the pool of employee numbers. The
       domain of employee numbers might be defined as the pool of integers greater than zero.
       The EMPLOYEE NUMBER column is marked PK, which indicates that this column holds the
       Primary Key. The next 3 columns are marked FK, which stands for Foreign Key.
       The purpose of the Primary Key is to uniquely identify each record. No two values in a
       primary key column can be identical.
       A Foreign Key represents the Primary Key of another table. Relationships between tables
       are formed through the use of Foreign Keys.
Teradata SQL (Module 2)

Objectives

After completing this module, you should be able to:

         Describe the uses of the Teradata SQL SELECT statement.
         Retrieve data from a relational table using the SELECT statement.
         Use the SQL ORDER BY and DISTINCT options.
         Set a default database using the DATABASE command.
         Write SQL statements using recommended coding conventions.
         Name database objects according to Teradata SQL rules.



SELECT

Structured Query Language (SQL) consists of three types of statements, previously defined
as:

Data Definition Language (DDL)

  - Used to create, drop and modify objects
Data Manipulation Language(DML)

  - Used to add, delete, update and read data rows in a table
Data Control Language(DCL)
  - Used to implement security and control on database objects.

Our focus in this course will be mostly on the DML portion of the language. We will first look at the
SELECT statement.

The SELECT statement allows you to retrieve data from one or more tables. In its most common form,
you specify certain rows to be returned as shown.

SELECT     *
FROM       employee
WHERE      department_number = 401;

The asterisk, "*", indicates that we wish to see all of the columns in the table. The FROM clause
specifies from which table in our database to retrieve the rows. The WHERE clause acts as a filter
which returns only rows that meet the specified condition, in this case, records of employees in
department 401.

Note: SQL does not require a trailing semicolon to end a statement but the Basic Teradata Query
(BTEQ) utility that we use to enter SQL commands does require it. All examples in this course will
include the semicolon.
What if we had not specified a WHERE clause.

SELECT     * FROM employee;

This query would return all columns and all rows from the employee table.

Instead of using the asterisk symbol to specify all columns, we could name specific columns
separated by commas:

SELECT     employee_number
           ,hire_date
           ,last_name
           ,first_name
FROM       employee
WHERE      department_number = 401;
employee_number            hire_date           last_name          first_name
--------------------       ----------          -----------        -----------
1004                       76/10/15            Johnson            Darlene
1003                       76/07/31            Trader             James
1013                       77/04/01            Phillips           Charles
1010                       77/03/01            Rogers             Frank
1022                       79/03/01            Machado            Albert
1001                       76/06/18            Hoover             William
1002                       76/07/31            Brown              Alan

Unsorted Results

Results come back unsorted unless you specify that you want them sorted in a certain way. How
to retrieve ordered results is covered in the next section.


ORDER BY Clause

Use the ORDER BY clause to have your results displayed in a sorted order. Without the ORDER
BY clause, resulting output rows are displayed in a random sequence.

SELECT      employee_number
            ,last_name
            ,first_name
            ,hire_date
FROM        employee
WHERE       department_number = 401
ORDER BY    hire_date;



Sort Direction

In the example above, results will be returned in ascending order by hire date. Ascending order
is the default sort sequence for an ORDER BY clause. To explicitly specify ascending or
descending order, add ASC or DESC, to the end of the ORDER BY clause. The following is an
example of a sort using descending sequence.

ORDER BY hire_date DESC;


Naming the Sort Column

You may indicate the sort column by naming it directly (e.g., hire_date) or by specifying its
position within the SELECT statement. Since hire_date is the fourth column in the SELECT
statement, the following ORDER BY clause is equivalent to saying ORDER BY hire_date.

ORDER BY 4;


Multiple ORDER BY Columns

An ORDER BY clause may specify multiple columns. No single column in an ORDER BY clause
should exceed a length of 4096 bytes, otherwise it will be truncated for sorting purposes.

The order in which columns are listed in the ORDER BY clause is significant. The column named
first is the major sort column. The second and subsequent are minor sort columns. In the
following example, results are sorted by department number in ascending order. Where
multiple records share the same department number, those rows are sorted by job_code in
ascending order. The following are examples:

SELECT          employee_number
                ,department_number
                ,job_code
FROM            employee
WHERE           department_number < 302
ORDER BY        department_number
                ,job_code;
  employee_number          department_number          job_code
    --------------------     ----------------------    ----------
                   801                         100      111100
                  1025                         201      211100
                  1021                         201      222101
                  1019                         301      311100
                  1006                         301      312101
                  1008                         301      312102


Note: Each column specified in the ORDER BY clause can have its own sort order, either
ascending or descending.

SELECT           employee_number
                 ,department_number
                 ,job_code
FROM             employee
WHERE            department_number < 302
ORDER BY         department_number ASC
                 ,job_code DESC;
employee_number                     department_number               job_code
           --------------------                ----------------------         ----------
                          801                                    100           111100
                         1021                                    201           222101
                         1025                                    201           211100
                         1008                                    301           312102
                         1006                                    301           312101
                         1019                                    301           311100



DISTINCT

The DISTINCT operator will consolidate duplicate output rows to a single occurrence.

Example Without DISTINCT


SELECT        department_number
              ,job_code
FROM          employee
WHERE         department_number = 501;
             department_number                                 job_code
               ----------------------                           ----------
                                  501                             512101
                                  501                             512101
                                  501                             511100


Note: Two people in department 501 have the same job code (512101). If our purpose is
simply to find out which job codes exist in department 501, we could use DISTINCT to avoid
seeing duplicate rows.

Example With DISTINCT


SELECT        DISTINCT department_number
              ,job_code
FROM          employee
WHERE         department_number = 501;
             department_number          job_code
               ----------------------    ----------
                                  501     511100
                                  501     512101


Note: DISTINCT appears directly after SELECT, and before the first named column. It may
appear to apply only to the first column, but in fact, DISTINCT applies to all columns named in
the query. Two rows in our result example set both have department_number 501. The
combination of department_number and job_code are distinct since the job codes differ.


Naming Database Objects

All Teradata objects, such as tables, must be assigned a name by the user when they are
created.

These rules for naming objects are summarized as follows:

Names are composed of:         a-z
                               A-Z
                               0-9
                               _ (underscore)
                               $
                               #



Names are limited to 30 characters.
Names cannot begin with a number.

Teradata names are not case-sensitive.

Examples of valid names:

Accounts
Accounts_2005
accounts_over_$2000
Account#

Equivalence

Accounts and accounts represent the same table. Case is not considered.

Naming Rules

Naming Syntax

        Database names and User names must be unique within the Teradata Database.
        Table, view, macro, trigger, index and stored procedure names must be unique within
        a Database or User.
        Column names must be unique within a Table.

The syntax for fully qualifying a column name is:

Databasename.Tablename.Columnname
Example
 NAME                                    (unqualified)

 EMPLOYEE.NAME                           (partially qualified)

 PAYROLL.EMPLOYEE.NAME                   (fully qualified)
Note: The amount of qualification necessary is a function of your default database setting.


Coding Conventions

SQL is considered a 'free form' language, that is, it can cover multiple lines of code and there
is no restriction on how much 'white space' (i.e., blanks, tabs, carriage returns) may be
embedded in the query. Having said that, SQL is syntactically a very precise language.
Misplaced commas, periods and parenthesis will always generate a syntax error.

The following coding conventions are recommended because they make it easier to read,
create, and change SQL statements.

Recommended Practice

SELECT   last_name
          ,first_name
         ,hire_date
         ,salary_amount
FROM      employee
WHERE    department_number = 401
ORDER BY last_name;

Not Recommended Practice

select last_name, first_name, hire_date, salary_amount
from employee where department_number = 401 order by last_name;

The first example is easy to read and troubleshoot (if necessary). The second example
appears to be a jumble of words. Both, however, are valid SQL statements.


Default Database

Setting the Default Database

As a valid user, you will normally have access rights to your own user database and the
objects it contains. You may also have permission to access objects in other databases.

The user name you logon with is usually your default database. (This depends on how you
were created as a user.)
For example, if you log on as:

  .logon rayc;

  password: xyz

then "rayc" is normally your default database.

Note the dot (.) before "logon". Commands that begin with a dot are BTEQ commands, not
SQL commands. The BTEQ command processor will read this command; the SQL processor
will not see it.

Queries you make that do not specify the database name will be made against your default
database.

Changing the Default Database

The DATABASE command is used to change your default database.

For example:

DATABASE payroll;
sets your default database to payroll. Subsequent queries (assuming the proper privileges are
held) are made against the payroll database.


Lab

For this set of lab questions you will need information from the Database Info document.

These exercises are to be done as a pencil-and-paper workshop. Write SQL statements as
you would enter them on-line. Click on the buttons to the left to see the answers.

Question 3:

   A. Select all columns for all departments from the department table.
   B. Using the employee table, generate a report of employee last and first names and
      salary for all of manager 1019's employees. Order the report in last name ascending
      sequence.
   C. Modify the previous request to show department number instead of first name. Make
      it for manager 801's employees instead of manager 1019's.
   D. Prepare a report of the department numbers and the manager's employee numbers
      for everyone in the employee table. Now add the DISTINCT option to the same report.

Note: Save your answers for this Lab, as you actually enter and run these exercises using
BTEQ scripts for the Labs in Module 3.



Simple BTEQ (Module 3)
Objectives

After completing this module, you should be able to:

       Use BTEQ to submit SQL to the Teradata database.
       Set session parameters to enable
                   Teradata transaction semantics.
                   The SQL Flagger.



What is BTEQ?

BTEQ is a front end tool for submitting SQL queries. 'BTEQ' stands for Basic Teradata Query
program.

BTEQ is client software that resides on your network or channel-attached host. After starting
BTEQ, you will log on to Teradata using a TDP-id (Teradata Director Program id), your user
id and password. The TDP-id identifies the instance of Teradata you are going to access.

TDP's come in two varieties - the standard TDP for channel-attached clients, and the Micro-
TDP (or MTDP) for network-attached clients.

They are involved in getting your SQL requests routed to a Parsing Engine (PE) which
validates your request and passes it to the Access Module Processors (AMPs). AMPs retrieve
the answer sets from the disks and send the response set back to the PE which in turn
forwards it to the TDP and ultimately back to you at your session.

Where is BTEQ Located?

BTEQ is Teradata client software which is installed on mainframe hosts or network attached
clients. It operates under all host systems and local area networks (LANs).

BTEQ Commands

Facts about BTEQ commands:

       Must be preceded by a period (.) or terminated by a semi-colon or both.
       Provide an output listing (an audit trail) of what occurred.
       Additional commands for report formatting are available.
       Are not case-sensitive.

Invoking BTEQ varies somewhat depending on the platform. In the UNIX enviroment, simply
typing in the command 'bteq' is required.

For purposes of this course, instructions for starting a lab session are contained on each lab
page.


Using BTEQ Interactively
Submitting SQL Statements with BTEQ

There are two ways to submit SQL statements to BTEQ in interactive mode:

       Type in SQL statements directly to the BTEQ prompt.
       Open another window with a text editor. Compose SQL statements using the text
       editor, then cut and paste the SQL to the BTEQ prompt.

When users log on to BTEQ, they are by default assigned a single session.


Session Parameters

Session parameters include transaction semantics and the SQL Flagger.

Transaction semantics, allows you to set your session in either ANSI or Teradata (BTET)
mode. All features of Teradata SQL will work in either mode, but each mode activates
different case-sensitivity and data conversion defaults, and so the same query might return
different results in each mode.

For purposes of this course, Teradata-mode sessions will be assumed unless otherwise
specified. More on these session parameters is covered in the Teradata SQL Advanced WBT.

Example

.SET SESSION TRANSACTION ANSI; /* Sets ANSI mode*/

.SET SESSION TRANSACTION BTET; /* Sets Teradata mode*/

Note: All text between /* and */ are treated as comments by BTEQ.

You may also activate the ANSI Flagger, which automatically flags non-ANSI compliant
syntax with a warning but still returns the expected answer set.

Example

.SET SESSION SQLFLAG ENTRY; /* Causes non-Entry level ANSI syntax to be
flagged */

SELECT DATE; /* Causes a warning because keyword DATE is not ANSI
standard*/

*** SQL Warning 5821 Built-in values DATE and TIME are not ANSI.
*** Query completed. One row found. One column returned.
*** Total elapsed time was 1 seconds.

   Date
--------
05/01/12
Example

.SET SESSION SQLFLAG NONE /* Disables ANSI Flagger*/

SELECT DATE; /* DATE keyword is not flagged */

*** Query completed. One row found. One column returned.
*** Total elapsed time was 1 second.

   Date
--------
05/01/12

Note: In both cases, the date was returned.

You need to establish your session parameters prior to logging on. Teradata extensions
cannot be disabled, but they can be flagged using the ANSI flagger.


The SHOW CONTROL Command

The BTEQ .SHOW CONTROL command displays BTEQ settings. The following output shows
the result of this command.

 .SHOW CONTROL

 Default   Maximum Byte Count          = 4096
 Default   Multiple Maximum Byte Count = 2048
 Current   Response Byte Count         = 4096
 Maximum   number of sessions          = 20
 Maximum   number of the request size = 32000

 EXPORT RESET
 IMPORT FIELD
 LOGON   L7544/tdxxx
 RUN
 [SET] ECHOREQ               =   ON
 [SET] ERRORLEVEL            =   ON
 [SET] FOLDLINE              =   OFF ALL
 [SET] FOOTING               =   NULL
 [SET] FORMAT                =   OFF
 [SET] FORMCHAR              =   OFF
 [SET] FULLYEAR              =   OFF
 [SET] HEADING               =   NULL
 [SET] INDICDATA             =   OFF
 [SET] NOTIFY                =   OFF
 [SET] NULL                  =   ?
 [SET] OMIT                  =   OFF ALL
 [SET] PAGEBREAK             =   OFF ALL
 [SET] PAGELENGTH            =   55
 [SET] QUIET                 =   OFF
 [SET] RECORDMODE            =   OFF
 [SET] REPEATSTOP            =   OFF
[SET]   RETCANCEL         =    OFF
 [SET]   RETLIMIT          =    No Limit
 [SET]   REPEATSTOP        =    OFF
 [SET]   RETCANCEL         =    OFF
 [SET]   RETLIMIT          =    No Limit
 [SET]   RETRY             =    ON
 [SET]   RTITLE            =    NULL
 [SET]   SECURITY          =    NONE
 [SET]   SEPARATOR         =    two blanks
 [SET]   SESSION CHARSET   =    ASCII
 [SET]   SESSION SQLFLAG   =    NONE
 [SET]   SESSION TRANSACTION    = BTET
 [SET]   SESSIONS          =    1
 [SET]   SIDETITLES        =    OFF for the normal report.
 [SET]   SKIPDOUBLE        =    OFF ALL
 [SET]   SKIPLINE          =    OFF ALL
 [SET]   SUPPRESS          =    OFF ALL
 [SET]   TDP               =    L7544
 [SET]   TIMEMSG           =    DEFAULT
 [SET]   TITLEDASHES       =    ON for the normal report.
 [SET]   UNDERLINE         =    OFF ALL
 [SET]   WIDTH             =    75


BTEQ Scripts

A BTEQ script is a file that contains BTEQ commands and SQL statements. A script is built
for sequences of commands that are to be executed on more than one occasion, i.e.
monthly, weekly, daily.

How to create a BTEQ Script

To create and edit a BTEQ script, use an editor on your client workstation. For example, on
a UNIX workstation, use either the vi or text editor.


How to Submit a BTEQ Script

Start BTEQ, then enter the following BTEQ command to submit a BTEQ script:

  .run file = <scriptname>


BTEQ Comments -- Teradata Extensions

The Teradata RDBMS supports comments that span multiple lines by using the "/*" and
"*/" as delimiters.

Example of a BTEQ comment:

     /* You can include comments in a BTEQ
    script by enclosing the comment text between “/*” and “*/”
    and the comment may span multiple lines */
Script Example

Let's look at an example of a BTEQ script using ANSI standard comments. The ANSI
comment delimiter is the double dash, --.

(This script is named mod2exer.scr )

   .SET SESSION TRANSACTION ANSI
   .LOGON L7544/tdxxx,;

   -- Obtain a list of the department numbers and names
   -- from the department table.

   SELECT    department_number
              ,department_name
   FROM      department;

   .QUIT

Note: Both Teradata style (/* */) and ANSI style (--) comments may be included in any
SQL command script.


To Execute The Script:

   .run file=mod2exer.scr

(The following is the output generated by the above command.)

Script started on Sat Feb 15 10:48:19 1997
$ bteq

Teradata BTEQ 04.00.01.00 for UNIX5. Enter your logon or BTEQ command:

 .run file=mod2exer.scr                (this is the only user input; the rest of the commands came from
                                       file mod2exer.scr)

.run file=mod2exer.scr
Teradata BTEQ 04.00.01.00 for UNIX5. Enter your logon or BTEQ command:

.LOGON L7544/tdxxx,

***   Logon successfully completed.
***   Transaction Semantics are ANSI.
***   Character Set Name is 'ASCII'.
***   Total elapsed time was 1 second.

BTEQ -- Enter your DBC/SQL request or BTEQ command:
-- Obtain a list of the department numbers and names
-- from the department table.

SELECT department_number
,department_name
FROM department;

*** Query completed. 9 rows found. 2 columns returned.
*** Total elapsed time was 1 second.

 department_number                department_name
 ------------------               -----------------
                  401             customer support

<rest of result rows are not shown in this screen capture>

BTEQ -- Enter your DBC/SQL request or BTEQ command:

.QUIT
*** You are now logged off from the DBC.
*** Exiting BTEQ...
*** RC (return code) = 0
# exit


Using BTEQ in BATCH Mode

If you prefer to write all SQL statements in a single script file, there are two ways you
may execute the script:

        Start BTEQ in interactive mode. Use the following BTEQ command to execute the
        script:

        .run file = mod2exer.scr

        Start BTEQ and redirect standard input to use the script file.

        $bteq < mod2exer.scr

        (Note: The dollar sign ‗$‘ corresponds to the UNIX prompt.)

How to Capture BTEQ Session Output

From a UNIX workstation, use the script <filename> command to capture the output of
your session :

$script <filename>               Logs all input and output to <filename>.
$bteq                            Starts BTEQ in interactive mode.
.run file = <scriptname>         Submits pre-written script which contains BTEQ
commands and SQL statements.

The contents of <scriptname> and responses from the Teradata database will be output
to both the screen and the designated <filename> if one has been designated.

How to Stop Capturing BTEQ Session Output

From a UNIX workstation, issue the following UNIX command to stop the script
command:

   $exit
This closes the logging file but does not terminate the UNIX session.


Identifying Syntax Errors

BTEQ output results will display a "$" to indicate the location where the error was
detected in either the script or request. The following is an example of captured output
showing a syntax error:


Script started on Thu Oct 24 16:21:21 1996
# bteq
   …

   Teradata BTEQ 04.00.00.00 for UNIX5. Enter your logon or BTEQ command:

.logon L7544/tdxxx,

***   Logon successfully completed.
***   Transaction Semantics are ANSI.
***   Character Set Name is 'ASCII'.
***   Total elapsed time was 1 second.

   BTEQ    --    Enter your DBC/SQL request or BTEQ command:

 SELECT             department_number
                    ,DISTINCT department_name
 FROM               department;
                    ,DISTINCT department_name
                    $
 *** Failure 3708 Syntax error, 'DISTINCT' that follows the ',' should be
deleted.


      Statement# 1,    Info =36
      *** Total elapsed time was 1 second

.BTEQ -- Enter your DBC/SQL request or BTEQ command:
.quit
  *** You are now logged off from the DBC.
  *** Exiting BTEQ...
  *** RC (return code) = 8
# exit

script done on Thu Oct 24 16:21:39 1996


The dollar sign points to the command DISTINCT. The error text tells us that DISTINCT
should be deleted. The DISTINCT command must directly follow the SELECT command in
your request.


Lab
For this set of lab questions you will need information from the Database Info document.

To start the online labs, click on the Telnet button in the lower left hand screen of the
course. Two windows will pop-up: a BTEQ Instruction Screen and your Telnet Window.
Sometimes the BTEQ Instructions get hidden behind the Telnet Window.
You will need these instructions to log on to Teradata.

Be sure to change your default database to the Customer_Service database in
order to run these labs.

Question 4:

   A. See Labs A, B, and C from Module 2 that you did on paper. You can use NotePad or
      another text editor to create your SQL requests again, and then simply copy and
      paste them into the Telnet window after you've logged on with BTEQ.
   B. Use BTEQ to submit your two reports from Lab D in Module 2. Observe the number
      of rows returned in your output. Which rows were eliminated due to the DISTINCT
      option?

       Click on the Lab B button to see the answer for this Lab.

   C. Set the ANSI Flagger ON and observe the differences it produces.

       Do this by:

       Logging off of Teradata (.logoff).
       Setting the flagger on (.SET SESSION SQLFLAG ENTRY).
       Relogging on to Teradata

       Resubmit your query from Lab A.1.
       What differences do you observe?
       Why?

       (Note: the ANSI Flagger is covered in more detail in SQL Level 3.)
Click on the Lab C button to see the answer for this Lab.

     D. 1) Determine the default system session transaction mode. What command did
        you use?

          2) Set the session transaction mode to the opposite setting (e.g., set it to ANSI if
          the system default is BTET) then verify the new setting.

          Click on the Lab D button to see the answer for this Lab.



Lab Answer A.A
DATABASE Customer_Service;
SELECT * FROM department ORDER BY 1;

*** Query completed. 9 rows found. 4 columns returned. *** Total elapsed time was 1 second.

department_number         department_name           budget_amount         manager_employee_number
-----------------------    ---------------------     ------------------    ---------------------------------
                  100      president                 400000.00              801
                  401      customer support          982300.00              1003
                  403      education                 932000.00              1005
                  402      software support          308000.00              1011
                  302      product planning          226000.00              1016
                  501      marketing sales           308000.00             1017
                  301      research and development 465600.00               1019
                  201      technical operations       293800.00             1025
                  600      None                      ?                      1099



Note: Order is random. And user input is highlighted in red



Lab Answer A.B

 SELECT last_name
 ,first_name
 ,salary_amount
 FROM     employee
 WHERE manager_employee_number                          =   1019
 ORDER BY       last_name
 ;


*** Query completed. 2 rows found. 3 columns returned.
 last-name                 first-name                   salary-amount
 Kanieski                  Carol                             29250.00
 Stein                     John                              29450.00
Lab Answer A.C

 SELECT last_name
       ,department_number
       ,salary_amount
 FROM      employee
 WHERE    manager_employee_number    =    801
 ORDER BY      last_name
 ;


*** Query completed. 8 rows found. 3 columns returned.
last_name department_number salary_amount
Daly                     402         52500.00
Kubic                    301         57700.00
Rogers                   302         56500.00
Runyon                   501         66000.00
Ryan                     403         31200.00
Short                    201         34700.00
Trader                   401         37850.00
Trainer                  100        100000.00



Lab Answer B
SELECT   department_number
          ,manager_employee_number
 FROM     employee
 ;


*** Query completed. 26 rows found. 2 columns returned.
 department_number    manager_employee_number

                301                      1019
                501                       801
                100                       801
                401                       801
                402                      1011
                301                       801
                301                      1019
                402                       801
                401                      1003
                403                      1005
                401                      1003
                403                      1005
                403                       801
                201                       801
                201                      1025
                501                      1017
                403                      1005
                501                      1017
                401                      1003
                401                      1003
                401                      1003
                403                      1005
                403                      1005
                401                      1003
                501                      1017
                302                       801


SELECT   DISTINCT
  department_number
  ,manager_employee_number
FROM   employee
;

*** Query completed. 14 rows found. 2 columns returned.
 department_number    manager_employee_number

                100                       801
                201                       801
                201                      1025
                301                       801
                301                      1019
                302                       801
                401                       801
                401                      1003
402    801
402   1011
403    801
403   1005
501    801
501   1017
Lab Answer C

Note: Actual warning messages generated will vary depending on how you have
written your queries. Remember that ANSI does not support any lower case syntax.

.SET SESSION SQLFLAG ENTRY

.LOGON RPC1042/tdxxx;

SELECT *
FROM department
;

*** Query completed. 9 rows found. 4 columns returned.
*** Total elapsed time was 1 second.

FROM department
               $
*** SQL Warning 5836 Token is not an entry level ANSI Identifier or
Keyword.

department_number     department_name               budget_amount
manager_employ
-----------------     -----------------------       -------------      --------
------
               100    president                          400000.00
801
               401    customer support                   982300.00
1003
               403    education                          932000.00
1005
               402    software support                   308000.00
1011
               302    product planning                   226000.00
1016
               501    marketing sales                    308000.00
1017
               301    research and development           465600.00
1019
               201    technical operations               293800.00
1025
               600    None                                         ?
1099
The warning message is generated because the ANSI flagger is enabled
and is reporting that ANSI mode does not support lowercase syntax.



Lab Answer D
.SHOW CONTROL
       .
       .
       .
[SET] SESSION SQLFLAG = ENTRY
[SET] SESSION TRANSACTION = BTET
       .
       .
       .
.LOGOFF .SET SESSION TRANSACTION ANSI
.SHOW CONTROL
       .
       .
       .
[SET] SESSION SQLFLAG = ENTRY
[SET] SESSION TRANSACTION = ANSI
       .
       .
       .



HELP Functions Module 4

Objectives

After completing of this module, you should be able to:

       Obtain the definition of an existing Database, Table, View, or Macro using the
       HELP and SHOW statements.
       Determine how the Teradata RDBMS will process a SQL request using the
       EXPLAIN statement.



Teradata SQL Extensions

Several commands in our software are Teradata-specific. Here is a list of Teradata
extensions covered within this course.

ADD_MONTHS                  BEGIN/ END TRANSACTION
COLLECT/ DROP               COMMENT ON
STATISTICS
CONCATENATION               EXPLAIN
FALLBACK                    FORMAT
HELP                          INDEX
LOCKING                       MACRO Facility

                              • CREATE
                              • REPLACE
                              • DROP
                              • EXECUTE
NAMED                         NULLIFZERO/ZEROIFNULL
SHOW                          SUBSTR
TITLE                         TRIM
WITH                          WITH . . . BY

In this module, we focus on the following functions:

        EXPLAIN
        HELP
        SHOW



HELP Commands: Database objects

The HELP Command is used to display information about database objects such as (but
not limited to):

        Databases and Users
        Tables
        Views
        Macros

HELP retrieves information about these objects from the Data Dictionary. Below are the
syntactical options for various forms of the HELP command:

HELP Command

HELP DATABASE databasename;
HELP USER          username;
HELP TABLE         tablename;
HELP VIEW          viewname;
HELP MACRO         macroname;
HELP COLUMN        table or viewname.*; (all columns)
HELP COLUMN        table or viewname.colname . . ., colname;

Some of the other HELP commands which will be seen later in this course include:
HELP INDEX                tablename;
HELP STATISTICS           tablename;
HELP CONSTRAINT           constraintname;
HELP JOIN INDEX           join_indexname;
HELP TRIGGER              triggername;



The HELP DATABASE Command

The HELP DATABASE command in the following example shows all objects in the
Customer_Service database. Objects may be recognized by their 'Kind' designation as
follows:

      Table                   =T
      View                    =V
      Macro                   =M
      Trigger                 =G
      Join Index              =J
      Stored Procedure        =P

  HELP DATABASE Customer_Service;

Results will be displayed as follows:

Table/View/Macro               Kind        Comment
Name
contact                          T              ?
customer                         T              ?
department                       T              ?
employee                         T              ?
employee_phone                   T              ?
job                              T              ?
location                         T              ?
location_employee                T              ?
location_phone                   T              ?

All objects in this database are tables. The '?' is how BTEQ displays a null, indicating that
no user comments have been entered.

Note: To return HELP information on an object, a user must either own the object or
have at least one privilege on it.
The HELP TABLE Command

The HELP TABLE command shows the name, data type, and comment (if applicable), of
all columns in the specified table:

  HELP TABLE Customer_Service.employee
ColumnName                      Type Comment
employee_number                 I       System assigned identification
manager_employee_number         I       ?
department_number               I       Department employee works
                                        in
job_code                        I       Job classification designation
last_name                       CF      Employee surname
first_name                      CV      Employee given name
hire_date                       DA      Date employee was hired
birthdate                       DA      ?
salary_amount                   D       Annual compensation amount

Data types are as follows:

Type        Description              Type       Description
CF          CHARACTER FIXED          F          FLOAT
CV          CHARACTER VARIABLE       BF         BYTE
D           DECIMAL                  BV         VARBYTE
DA          DATE                     AT         TIME
I           INTEGER                  TS         TIMESTAMP
I1          BYTEINT
I2          SMALLINT



HELP Commands: Session Characteristics

Use the HELP SESSION; command to see specific information about your SQL session.
The following displays the user name with which you logged in log-on date and time,
your default database, and other information related to your current session:

               User Name     DBC
            Account Name     DBC
              Log on Date    05/02/18
              Log on Time    11:54:46
       Current DataBase      DBC
Collation   ASCII
            Character Set    ASCII
  Transaction Semantics      Teradata
       Current DateForm      IntegerDate
      Session Time Zone      00:00
 Default Character Type      LATIN
             Export Latin    1
          Export Unicode     1
  Export Unicode Adjust      0
        Export KanjiSJIS     1
          Export Graphic     0
    Default Date Format      None

To produce the formatting shown above use:

 .SET FOLDLINE ON

 .SET SIDETITLES ON



The SHOW Command

The SHOW command displays the current Data Definition Language (DDL) of a
database object (e.g., Table, View, Macro, Trigger, Join Index or Stored Procedure).
The SHOW command is used primarily to see how an object was created.

Sample Show Commands

Command                          Returns
                                 CREATE TABLE
SHOW TABLE tablename;
                                 statement
                                 CREATE VIEW
SHOW VIEW viewname;
                                 statement
                                 CREATE MACRO
SHOW MACRO macroname;
                                 statement

BTEQ also has a SHOW command (.SHOW CONTROL) which is different from the SQL
SHOW command. It provides information on formatting and display settings for the
current BTEQ session.



The SHOW TABLE Command
The SHOW TABLE command seen here returns the CREATE TABLE statement that was
used to create the employee table. To perform a SHOW TABLE, the user must have a
privilege on either the table itself or the containing database.

CREATE SET TABLE CUSTOMER_SERVICE.employee
,FALLBACK ,
  NO BEFORE JOURNAL,
  NO AFTER JOURNAL
   (
  employee_number INTEGER,
  manager_employee_number INTEGER,
  department_number INTEGER,
  job_code INTEGER,
  last_name CHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
  first_name VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL,
  hire_date DATE NOT NULL,
  birthdate DATE NOT NULL,
  salary_amount DECIMAL(10,2) NOT NULL) UNIQUE PRIMARY INDEX
(employee_number);

Note: If a table is subsequently altered after it has been created, the SHOW command
will always reflect the most current alterations.



The SHOW VIEW Command

The SHOW VIEW command shows you the CREATE VIEW statement used to create a
view:

  SHOW VIEW dept;
Result

CREATE VIEW dept
(dept_num
,dept_name
,budget
,manager)
AS
SELECT
department_number
,department_name
,budget_amount
,manager_employee_number
FROM CUSTOMER_SERVICE.department;

The view may be accessed instead of the table:

  SELECT * FROM dept;

Result
dept_num dept_name                     budget          manager
---------   -----------                --------         ---------
        301   research & development   46560000               1019
        302   product planning         22600000               1016
        501   marketing sales          80050000               1017
        403   education                93200000               1005
        402   software support         30800000               1011
        401   customer support         98230000               1003
        201   technical operations     29380000               1025



The SHOW Macro Command


The SHOW MACRO command shows you the statement used to create a macro:

SHOW MACRO get_depts;

Result

CREATE MACRO get_depts
AS (SELECT department_number
                     ,department_name
                     ,budget_amount
                    ,manager_employee_number
FROM department;
);




The EXPLAIN Command

The EXPLAIN function looks at a SQL request and responds in English how the
optimizer plans to execute it. It does not actually execute the SQL statement however
it is a good way to see what database resources will be used in processing your
request.

For instance, if you see that your request will force a full-table scan on a very large
table or cause a Cartesian Product Join, you may decide to re-write a request so that it
executes more efficiently.

EXPLAIN provides a wealth of information, including the following:

   1. Which indexes if any will be used in the query.
   2. Whether individual steps within the query may execute concurrently (i.e.
      parallel steps).
   3. An estimate of the number of rows which will be processed.
   4. An estimate of the cost of the query (in time increments).
EXPLAIN SELECT * FROM department;

*** Query completed. Ten rows found. One column returned.

Explanation

   1. First, we lock a distinct CUSTOMER_SERVICE."pseudo table" for read on a
      RowHash to prevent global deadlock for CUSTOMER_SERVICE.department.
   2. Next, we lock CUSTOMER_SERVICE.department for read.
   3. We do an all-AMPs RETRIEVE step from CUSTOMER_SERVICE.department by way
      of an all-rows scan with no residual conditions into Spool 1, which is built
      locally on the AMPs. The size of Spool 1 is estimated with low confidence to be 4
      rows. The estimated time for this step is 0.15 seconds.
   4. Finally, we send out an END TRANSACTION step to all AMPs involved in
      processing the request.
      The contents of Spool 1 are sent back to the user as the result of statement 1.
      The total estimated time is 0.15 seconds.




Lab
For this set of lab questions you will need information from the Database Info
document.

To start the online labs, click on the Telnet button in the lower left hand screen of the
course. Two windows will pop-up: a BTEQ Instruction Screen and your Telnet
Window. Sometimes the BTEQ Instructions get hidden behind the Telnet Window.
You will need these instructions to log on to Teradata.

   A. Use the HELP DATABASE command to find all tables, views, and macros names
      in the CS_Views database. What kind of objects do you find there? Do a
      similar HELP command on the Customer_Service database. What kind of
      objects do you find there?
   B. To see the names of the columns in the department table, use the appropriate
      HELP command. (Since the table is in the Customer_Service database, not
      your default database, you'll have to qualify the table name with the database
      name.) This is the command you may wish to use in the future to research
      data names.
   C. In Lab A, you may have noticed that the CS_Views database includes a view
      called emp. SHOW that view. Notice the list of short names the emp view
      uses in place of full column names. To save typing, you may use the emp
      view with the shortened names in place of the employee table in any labs
      throughout this course. (All lab solutions shown in this book use the employee
      table in Customer_Service.)
   D. Modify Lab A.1 from the previous module to cause the answer set to appear in
      department name sequence. To find out how Teradata plans to handle this
      request, submit it with EXPLAIN in front of it.
   E. Use the appropriate SHOW command to see the table definition of the
      employee_phone table in the Customer Service database.
F. Use the appropriate HELP command to see what kinds of indexes exist on the
      customer table. To get information about your session, use another HELP
      command. Change the display settings for sidetitles and foldline to better view
      the session information. Be sure to reset display attributes once you have seen
      results.
   G. Change your current database setting to Customer_Service using the
      DATABASE command. Try to do a SELECT of all columns and rows in the emp
      view. Does it work? If not, how can you make it work?




Lab Answer A

HELP DATABASE     cs_views;

*** Help information returned. 15 rows found.
Table/View/Macro name Kind Comment
agent_sales                V        ?
contact                    V        ?
customer                   V        ?
daily_sales                V        ?
department                 V        ?
emp                        V        ?
employee                   V        ?
employee_phone             V        ?
jan_sales                  V        ?
job                        V        ?
location                   V        ?
location_employee          V        ?
location_phone             V        ?
repair_time                V        ?
sales_table                V        ?

HELP DATABASE    customer_service;

*** Help information returned. 14 rows found.
Table/View/Macro name Kind Comment
agent_sales                T        ?
contact                    T        ?
customer                   T        ?
daily_sales                T        ?
department                 T        ?
employee                   T        ?
employee_phone             T        ?
jan_sales                  T        ?
job                        T        ?
location                   T        ?
location_employee          T        ?
location_phone             T        ?
repair_time                  T           ?
sales_table                  T           ?




Lab Answer B

HELP TABLE customer_service.department;

*** Help information returned. 4 rows found.

Column Name                       Type   Comment
------------------------------    ----   -----------
department_number                 I2     ?
department_name                   CF     ?
budget_amount                     D      ?
manager_employee_number           I      ?




Lab Answer C

SHOW VIEW cs_views.emp;

*** Text of DDL statement returned.
CREATE VIEW emp
             (emp
              ,mgr
              ,dept
              ,job
              ,last
              ,first
              ,hire
              ,birth
              ,sal)
AS
SELECT
      employee_number
      ,manager_employee_number
      ,department_number
      ,job_code
      ,last_name
      ,first_name
      ,hire_date
      ,birthdate
,salary_amount
FROM CUSTOMER_SERVICE.employee;



Lab Answer D

EXPLAIN SELECT * FROM customer_service.department ORDER BY
department_name ;

*** Help information returned. 11 rows found. Explanation

1. First, we lock a distinct customer_service."pseudo table" for
read on a RowHash to prevent global deadlock for
customer_service.department.

2. Next, we lock customer_service.department for read.

3. We do an all-AMPs RETRIEVE step from
customer_service.department by way of an all-rows scan with no
residual conditions into Spool 1, which is built locally on the
AMPs. Then we do a SORT to order Spool 1 by the sort key in
spool field1. The size of Spool 1 is estimated with low
confidence to be 12 rows. The estimated time for this step is
0.15 seconds.

4. Finally, we send out an   END TRANSACTION step to all AMPs
involved in processing the   request.
-> The contents of Spool 1   are sent back to the user as the
result of statement 1. The   total estimated time is 0.15 seconds.




Lab Answer E

SHOW TABLE Customer_Service.employee_phone;

*** Text of DDL statement returned.
CREATE TABLE customer_service.employee_phone ,FALLBACK ,
       NO BEFORE JOURNAL,
       NO AFTER JOURNAL
       (
       employee_number INTEGER NOT NULL,
       area_code SMALLINT NOT NULL,
       phone INTEGER NOT NULL,
       extension INTEGER,
       comment_line CHAR(72) CHARACTER SET LATIN NOT
CASESPECIFIC)
PRIMARY INDEX( employee_number )
;



Lab Answer F

HELP INDEX Customer_Service.customer;

***  Help information returned. One row.
           Primary or
Unique     Secondary    Column Names
Y          P            customer_number


.SET SIDETITLES ON
.SET FOLDLINE ON
HELP SESSION;
              User Name   tdxxx
          Account Name    $M_P0623_&D
            Logon Date    00/11/29
            Logon Time    11:52:18
      Current DataBase    tdxxx
              Collation   ASCII
         Character Set    ASCII
 Transaction Semantics    Teradata
      Current DateForm    IntegerDate
     Session Time Zone      00:00
Default Character Type    LATIN
          Export Latin    1
        Export Unicode    1
 Export Unicode Adjust    0
      Export KanjiSJIS    1
        Export Graphic    0
   Default Date Format    None

.SET SIDETITLES OFF
.SET FOLDLINE OFF




Lab Answer G

DATABASE Customer_Service;

SELECT * FROM emp;
(Fails because the emp view is not in database customer_service. To
make it work, fully qualify the view name.)

SELECT * FROM CS_Views.emp;

(You may also change the default database.)

DATABASE CS_Views;

SELECT * FROM emp;




Logical and Conditional Expressions Module 5

Objectives
After completing this module, you should be able to:

       Combine the following types of operators into logical expressions:
                   comparison operators
                   [NOT] IN
                   IS [NOT] NULL
                   LIKE
       Form expressions involving NULL values.
       Qualify a range of values.
       Search for a partial string within a string expression.
       Combine multiple logical expressions into a conditional expression using
       AND and OR.



Logical Operators

Operators are symbols or words that cause an 'operation' to occur on one or more
elements called 'operands'.

Logical expressions combine operands and operators to produce a Boolean
(true/false) result. Logical expressions can be combined into conditional
expressions which are used in the WHERE clause of a SELECT statement.

Types of Operators in Logical Expressions

            Operator Syntax                Meaning
                    =                      equal
                   <>                      not equal
                    >                      greater than
<                     less than
                   >=                     greater than or equal to
                   <=                     less than or equal to
       BETWEEN <a> AND <b>                inclusive range
                [NOT] IN                  <expression> is in a list
                                          or
                                          <expression> is not in a list
            IS [NOT] NULL                 <expression> is null
                                          or
                                          <expression> is not null
            [NOT] EXISTS*                 table contains at least 1 row
                                          or
                                          table contains no rows
                  LIKE                    partial string operator

The EXISTS operator is covered in the Teradata Advanced SQL course.


BETWEEN -- Numeric Range Testing

To locate rows for which a numeric column is within a range of values, use the
BETWEEN <a> AND <b> operator. Specify the upper and lower range of values that
qualify the row.

The BETWEEN operator looks for values between the given lower limit <a> and
given upper limit <b> as well as any values that equal either <a> or <b> (i.e.,
BETWEEN is inclusive.)

Example

Select the name and the employee's manager number for all employees whose job
codes are in the 430000 range.

  SELECT     first_name
             ,last_name
             ,manager_employee_number
  FROM       employee
  WHERE      job_code BETWEEN 430000 AND 439999;

An alternative syntax is shown below:

  SELECT     first_name
             ,last_name
             ,manager_employee_number
  FROM       employee
  WHERE      job_code >= 430000
  AND        job_code <= 439999;
first_name       last_name         manager_employee_number
-----------      -----------       ------------------------------
Loretta          Ryan                            801
Armando          Villegas                       1005




BETWEEN -- Character Range Testing

Use the BETWEEN <a> AND <b> operator to locate rows for which a character column
is within a range of values. Specify the upper and lower range of values that qualify
the row. BETWEEN will select those values which are greater than or equal to <a> and
less or equal to <b>. (BETWEEN is inclusive.)

SELECT last_name
FROM employee
WHERE last_name BETWEEN 'r' AND 's';

last_name
------------
Ryan

Note: 'Stein' is not included because 'S_____' sorts lower than 'Stein'. (Teradata is
not case-sensitive by default.)


Set Operator IN
Use the IN operator as shorthand when multiple values are to be tested. Select the
name and department for all employees in either department 401 or 403. This query
may also be written using the OR operator which we shall see shortly.
  SELECT     first_name
             ,last_name
             ,department_number
  FROM       employee
  WHERE      department_number IN (401, 403);

first_name       last_name        department_number
-----------      -----------         ---------------------
Darlene         Johnson                            401
Loretta         Ryan                               403
Armando         Villegas                           403
James           Trader                             401




Set Operator NOT IN

Use the NOT IN operator to locate rows for which a column does not match any of a
set of values. Specify the set of values which disqualifies the row.

  SELECT      first_name
              ,last_name
              ,department_number
  FROM        employee
  WHERE       department_number NOT IN (401, 403) ;

first_name          last_name           department_number
-----------         -----------         ---------------------
Carol               Kanieski            301
John                Stein               301
NOT IN vs. OR

NOT IN provides a shorthand version of a 'negative OR' request. The following is an
example using the OR operator for the query example given above.

Select the name and the department for all employees who are NOT members of
departments 401 and 403.

  SELECT            first_name
                    ,last_name
                    ,department_number
  FROM              employee
  WHERE NOT         (department_number=401
                    OR
                    department_number=403);

first_name             last_name          department_number
-----------            -----------        ---------------------
Carol                  Kanieski           301
John                   Stein              301


NULL

The following are facts about nulls:

         NULL is used to represent the absence of a data value.
         NULL is not the same as having a value of zero or spaces.
         NULL indicates that a data value is missing or unknown.
         NULL in a comparison operation produces an unknown result.
         When doing an ascending sort on a column with NULL, NULLs sort before
         negative values (numeric) and before blank values (character).
         To prohibit NULLs, a column must be defined as NOT NULL.
         Null columns may be compressed to occupy zero row space.




Arithmetic and Comparison Operation on NULL

The following logic applies to operations on NULLs:

 Col A     Operation      Col B        Results
  10            +              NULL     NULL
  10            -              NULL     NULL
  10            *              NULL     NULL
  10            /              NULL     NULL
  10            >              NULL    UNKNOWN
10          <           NULL      UNKNOWN
  10         >=           NULL      UNKNOWN
  10         <=           NULL      UNKNOWN
  10          =           NULL      UNKNOWN
  10         <>           NULL      UNKNOWN
 NULL         >           NULL      UNKNOWN
 NULL         <           NULL      UNKNOWN
 NULL        >=           NULL      UNKNOWN
 NULL        <=           NULL      UNKNOWN
 NULL         =           NULL      UNKNOWN
 NULL        <>           NULL      UNKNOWN



Using NULL in a Select

Use NULL in a SELECT statement, to define that a range of values either IS NULL or IS
NOT NULL.

The following table lists two employees with unknown telephone extensions:




To list employee numbers in this table with unknown extensions:

  SELECT      employee_number
  FROM        employee_phone
  WHERE       extension IS NULL;
employee_number
--------------------
1025
1005

To list employee numbers of people with known extensions:
SELECT      employee_number
  FROM        employee_phone
  WHERE       extension IS NOT NULL;
employee_number
--------------------
1008
1013


LIKE Operator

The LIKE operator searches for patterns matching character data strings.

You must provide two parameters for the LIKE operator: a string expression to be searched
and a string pattern for which to search.

The string can contain specific characters, as well as the following "wildcards":

       % (indicates zero or more character positions)
       _ (indicates a single character position)

Here are some examples using the LIKE operator:

String pattern
                           Meaning:
example:
LIKE 'JO%'                 begins with 'JO'
LIKE '%JO%'                contains 'JO' anywhere
LIKE '__HN'                contains 'HN' in 3rd and 4th position
LIKE '%H_'                 contains 'H' in next to last position


LIKE Operator -- Case-Blind Comparison

Case-Sensitivity: ANSI vs. BTET session transaction mode

Case-sensitivity of string comparisons is handled differently in the two different session
transaction modes (ANSI or BTET). This can lead to different results for a comparison
when run from sessions with different transaction modes. To ensure consistent
behavior, either case-sensitive or case-blind compares, use the following:

UPPER or LOWER operators for case-blind comparisons
CASESPECIFIC operator for case-sensitive comparisons

Case-Blind Compare

The UPPER function converts a string to uppercase. Use the UPPER string function on
both strings being compared to ensure a case-blind comparison regardless of the
session transaction mode. The LOWER function may be similarly used.
The NOT CASESPECIFIC data attribute can also be used to force case-blind
compares, however it is not an ANSI-compliant operator.

Problem

Display the full name of employees whose last name contains the letter "r" followed by
the letter "a".

Teradata Mode Solution


  SELECT      first_name
              ,last_name
  FROM        employee
  WHERE       last_name LIKE '%ra%';

first_name                                   last_name
------------------------------               --------------------
James                                        Trader
Peter                                        Rabbit
I.B.                                         Trainer
Robert                                       Crane
Larry                                        Ratzlaff

Since we are in Teradata (BTET) mode, the default for comparisons is non-case-
specific. Thus, we could have also used LIKE '%Ra%' or LIKE '%RA%' and
produced the same result.

ANSI Mode Solution

SELECT     first_name
              ,last_name
FROM      employee
WHERE     last_name LIKE '%ra%';

first_name                           last_name
------------------------------       --------------------
James                                Trader
I.B.                                 Trainer
Robert                               Crane

Since we are in ANSI mode, the default for comparisons is case-specific. Thus, we will
not pick up Ratzlaff or Rabbit, unless we use 'case blind' testing, seen in the next
example.

SELECT     first_name
              ,last_name
FROM      employee
WHERE     LOWER(last_name) LIKE LOWER('%ra%');

first_name                           last_name
------------------------------ --------------------
James                               Trader
Peter                               Rabbit
I.B.                                Trainer
Robert                              Crane
Larry                               Ratzlaff
By applying the LOWER function to each side of the comparison, all testing is done in
a 'case blind' mode. UPPER could have also been used. We could also have used LIKE
'%ra%' (NOT CASESPECIFIC) to produce this result, however this is not an ANSI
standard approach.


LIKE Operator - Case-Sensitive Comparison

Use the CASESPECIFIC data attribute on one or both of the string expressions being
compared to ensure a case-sensitive comparison, regardless of the session transaction
mode. CASESPECIFIC is a Teradata extension.

Problem
Display the full name of employees whose last name contains "Ra". This is a case-
sensitive test.

Teradata Mode Solution

  SELECT      first_name
              ,last_name
  FROM        employee
  WHERE       last_name (CASESPECIFIC) LIKE '%Ra%';

first_name                             last_name
------------------------------         --------------------
Peter                                  Rabbit
Larry                                  Ratzlaff

The default comparison for Teradata mode is not case-specific.

Use of the Teradata extension (CASESPECIFIC) forces a case-specific comparison.

Because we used the case-specific designator, we don't get James Trader in our answer
set but only get answers that contain an uppercase "R". The name 'LaRaye' would have
also appeared in this answer set, if it existed in the table. Using LIKE 'Ra%' will return
only names that begin with "Ra".

ANSI Mode Solution

  SELECT first_name
 ,last_name
 FROM employee
 WHERE last_name LIKE '%Ra%';

first_name                             last_name
------------------------------         --------------------
Peter                                 Rabbit
Larry                                 Ratzlaff

The default comparison for ANSI mode is case-specific.

Use of the Teradata extension (CASESPECIFIC) is not required. This could have also
been submitted with LIKE 'Ra%' and produced the same result, however it would have
missed a name like 'LaRaye'.


LIKE Operator -- Using Quantifiers

To extend the pattern matching functions of the LIKE operator, use quantifiers.

There are three such quantifiers:

ANY — any single condition must be met (OR logic)
SOME — same as ANY
ALL — all conditions must be met (AND logic)

ANY and SOME are synonyms. Using LIKE ANY and LIKE SOME will give the same result.




Problem

Display the full name of all employees with both "E" and "S" in their last name.

Solution

  SELECT   first_name
           ,last_name
   FROM    employee
   WHERE   last_name LIKE ALL ('%E%', '%S%');
first_name            last_name
----------            ----------
John                       Stein
Carol                      Kanieski
Arnando                    Villegas
Problem

Display the full name of all employees with either an "E" or "S" in their last name.

Solution

  SELECT    first_name
            ,last_name
   FROM     employee
   WHERE    last_name LIKE ANY ('%E%', '%S%');
first_name             last_name
-----------            -----------
John                       Stein
Carol                      Kanieski
Arnando                    Villegas
Darlene                    Johnson
James                      Trader


LIKE with ESCAPE Character

The "_" and "%" symbols are used as 'wildcards' in the string expression of the LIKE
construct. However, what if one of the wildcard symbols is in the expression you are
evaluating. For example, to search for the substring "95%", you must define an
ESCAPE character to instruct the Parser to treat the '%' as a non-wildcard character.

To Summarize:

        The ESCAPE feature of LIKE lets wildcard characters be treated as non-
        wildcards.
        Characters following the escape character are not treated as wildcards.

Problem

List all objects defined in the Teradata Database Data Dictionary whose names contain
"_" (underscore) as the second character.

Solution

SELECT tablename
FROM dbc.tables
WHERE tablename LIKE '_Z_%' ESCAPE 'Z';


TableName
------------------------------
M_7_B
t_wt_erd1
Things To Notice

        The defined escape character is the letter 'Z'.
        The first "_" (underscore) seen represents a wildcard - i.e., any single arbitrary
        character.
        The "Z_" sequence tells the Parser that the second "_" (underscore) is treated as
        a character, not as a wildcard.


When you define an ESCAPE character, any use of the ESCAPE character in the string
expression must be immediately followed by either the "_", "%", or the ESCAPE
character itself.

Assume the escape character is defined to be the letter 'G'.

LIKE 'G_' means the underscore is treated as an underscore, not as a wildcard.
LIKE 'G%' means the percent sign is treated as a percent sign, not as a wildcard.
LIKE 'GG' means the two consecutive 'G' characters should be treated as a single 'G',
not as an escape character.

Example

LIKE '%A%%AAA_' ESCAPE 'A'

Searches for the following pattern:
- any number of arbitrary characters, followed by
- the "%" single character, followed by
- any number of arbitrary characters, followed by
- the "A" single character, followed by
- the "_" single character, which is the last character in the string.


Logical Operator -- AND

Logical operators AND, OR and NOT allow you to specify complex conditional expressions
by combining one or more logical expressions.

Logical Operator AND

The logical operator AND combines two expressions, both of which must be true in a
given record for them to be included in the result set.

            Boolean Logic Table
True      AND      True          = True
False     AND      True          = False
True      AND      False         = False
False     AND      False         = False
True       OR        True           = True
True       OR        False          = True
False      OR        True           = True
False      OR        False          = False


NOT        True      = False
NOT        false     = True

Problem

Display the name and employee number of employees in department 403 who earn less
than $35,000 per year.

Solution

  SELECT          first_name
                  ,last_name
                  ,employee_number
  FROM            employee
  WHERE           salary_amount < 35000.00
  AND             department_number = 403 ;
first_name                   last_name          employee_number
-----------                  -----------        --------------------
Loretta                      Ryan               1005




Logical Operator -- OR

The logical operator OR combines two expressions. At least one must be true in a given
record for it to be included in the result set.

Problem

Display the name and the employee number for employees who either earn less than
$35,000 annually or work in department 403.
Solution

  SELECT      first_name
              ,last_name
              ,employee_number
  FROM        employee
  WHERE       salary_amount < 35000.00
  OR          department_number = 403;

Result

first_name              last_name              employee_number
----------              ----------             ----------------
Arnando                 Villegas               1007
Carol                   Kanieski               1008
Loretta                 Ryan                   1005
John                    Stein                  1006




Multiple AND . . . OR

You want to find all employees in either department 401 or department 403 whose
salaries are either under $35,000 or over $85,000.

  SELECT      last_name
              ,salary_amount
              ,department_number
  FROM        employee
  WHERE       (salary_amount < 35000
  OR          salary_amount > 85000)
  AND         (department_number = 401
  OR          department_number = 403) ;


Logical Operators -- Combinations

Operator Procedures

Parentheses can be used to force an evaluation order. In the presence of parentheses,
expressions are evaluated from the inner-most to outer-most set of parenthetical
expressions.




In the absence of parentheses, SQL uses the default precedence of the Boolean
operators. By default, NOT has higher precedence than AND which has higher precedence
than OR. Operators that have the same precedence level are evaluated from left to right
(e.g., multiple ORs or multiple ANDs).

If we remove the parentheses from the example above, our conditional expression gets
evaluated in a totally different order. If we were to use it in a query, it would yield
different results.




NOT has the highest precedence of the three operators.
Logical Operators -- Using Parentheses

Problem

Select the name, department number, and job code for employees in departments 401
or 403 who have job codes 412101 or 432101.

Solution

  SELECT      last_name
              ,department_number
              ,job_code
  FROM        employee
  WHERE       (department_number = 401
  OR          department_number = 403)
  AND         (job_code = 412101
  OR          job_code = 432101) ;

Result

last_name         department_number                  job_code
-----------       ---------------------              ----------
Villegas          403                                432101
Johnson           401                                412101

If we accidentally left the parentheses out of our statement, would we get the same
results?

  SELECT      last_name
              ,department_number
              ,job_code
  FROM        employee
  WHERE       department_number = 401
  OR          department_number = 403
  AND         job_code = 412101
  OR          job_code = 432101;
last_name         department_number                  job_code
----------        ---------------------              ---------
Villegas          403                                432101
Johnson           401                                 412101
Trader            401                                 411100

Question
James Trader does not have either job code. Why was he selected?

Answer
Without parentheses, the default precedence causes the expression to be evaluated as
follows:

  SELECT      last_name
              ,department_number
              ,job_code
  FROM        employee
  WHERE       department_number = 401
  OR          (department-number = 403
  AND         job_code = 412101)
  OR          job_code = 432101;

Remember, if any of the expressions that OR combines are true, the result is true. Since
James Trader is in department_number 401, that expression evaluates to true.
Therefore the row qualifies for output.


Multiple AND

Use multiple ANDs if you need to locate rows which meet all of two or more sets of
specific criteria.

For example, what happens if we take the previous example, and replace all the ORs
with ANDs?

  SELECT     last_name
             ,department_number
             ,job_code
  FROM       employee
  WHERE      department_number = 401
  AND        department_number = 403
  AND        job_code = 412101
  AND        job_code = 432101;

No rows will be found. Why?

Answer

For a row to be displayed in this answer set, an employee would have to be in
department numbers 401 and 403. While we could conceive of an employee who
works in two departments, the employee table has only one field for department
number. There is no way that any row in this table can contain more than one
department number. This query never will return any rows. A more realistic example
follows.
Problem

Find all employees in department number 403 with job_code 432101 and a salary
greater than $25,000.

Solution

  SELECT      last_name
              ,department_number
              ,job_code
              ,salary
  FROM        employee
  WHERE       department_number = 403
  AND         job_code = 432101
  AND         salary_amount > 25000.00 ;

Result

last_name      department_number             job_code     salary_amount
-----------    ----------------------        ----------   ----------------
Lombardo       403                           432101       31000.00
Villegas       403                           432101       49700.00
Charles        403                           432101       39500.00
Hopkins        403                           432101       37900.00
Brown          403                           432101       43700.00


Logical NOT

Place the NOT operator in front of a conditional expression or in front of a comparison
operator if you need to locate rows which do not meet specific criteria.

Problem

Select the name and employee number of employees NOT in department 301.

Solution for NOT Operator

  SELECT        first_name
                ,last_name
                ,employee_number
  FROM          employee
  WHERE         department_number NOT = 301;

Solution for NOT Condition

  SELECT        first_name
                ,last_name
,employee_number
  FROM         employee
  WHERE NOT    (department_number = 301);

Result (Note that both approaches return the same result.)

first_name             last_name              employee_number
------------           ------------           --------------------
Arnando                Villegas               1007
James                  Trader                 1003
Loretta                Ryan                   1005
Darlene                Johnson                1004
SQL Lab Databases Info Document:
Your assigned user-id has SELECT access to the ‗Customer_Service‘
and the ‗Student‘ databases. These databases are used for labs
during this SQL course. When selecting from tables, either set your
default database to Customer_Service, Student, or your own user-
assigned database (depending on the lab requirements) or
alternatively, qualify your table names to reflect the appropriate
database.
The following pages include table definitions for the
‗Customer_Service‘ database and the ‗Student‘ database.
You may want to print this document for reference throughout this
course.

‗Customer_Service‘ Table Definitions


CREATE SET TABLE agent_sales ,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
agent_id INTEGER,
sales_amt INTEGER)
UNIQUE PRIMARY INDEX ( agent_id );
--
CREATE TABLE clob_files
(Id INTEGER NOT NULL,
text_file CLOB(10000))
UNIQUE PRIMARY INDEX ( Id );
--
CREATE TABLE contact, FALLBACK
(contact_number INTEGER
,contact_name CHAR(30) NOT NULL
,area_code SMALLINT NOT NULL
,phone INTEGER NOT NULL
,extension INTEGER
,last_call_date DATE NOT NULL)
UNIQUE PRIMARY INDEX (contact_number);
--
CREATE TABLE customer, FALLBACK
(customer_number INTEGER
,customer_name CHAR(30) NOT NULL
,parent_customer_number INTEGER
,sales_employee_number INTEGER
)
UNIQUE PRIMARY INDEX (customer_number);
--
CREATE SET TABLE daily_sales
,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
itemid INTEGER,
salesdate DATE FORMAT 'YY/MM/DD',
sales DECIMAL(9,2))
PRIMARY INDEX ( itemid );

--
CREATE SET TABLE daily_sales_2004
,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
itemid INTEGER,
salesdate DATE FORMAT 'YY/MM/DD',
sales DECIMAL(9,2))
PRIMARY INDEX ( itemid );

--
CREATE TABLE department, FALLBACK
(department_number SMALLINT
,department_name CHAR(30) NOT NULL
,budget_amount DECIMAL(10,2)
,manager_employee_number INTEGER
)
UNIQUE PRIMARY INDEX (department_number)
,UNIQUE INDEX (department_name);
--
CREATE TABLE employee, FALLBACK
(employee_number INTEGER
,manager_employee_number INTEGER
,department_number INTEGER
,job_code INTEGER
,last_name CHAR(20) NOT NULL
,first_name VARCHAR(30) NOT NULL
,hire_date DATE NOT NULL
,birthdate DATE NOT NULL
,salary_amount DECIMAL(10,2) NOT NULL
)
UNIQUE PRIMARY INDEX (employee_number);
--
CREATE TABLE employee_phone, FALLBACK
(employee_number INTEGER NOT NULL
,area_code SMALLINT NOT NULL
,phone INTEGER NOT NULL
,extension INTEGER
,comment_line CHAR(72)
)
PRIMARY INDEX (employee_number);
--
CREATE SET TABLE Jan_sales
,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
itemid INTEGER,
salesdate DATE FORMAT 'YY/MM/DD',
sales DECIMAL(9,2))
PRIMARY INDEX ( itemid );

--
CREATE TABLE job, FALLBACK
(job_code INTEGER
,description VARCHAR(40) NOT NULL
,hourly_billing_rate DECIMAL(6,2)
,hourly_cost_rate DECIMAL(6,2)
)
UNIQUE PRIMARY INDEX (job_code)
,UNIQUE INDEX (description);
--
CREATE TABLE location, FALLBACK
(location_number INTEGER
,customer_number INTEGER NOT NULL
,first_address_line CHAR(30) NOT NULL
,city VARCHAR(30) NOT NULL
,state CHAR(15) NOT NULL
,zip_code INTEGER NOT NULL
,second_address_line CHAR(30)
,third_address_line CHAR(30)
)
PRIMARY INDEX (customer_number);
--
CREATE TABLE location_employee, FALLBACK
(location_number INTEGER NOT NULL
,employee_number INTEGER NOT NULL
)
PRIMARY INDEX (employee_number);
--
CREATE TABLE location_phone, FALLBACK
(location_number INTEGER
,area_code SMALLINT NOT NULL
,phone INTEGER NOT NULL
,extension INTEGER
,description VARCHAR(40) NOT NULL
,comment_line LONG VARCHAR
)
PRIMARY INDEX (location_number);

--
CREATE TABLE phonelist
( LastName CHAR(20),
FirstName CHAR(20),
Number CHAR(12) NOT NULL,
Photo BLOB(10000))
UNIQUE PRIMARY INDEX ( Number );

--
CREATE TABLE repair_time
( serial_number INTEGER
,product_desc CHAR(8)
,start_time TIMESTAMP(0)
,end_time TIMESTAMP(0))
UNIQUE PRIMARY INDEX
(serial_number);

--
CREATE SET TABLE salestbl
,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
storeid INTEGER,
prodid CHAR(1),
sales DECIMAL(9,2))
PRIMARY INDEX ( storeid );




‗Student‘ Database Table Definitions

CREATE TABLE city ,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
cityname CHAR(15) NOT CASESPECIFIC,
citystate CHAR(2) NOT CASESPECIFIC,
citypop INTEGER)
PRIMARY INDEX ( cityname );

CREATE TABLE customers ,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
cust_id integer not null
,cust_name char(15)
,cust_addr char(25) compress)
PRIMARY INDEX ( cust_id);
CREATE TABLE orders ,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
order_id INTEGER NOT NULL
,order_date DATE FORMAT 'YYYY-MM-DD'
,cust_id INTEGER
,order_status CHAR(1))
UNIQUE PRIMARY INDEX ( order_id );

CREATE TABLE state ,NO FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL
(
stateid CHAR(2) NOT CASESPECIFIC NOT NULL,
statename CHAR(15) NOT CASESPECIFIC,
statepop INTEGER NOT NULL,
statecapitol CHAR(15) NOT CASESPECIFIC)
PRIMARY INDEX ( stateid );




Lab

 For this set of lab questions you will need information from the Database Info document.

 To start the online labs, click on the Telnet button in the lower left hand screen of the course. Two
 windows will pop-up: a BTEQ Instruction Screen and your Telnet Window.

 Sometimes the BTEQ Instructions get hidden behind the Telnet Window. You will need these
 instructions to log on to Teradata.

 Be sure to change your default database to the Customer_Service database in order to run these
 labs.

     A. Management needs a list with employee number, last name, salary and job code of all
        employees earning between $40,001 and $50,000. Produce this report using the comparison
        operators and sort by last name.

          Modify the query to use the BETWEEN operator and sort by salary descending.

     B. Management requests a report of all employees in departments 501, 301, and 201 who earn
        more than $30,000. Show employee number, department number, and salary. Sort by
        department number and salary amount within department.
     C. Display location number, area code, phone number, extension, and description from the
        location_phone table if the description contains the string ‘manager'. Sort by location
        number.
     D. List customers from the customer table identified by:
             1. An unknown parent customer number; and
             2. A known sales employee number.
Display all columns except parent customer number. Order results by customer number.

    E. Create a report that lists all location numbers in area code 415 not dedicated to any manager.
       Include all columns except comment and extension. Sequence by phone number.
    F. List all job codes in the 400000 series that are management and all Analyst positions regardless
       of job code value. List job code and description for the selected rows. Sort by description.
       Submit again using EXPLAIN to look at how the Teradata RDBMS handled this request.
    G. List the location numbers in area codes 415 or 617 which have no phone extensions. Order by
       area code and phone number. Include all columns of the table except for description and
       comment line columns. Notice how NULLs appear in your output.




Lab Answer A

DATABASE Customer_Service;
SELECT employee_number
        ,last_name
        ,salary_amount
        ,job_code
FROM    employee
WHERE   salary_amount >=                   40001
AND     salary_amount <=                   50000
ORDER BY        last_name
;


*** Query completed. 4 rows found. 4 columns returned.

employee_number last_name salary_amount job_code
            1024 Brown         43700.00 432101
            1002 Brown         43100.00 413201
            1010 Rogers        46000.00 412101
            1007 Villegas      49700.00 432101
SELECT employee_number
        ,last_name
        ,salary_amount
        ,job_code
FROM    employee
WHERE   salary_amount BETWEEN 40001 AND 50000
ORDER BY        salary_amount DESC
;


*** Query completed. 4 rows found. 4 columns returned.

employee_number last_name salary_amount job_code
              1007 Villegas                 49700.00        432101
1010 Rogers            46000.00      412101
             1024 Brown             43700.00      432101
             1002 Brown             43100.00      413201


Lab Answer B

SELECT employee_number
        ,department_number
        ,salary_amount
FROM    employee
WHERE   salary_amount > 30000
AND     department_number IN        (501,301,201)
ORDER BY department_number
        ,salary_amount
;


*** Query completed. 6 rows found. 3 columns returned.

employee_number department_number salary_amount
             1025                  201         34700.00
             1021                  201         38750.00
             1019                  301         57700.00
             1015                  501         53625.00
             1018                  501         54000.00
             1017                  501         66000.00


Lab Answer C

SELECT location_number
        ,area_code
        ,phone
        ,extension
        ,description
FROM    location_phone
WHERE   description LIKE '%Manager%'
ORDER BY        location_number
;


*** Query completed. 5 rows found. 5 columns returned.

  location_number      area_code       phone    extension description
          5000001            415     4491225            ? System Manager
         14000020            312     5692136            ? System Manager
22000013        617   7562918         ? System Manager
         31000004        609   5591011       224 System Manager
         33000003        212   7232121         ? System Manager




Lab Answer D

SELECT customer_number
        ,customer_name
        ,sales_employee_number
FROM    customer
WHERE   parent_customer_number IS NULL
AND     sales_employee_number IS NOT NULL
ORDER BY 1
;

*** Query completed. 14 rows found. 3 columns
returned.
customer_number customer_name
sales_employee_number
 -------------- ---------------------------- -
----------------------
             1 A to Z Communications, Inc.
1015
             3 First American Bank
1023
             5 Federal Bureau of Rules
1018
             6 Liberty Tours
1023
             7 Cream of the Crop
1018
             8 Colby Co.
1018
             9 More Data Enterprise
1023
            10 Graduates Job Service
1015
            11 Hotel California
1015
            12 Cheap Rentals
1018
            14 Metro Savings
1018
            15 Cates Modeling
1015
            17 East Coast Dating Service
1023
            18 Wall Street Connection
1023


Lab Answer E
SELECT location_number
        ,area_code
        ,phone
        ,description
FROM    location_phone
WHERE   area_code = 415
AND     description NOT LIKE   '%Manager%'
ORDER BY        phone
;


*** Query completed.   6 rows found.   4 columns
returned.


location_number area_code       phone description
--------------- --------- ----------- -------------
        5000010       415     2412021 Alice Hamm
        5000011       415     3563560 J.R. Stern
        5000001       415     4491221 FEs office
        5000001       415     4491244 Secretary
        5000019       415     6567000 Receptionist
        5000002       415     9237892 Receptionist



Lab Answer F
SELECT job_code
        ,description
FROM    job
WHERE   (job_code BETWEEN 400000 AND          499999
AND     description LIKE '%manager%')
OR      (description LIKE '%analyst%')
ORDER BY        description
;



***   Query completed.    6 rows found.     2 columns returned.


   job_code    description
-----------    -----------------------------
     411100    Manager - Customer Support
     431100    Manager - Education
     421100    Manager - Software Support
     422101    Software Analyst
     222101    System Analyst
     412103    System Support Analyst

Note: EXPLAIN text varies depending on optimizer path.




Lab Answer G
SELECT location_number
        ,area_code
        ,phone
        ,extension
FROM    location_phone
WHERE   extension IS NULL
AND     area_code IN (415,617)
ORDER BY area_code
        ,phone
;


*** Query completed.       9 rows found.     4 columns
returned.

location_number     area_code          phone       extension
---------------     ---------    -----------     -----------
        5000010           415        2412021               ?
        5000011           415        3563560               ?
        5000001           415        4491221               ?
        5000001           415        4491225               ?
        5000001           415        4491244               ?
        5000019           415        6567000               ?
        5000002           415        9237892               ?
       22000013           617        7562918               ?
       22000013           617        7567676               ?




Data Types and Conversions Module:- 6

Objectives

After completing this module, you should be able to:

       Define the data type for a column in a table.
       Compute values using arithmetic functions and operators.
       Convert data from one type to another.
       Manipulate the DATE data type.



Data Types

Every column in a row is associated with a data type that defines the kind of values it
accepts. These data types are associated with the fields when the table is created.
Data types fall into one of the four categories shown below:

Data Type                       Holds
Character data                  Character Strings
Byte data                       Binary Data Strings
Numeric data                     Numbers
                                 Dates,Times,Timestamps,Time Intervals
                                 (Note: Time, Timestamps and Intervals
Date/Time data
                                 are covered in the Teradata SQL
                                 Advanced course)


Character Data

There are two data types for holding character data:

       CHAR - has fixed-length character strings.
       VARCHAR - has variable-length character strings.

In both cases, the maximum string length is 64,000 characters. String size is specified
in parentheses after the keyword CHAR or VARCHAR as in CHAR(20) or VARCHAR(20).
There are subtle differences between the two.

In the case of CHAR, if you insert a character string less than the specified size (20 in
the above example), the system will append and store trailing blanks as needed to
expand the string to the specified length. The size specified on a VARCHAR field
represents a maximum length. The system will not pad the contents with trailing
blanks. (It will use two extra bytes to store the length internally however.)

When you know that data will always be a specific length (e.g., a Mail Stop that is a
four-character length) use CHAR. You save the two bytes that VARCHAR would use to
store the length. When data does not have a fixed length (e.g., last names), VARCHAR
makes more efficient use of the space, because it does not pad values with trailing
blanks.


Character Data                 Description                   Example
CHAR (size)                    Fixed length string           last_name CHAR(20)
                               Max: 64,000 characters
                                                             Sample contents:
                                                             'Ryan__________'
VARCHAR (size)                 Variable length string        first_name VARCHAR(30)
CHAR VARYING (size)            Max: 64,000 characters
CHARACTER VARYING                                            Sample contents:
(size)                                                       'Loretta'
LONG VARCHAR                   Equivalent to
                               VARCHAR (64000)


Note: VARCHAR(size), CHAR VARYING(size), and CHARACTER VARYING(size) are all
equivalent synonyms.

LONG VARCHAR   is equivalent to a maximum VARCHAR.
Character strings may be defined using any one of the following character sets:

            Character Set      Max Length
                      Latin    64,000 (English language default)
                    Kanji1     64,000
                 KanjiSJIS     64,000
                   Unicode     32,000 (two bytes per character)
                   Graphic     32,000 (two bytes per character)


Examples

   first_name VARCHAR(30) CHARACTER SET LATIN

   image_abc CHAR(32000) CHARACTER SET GRAPHIC



Byte Data

Teradata supports two data types for holding binary data:

       BYTE.
       VARBYTE.

BYTE is for fixed length binary strings. VARBYTE is for variable length binary strings.
These data types are used for storing binary objects such as digital images,
executable objects, flat files, etc.


 Byte Data                 Description

 BYTE (size)               Fixed length
                           Binary string
                           Default: (1)
                           Max: 64,000 bytes

 VARBYTE (size)            Variable length
                           Binary string
                           Default: (1)
                           Max: 64,000 bytes


Note: BYTE columns are not covertible to other data types.


Numeric Data
The following numeric data types are available:


Data Type         Description                     Examples
BYTEINT*          Whole number                    basket_count
                  Range -128 to 127               BYTEINT
                  Storage: 1 byte                   +125
SMALLINT          Whole number                    area_code
                  Range: -32,768 to 32,767        SMALLINT
                  Storage: 2 bytes                  +00213 (up to 5 digits)
INTEGER           Whole number                    phone
                  Range: -2,147,483,648 to        INTEGER
                  2,147,483,647                      +0006495252 (up to 10 digits)
                  Storage: 4 bytes
BIGINT            Whole number                    international_phone
                  Range ±                         BIGINT
                  9,233,372,036,854,775,80        +0000010807934842145 (up to 19 digits)
                  7
                  Storage: 8 bytes
DEC(m, n)         'm' is total number of digits. salary_amount
DECIMAL(m,n)      (m <= 18)                      DEC (10,2)
NUMERIC(m,n       'n' is precision places to the   +00035000.00
)                 right of decimal point.
(Small Decimal)   Max Size =18 digits
                  Storage: 2 to 8 bytes
DEC(m, n)         'm' is total number of digits. sheet_thickness
DECIMAL(m,n)      (18 < m <= 38)                 DEC (32,30)
NUMERIC(m,n       'n' is precision places to the   +01.12349878279278758297727849782
)                 right of decimal point.        7
(Large Decimal)   Max Size = 38 digits
                  Storage: 16 bytes
FLOAT             Floating Point Format           salary_factor
                  (IEEE)                          FLOAT
                  2x10-307 to 2x10+308            4.35400000000000E-001
                  Storage: 8 bytes

FLOAT             Internally represented
[(precision)]     as FLOAT
REAL              Internally represented
                  as FLOAT
DOUBLE            Internally represented
PRECISION         as FLOAT


* Non-ANSI standard data type

Date Data
DATE represents a calendar date. It simplifies handling and formatting dates common to
business applications. DATE is stored as an integer, using the following formula:
(year - 1900) * 10000 + (month * 100) + day.

The DATE data type, shown here, is used in several forthcoming examples.


Data Type                              Description                     Examples
DATE               Specially formatted integer:                        hire_date DATE
                     YYMMDD thru 1999                                   +0000990921
                     YYYMMDD from 2000 onward                           +0001000215


In the first example, the date being represented is September 21, 1999.
In the second example, the date being represented is February 15, 2000.

Note that the year is represented as an offset from the year 1900 in both cases. Note,
this is how the date is stored internally. How you see the date in a report depends on how
the date is formatted.

The recommended display format for DATE values is ‗YYYY-MM-DD‘. This format will avoid
problems that may occur from formats specifying only two digits for the year. This is a
significant issue as dates for the year 2000 and beyond are now commonly entered.

Example

2006-03-14 formatted as ‘YY-MM-DD’ displays ad 01-03-14, which is also the
representation for 1901-03-14.
2006-03-14 formatted as ‘YYYY-MM-DD’ displays as 2006-03-14, which is unambiguous.

Note: Formatting techniques for dates are discussed in the forthcoming module 'Output
Attributes'.


Arithmetic Operators

Teradata provides six binary arithmetic operators and two unary arithmetic operators.
They are defined in the tables below:

Binary Operators (require two operands)

Operator              Definition
**                    exponentiation
*                     Multiply
/                     Divide
MOD                   Modulos (remainders)
+                     Add
-                     Subtract
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL
Introduction to Teradata SQL

Contenu connexe

Tendances

The Database Environment Chapter 7
The Database Environment Chapter 7The Database Environment Chapter 7
The Database Environment Chapter 7Jeanie Arnoco
 
Partitioning tables and indexing them
Partitioning tables and indexing them Partitioning tables and indexing them
Partitioning tables and indexing them Hemant K Chitale
 
Partitioning on Oracle 12c - What changed on the most important Oracle feature
Partitioning on Oracle 12c - What changed on the most important Oracle featurePartitioning on Oracle 12c - What changed on the most important Oracle feature
Partitioning on Oracle 12c - What changed on the most important Oracle featureLuis Marques
 
Teradata 13.10
Teradata 13.10Teradata 13.10
Teradata 13.10Teradata
 
Module 02 teradata basics
Module 02 teradata basicsModule 02 teradata basics
Module 02 teradata basicsMd. Noor Alam
 
White paper on Spool space in teradata
White paper on Spool space in teradataWhite paper on Spool space in teradata
White paper on Spool space in teradataSanjeev Kumar Jaiswal
 
Databases: Denormalisation
Databases: DenormalisationDatabases: Denormalisation
Databases: DenormalisationDamian T. Gordon
 
The Database Environment Chapter 11
The Database Environment Chapter 11The Database Environment Chapter 11
The Database Environment Chapter 11Jeanie Arnoco
 
Optimizing Queries over Partitioned Tables in MPP Systems
Optimizing Queries over Partitioned Tables in MPP SystemsOptimizing Queries over Partitioned Tables in MPP Systems
Optimizing Queries over Partitioned Tables in MPP SystemsEMC
 
The Database Environment Chapter 10
The Database Environment Chapter 10The Database Environment Chapter 10
The Database Environment Chapter 10Jeanie Arnoco
 
Sql ch 9 - data integrity
Sql ch 9 - data integritySql ch 9 - data integrity
Sql ch 9 - data integrityMukesh Tekwani
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresSteven Johnson
 
Understanding System Performance
Understanding System PerformanceUnderstanding System Performance
Understanding System PerformanceTeradata
 
Normalization by Ashwin and Tanmay
Normalization by Ashwin and TanmayNormalization by Ashwin and Tanmay
Normalization by Ashwin and TanmayAshwin Dinoriya
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesMaria Colgan
 

Tendances (20)

The Database Environment Chapter 7
The Database Environment Chapter 7The Database Environment Chapter 7
The Database Environment Chapter 7
 
Partitioning tables and indexing them
Partitioning tables and indexing them Partitioning tables and indexing them
Partitioning tables and indexing them
 
Ms sql server tips 1 0
Ms sql server tips 1 0Ms sql server tips 1 0
Ms sql server tips 1 0
 
Partitioning on Oracle 12c - What changed on the most important Oracle feature
Partitioning on Oracle 12c - What changed on the most important Oracle featurePartitioning on Oracle 12c - What changed on the most important Oracle feature
Partitioning on Oracle 12c - What changed on the most important Oracle feature
 
Teradata 13.10
Teradata 13.10Teradata 13.10
Teradata 13.10
 
Module 02 teradata basics
Module 02 teradata basicsModule 02 teradata basics
Module 02 teradata basics
 
White paper on Spool space in teradata
White paper on Spool space in teradataWhite paper on Spool space in teradata
White paper on Spool space in teradata
 
Databases: Denormalisation
Databases: DenormalisationDatabases: Denormalisation
Databases: Denormalisation
 
Data integrity
Data integrityData integrity
Data integrity
 
The Database Environment Chapter 11
The Database Environment Chapter 11The Database Environment Chapter 11
The Database Environment Chapter 11
 
Data integrity
Data integrityData integrity
Data integrity
 
Optimizing Queries over Partitioned Tables in MPP Systems
Optimizing Queries over Partitioned Tables in MPP SystemsOptimizing Queries over Partitioned Tables in MPP Systems
Optimizing Queries over Partitioned Tables in MPP Systems
 
Chapter8 my sql revision tour
Chapter8 my sql revision tourChapter8 my sql revision tour
Chapter8 my sql revision tour
 
The Database Environment Chapter 10
The Database Environment Chapter 10The Database Environment Chapter 10
The Database Environment Chapter 10
 
Sql ch 9 - data integrity
Sql ch 9 - data integritySql ch 9 - data integrity
Sql ch 9 - data integrity
 
MIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome MeasuresMIS5101 WK10 Outcome Measures
MIS5101 WK10 Outcome Measures
 
Understanding System Performance
Understanding System PerformanceUnderstanding System Performance
Understanding System Performance
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
 
Normalization by Ashwin and Tanmay
Normalization by Ashwin and TanmayNormalization by Ashwin and Tanmay
Normalization by Ashwin and Tanmay
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
 

Similaire à Introduction to Teradata SQL

SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSabrinaShanta2
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSaiMiryala1
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxBhupendraShahi6
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...SakkaravarthiS1
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL StatmentsUmair Shakir
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQueryAbhishek590097
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxEliasPetros
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptxEllenGracePorras
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorialMohd Tousif
 

Similaire à Introduction to Teradata SQL (20)

SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL Query
SQL QuerySQL Query
SQL Query
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Lab
LabLab
Lab
 
Assignment#02
Assignment#02Assignment#02
Assignment#02
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
lovely
lovelylovely
lovely
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Oracle sql material
Oracle sql materialOracle sql material
Oracle sql material
 
lect 2.pptx
lect 2.pptxlect 2.pptx
lect 2.pptx
 
Interview Questions.pdf
Interview Questions.pdfInterview Questions.pdf
Interview Questions.pdf
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 
SQL.ppt
SQL.pptSQL.ppt
SQL.ppt
 
Data Manipulation Language.pptx
Data Manipulation Language.pptxData Manipulation Language.pptx
Data Manipulation Language.pptx
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorial
 
SQL
SQLSQL
SQL
 
SQL commands
SQL commandsSQL commands
SQL commands
 

Dernier

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Dernier (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Introduction to Teradata SQL

  • 1. undefined Introduction to Teradata SQL (Module 1) Objectives After completing this module, you should be able to: Describe the structure of a Relational Database Management System (RDBMS). Explain the role of Structured Query Language (SQL) in accessing a Relational Database. List the three categories of SQL statements and describe their function. What is an RDBMS? Data is organized into tables in a relational database management system (RDBMS). Rows in the table represent instances of an entity, in this case an employee or a department. Columns represent the data fields which comprise the rows. Relations between tables occur when a column in one table also appears as a column in another. Here is an example of two related tables:
  • 2. Can you answer the following questions using the tables above? Question 1: What is the department name for employee 1004? Question 2: Who is the manager of employee 1004? What is SQL? Structured Query Language (SQL) is the industry standard language for communicating with Relational Database Management Systems. SQL is used to look up data in relational tables, create tables, insert data into tables, grant permissions and many other things. Structured Query Language is used to define the answer set that is returned from the Teradata Database. SQL is a non-procedural language, meaning it contains no procedural-type statements such as those listed here: GO TO PERFORM DO LOOP OPEN FILE
  • 3. CLOSE FILE END OF FILE SQL Commands SQL statements commonly are divided into three categories: 1. Data Definition Language (DDL) - Used to define and create database objects such as tables, views, macros, databases, and users. 2. Data Manipulation Language (DML) - Used to work with the data, including such tasks as inserting data rows into a table, updating an existing row, or performing queries on the data. The focal point of this course will be on SQL statements in this category. 3. Data Control Language (DCL) - Used for administrative tasks such as granting and revoking privileges to database objects or controlling ownership of those objects. DCL statements will not be covered in detail in this course. For complete Data Control Language coverage, please see the NCR Customer Education "Teradata Database Administration" course. Data Definition Language (DDL) Examples SQL statement Function CREATE Define a table, view, macro, index, trigger or stored procedure. DROP Remove a table, view, macro, index, trigger or stored procedure. ALTER Change table structure or protection definition. Data Manipulation Language (DML) SQL statement Function SELECT Select data from one or more tables. INSERT Place a new row into a table. UPDATE Change data values in one or more existing rows. DELETE Remove one or more rows from a table. Data Control Language (DCL) SQL statement Function GRANT Give user privileges. REVOKE Remove user privileges. GIVE Transfer database ownership. Relational Concepts
  • 4. The figure below illustrates six rows of a much larger table. Some interesting things to note about this table: The intersection of a row and a column is a data value. Data values come from a particular domain. Domains represent the pool of legal values for a column. For example, the data values in the EMPLOYEE NUMBER and MANAGER EMPLOYEE NUMBER come from the same domain because both columns come from the pool of employee numbers. The domain of employee numbers might be defined as the pool of integers greater than zero. The EMPLOYEE NUMBER column is marked PK, which indicates that this column holds the Primary Key. The next 3 columns are marked FK, which stands for Foreign Key. The purpose of the Primary Key is to uniquely identify each record. No two values in a primary key column can be identical. A Foreign Key represents the Primary Key of another table. Relationships between tables are formed through the use of Foreign Keys.
  • 5. Teradata SQL (Module 2) Objectives After completing this module, you should be able to: Describe the uses of the Teradata SQL SELECT statement. Retrieve data from a relational table using the SELECT statement. Use the SQL ORDER BY and DISTINCT options. Set a default database using the DATABASE command. Write SQL statements using recommended coding conventions. Name database objects according to Teradata SQL rules. SELECT Structured Query Language (SQL) consists of three types of statements, previously defined as: Data Definition Language (DDL) - Used to create, drop and modify objects Data Manipulation Language(DML) - Used to add, delete, update and read data rows in a table Data Control Language(DCL) - Used to implement security and control on database objects. Our focus in this course will be mostly on the DML portion of the language. We will first look at the SELECT statement. The SELECT statement allows you to retrieve data from one or more tables. In its most common form, you specify certain rows to be returned as shown. SELECT * FROM employee WHERE department_number = 401; The asterisk, "*", indicates that we wish to see all of the columns in the table. The FROM clause specifies from which table in our database to retrieve the rows. The WHERE clause acts as a filter which returns only rows that meet the specified condition, in this case, records of employees in department 401. Note: SQL does not require a trailing semicolon to end a statement but the Basic Teradata Query (BTEQ) utility that we use to enter SQL commands does require it. All examples in this course will include the semicolon.
  • 6. What if we had not specified a WHERE clause. SELECT * FROM employee; This query would return all columns and all rows from the employee table. Instead of using the asterisk symbol to specify all columns, we could name specific columns separated by commas: SELECT employee_number ,hire_date ,last_name ,first_name FROM employee WHERE department_number = 401; employee_number hire_date last_name first_name -------------------- ---------- ----------- ----------- 1004 76/10/15 Johnson Darlene 1003 76/07/31 Trader James 1013 77/04/01 Phillips Charles 1010 77/03/01 Rogers Frank 1022 79/03/01 Machado Albert 1001 76/06/18 Hoover William 1002 76/07/31 Brown Alan Unsorted Results Results come back unsorted unless you specify that you want them sorted in a certain way. How to retrieve ordered results is covered in the next section. ORDER BY Clause Use the ORDER BY clause to have your results displayed in a sorted order. Without the ORDER BY clause, resulting output rows are displayed in a random sequence. SELECT employee_number ,last_name ,first_name ,hire_date FROM employee WHERE department_number = 401 ORDER BY hire_date; Sort Direction In the example above, results will be returned in ascending order by hire date. Ascending order is the default sort sequence for an ORDER BY clause. To explicitly specify ascending or
  • 7. descending order, add ASC or DESC, to the end of the ORDER BY clause. The following is an example of a sort using descending sequence. ORDER BY hire_date DESC; Naming the Sort Column You may indicate the sort column by naming it directly (e.g., hire_date) or by specifying its position within the SELECT statement. Since hire_date is the fourth column in the SELECT statement, the following ORDER BY clause is equivalent to saying ORDER BY hire_date. ORDER BY 4; Multiple ORDER BY Columns An ORDER BY clause may specify multiple columns. No single column in an ORDER BY clause should exceed a length of 4096 bytes, otherwise it will be truncated for sorting purposes. The order in which columns are listed in the ORDER BY clause is significant. The column named first is the major sort column. The second and subsequent are minor sort columns. In the following example, results are sorted by department number in ascending order. Where multiple records share the same department number, those rows are sorted by job_code in ascending order. The following are examples: SELECT employee_number ,department_number ,job_code FROM employee WHERE department_number < 302 ORDER BY department_number ,job_code; employee_number department_number job_code -------------------- ---------------------- ---------- 801 100 111100 1025 201 211100 1021 201 222101 1019 301 311100 1006 301 312101 1008 301 312102 Note: Each column specified in the ORDER BY clause can have its own sort order, either ascending or descending. SELECT employee_number ,department_number ,job_code FROM employee WHERE department_number < 302 ORDER BY department_number ASC ,job_code DESC;
  • 8. employee_number department_number job_code -------------------- ---------------------- ---------- 801 100 111100 1021 201 222101 1025 201 211100 1008 301 312102 1006 301 312101 1019 301 311100 DISTINCT The DISTINCT operator will consolidate duplicate output rows to a single occurrence. Example Without DISTINCT SELECT department_number ,job_code FROM employee WHERE department_number = 501; department_number job_code ---------------------- ---------- 501 512101 501 512101 501 511100 Note: Two people in department 501 have the same job code (512101). If our purpose is simply to find out which job codes exist in department 501, we could use DISTINCT to avoid seeing duplicate rows. Example With DISTINCT SELECT DISTINCT department_number ,job_code FROM employee WHERE department_number = 501; department_number job_code ---------------------- ---------- 501 511100 501 512101 Note: DISTINCT appears directly after SELECT, and before the first named column. It may appear to apply only to the first column, but in fact, DISTINCT applies to all columns named in the query. Two rows in our result example set both have department_number 501. The combination of department_number and job_code are distinct since the job codes differ. Naming Database Objects All Teradata objects, such as tables, must be assigned a name by the user when they are
  • 9. created. These rules for naming objects are summarized as follows: Names are composed of: a-z A-Z 0-9 _ (underscore) $ # Names are limited to 30 characters. Names cannot begin with a number. Teradata names are not case-sensitive. Examples of valid names: Accounts Accounts_2005 accounts_over_$2000 Account# Equivalence Accounts and accounts represent the same table. Case is not considered. Naming Rules Naming Syntax Database names and User names must be unique within the Teradata Database. Table, view, macro, trigger, index and stored procedure names must be unique within a Database or User. Column names must be unique within a Table. The syntax for fully qualifying a column name is: Databasename.Tablename.Columnname Example NAME (unqualified) EMPLOYEE.NAME (partially qualified) PAYROLL.EMPLOYEE.NAME (fully qualified)
  • 10. Note: The amount of qualification necessary is a function of your default database setting. Coding Conventions SQL is considered a 'free form' language, that is, it can cover multiple lines of code and there is no restriction on how much 'white space' (i.e., blanks, tabs, carriage returns) may be embedded in the query. Having said that, SQL is syntactically a very precise language. Misplaced commas, periods and parenthesis will always generate a syntax error. The following coding conventions are recommended because they make it easier to read, create, and change SQL statements. Recommended Practice SELECT last_name ,first_name ,hire_date ,salary_amount FROM employee WHERE department_number = 401 ORDER BY last_name; Not Recommended Practice select last_name, first_name, hire_date, salary_amount from employee where department_number = 401 order by last_name; The first example is easy to read and troubleshoot (if necessary). The second example appears to be a jumble of words. Both, however, are valid SQL statements. Default Database Setting the Default Database As a valid user, you will normally have access rights to your own user database and the objects it contains. You may also have permission to access objects in other databases. The user name you logon with is usually your default database. (This depends on how you were created as a user.)
  • 11. For example, if you log on as: .logon rayc; password: xyz then "rayc" is normally your default database. Note the dot (.) before "logon". Commands that begin with a dot are BTEQ commands, not SQL commands. The BTEQ command processor will read this command; the SQL processor will not see it. Queries you make that do not specify the database name will be made against your default database. Changing the Default Database The DATABASE command is used to change your default database. For example: DATABASE payroll; sets your default database to payroll. Subsequent queries (assuming the proper privileges are held) are made against the payroll database. Lab For this set of lab questions you will need information from the Database Info document. These exercises are to be done as a pencil-and-paper workshop. Write SQL statements as you would enter them on-line. Click on the buttons to the left to see the answers. Question 3: A. Select all columns for all departments from the department table. B. Using the employee table, generate a report of employee last and first names and salary for all of manager 1019's employees. Order the report in last name ascending sequence. C. Modify the previous request to show department number instead of first name. Make it for manager 801's employees instead of manager 1019's. D. Prepare a report of the department numbers and the manager's employee numbers for everyone in the employee table. Now add the DISTINCT option to the same report. Note: Save your answers for this Lab, as you actually enter and run these exercises using BTEQ scripts for the Labs in Module 3. Simple BTEQ (Module 3)
  • 12. Objectives After completing this module, you should be able to: Use BTEQ to submit SQL to the Teradata database. Set session parameters to enable  Teradata transaction semantics.  The SQL Flagger. What is BTEQ? BTEQ is a front end tool for submitting SQL queries. 'BTEQ' stands for Basic Teradata Query program. BTEQ is client software that resides on your network or channel-attached host. After starting BTEQ, you will log on to Teradata using a TDP-id (Teradata Director Program id), your user id and password. The TDP-id identifies the instance of Teradata you are going to access. TDP's come in two varieties - the standard TDP for channel-attached clients, and the Micro- TDP (or MTDP) for network-attached clients. They are involved in getting your SQL requests routed to a Parsing Engine (PE) which validates your request and passes it to the Access Module Processors (AMPs). AMPs retrieve the answer sets from the disks and send the response set back to the PE which in turn forwards it to the TDP and ultimately back to you at your session. Where is BTEQ Located? BTEQ is Teradata client software which is installed on mainframe hosts or network attached clients. It operates under all host systems and local area networks (LANs). BTEQ Commands Facts about BTEQ commands: Must be preceded by a period (.) or terminated by a semi-colon or both. Provide an output listing (an audit trail) of what occurred. Additional commands for report formatting are available. Are not case-sensitive. Invoking BTEQ varies somewhat depending on the platform. In the UNIX enviroment, simply typing in the command 'bteq' is required. For purposes of this course, instructions for starting a lab session are contained on each lab page. Using BTEQ Interactively
  • 13. Submitting SQL Statements with BTEQ There are two ways to submit SQL statements to BTEQ in interactive mode: Type in SQL statements directly to the BTEQ prompt. Open another window with a text editor. Compose SQL statements using the text editor, then cut and paste the SQL to the BTEQ prompt. When users log on to BTEQ, they are by default assigned a single session. Session Parameters Session parameters include transaction semantics and the SQL Flagger. Transaction semantics, allows you to set your session in either ANSI or Teradata (BTET) mode. All features of Teradata SQL will work in either mode, but each mode activates different case-sensitivity and data conversion defaults, and so the same query might return different results in each mode. For purposes of this course, Teradata-mode sessions will be assumed unless otherwise specified. More on these session parameters is covered in the Teradata SQL Advanced WBT. Example .SET SESSION TRANSACTION ANSI; /* Sets ANSI mode*/ .SET SESSION TRANSACTION BTET; /* Sets Teradata mode*/ Note: All text between /* and */ are treated as comments by BTEQ. You may also activate the ANSI Flagger, which automatically flags non-ANSI compliant syntax with a warning but still returns the expected answer set. Example .SET SESSION SQLFLAG ENTRY; /* Causes non-Entry level ANSI syntax to be flagged */ SELECT DATE; /* Causes a warning because keyword DATE is not ANSI standard*/ *** SQL Warning 5821 Built-in values DATE and TIME are not ANSI. *** Query completed. One row found. One column returned. *** Total elapsed time was 1 seconds. Date -------- 05/01/12
  • 14. Example .SET SESSION SQLFLAG NONE /* Disables ANSI Flagger*/ SELECT DATE; /* DATE keyword is not flagged */ *** Query completed. One row found. One column returned. *** Total elapsed time was 1 second. Date -------- 05/01/12 Note: In both cases, the date was returned. You need to establish your session parameters prior to logging on. Teradata extensions cannot be disabled, but they can be flagged using the ANSI flagger. The SHOW CONTROL Command The BTEQ .SHOW CONTROL command displays BTEQ settings. The following output shows the result of this command. .SHOW CONTROL Default Maximum Byte Count = 4096 Default Multiple Maximum Byte Count = 2048 Current Response Byte Count = 4096 Maximum number of sessions = 20 Maximum number of the request size = 32000 EXPORT RESET IMPORT FIELD LOGON L7544/tdxxx RUN [SET] ECHOREQ = ON [SET] ERRORLEVEL = ON [SET] FOLDLINE = OFF ALL [SET] FOOTING = NULL [SET] FORMAT = OFF [SET] FORMCHAR = OFF [SET] FULLYEAR = OFF [SET] HEADING = NULL [SET] INDICDATA = OFF [SET] NOTIFY = OFF [SET] NULL = ? [SET] OMIT = OFF ALL [SET] PAGEBREAK = OFF ALL [SET] PAGELENGTH = 55 [SET] QUIET = OFF [SET] RECORDMODE = OFF [SET] REPEATSTOP = OFF
  • 15. [SET] RETCANCEL = OFF [SET] RETLIMIT = No Limit [SET] REPEATSTOP = OFF [SET] RETCANCEL = OFF [SET] RETLIMIT = No Limit [SET] RETRY = ON [SET] RTITLE = NULL [SET] SECURITY = NONE [SET] SEPARATOR = two blanks [SET] SESSION CHARSET = ASCII [SET] SESSION SQLFLAG = NONE [SET] SESSION TRANSACTION = BTET [SET] SESSIONS = 1 [SET] SIDETITLES = OFF for the normal report. [SET] SKIPDOUBLE = OFF ALL [SET] SKIPLINE = OFF ALL [SET] SUPPRESS = OFF ALL [SET] TDP = L7544 [SET] TIMEMSG = DEFAULT [SET] TITLEDASHES = ON for the normal report. [SET] UNDERLINE = OFF ALL [SET] WIDTH = 75 BTEQ Scripts A BTEQ script is a file that contains BTEQ commands and SQL statements. A script is built for sequences of commands that are to be executed on more than one occasion, i.e. monthly, weekly, daily. How to create a BTEQ Script To create and edit a BTEQ script, use an editor on your client workstation. For example, on a UNIX workstation, use either the vi or text editor. How to Submit a BTEQ Script Start BTEQ, then enter the following BTEQ command to submit a BTEQ script: .run file = <scriptname> BTEQ Comments -- Teradata Extensions The Teradata RDBMS supports comments that span multiple lines by using the "/*" and "*/" as delimiters. Example of a BTEQ comment: /* You can include comments in a BTEQ script by enclosing the comment text between “/*” and “*/” and the comment may span multiple lines */
  • 16. Script Example Let's look at an example of a BTEQ script using ANSI standard comments. The ANSI comment delimiter is the double dash, --. (This script is named mod2exer.scr ) .SET SESSION TRANSACTION ANSI .LOGON L7544/tdxxx,; -- Obtain a list of the department numbers and names -- from the department table. SELECT department_number ,department_name FROM department; .QUIT Note: Both Teradata style (/* */) and ANSI style (--) comments may be included in any SQL command script. To Execute The Script: .run file=mod2exer.scr (The following is the output generated by the above command.) Script started on Sat Feb 15 10:48:19 1997 $ bteq Teradata BTEQ 04.00.01.00 for UNIX5. Enter your logon or BTEQ command: .run file=mod2exer.scr (this is the only user input; the rest of the commands came from file mod2exer.scr) .run file=mod2exer.scr Teradata BTEQ 04.00.01.00 for UNIX5. Enter your logon or BTEQ command: .LOGON L7544/tdxxx, *** Logon successfully completed. *** Transaction Semantics are ANSI. *** Character Set Name is 'ASCII'. *** Total elapsed time was 1 second. BTEQ -- Enter your DBC/SQL request or BTEQ command: -- Obtain a list of the department numbers and names
  • 17. -- from the department table. SELECT department_number ,department_name FROM department; *** Query completed. 9 rows found. 2 columns returned. *** Total elapsed time was 1 second. department_number department_name ------------------ ----------------- 401 customer support <rest of result rows are not shown in this screen capture> BTEQ -- Enter your DBC/SQL request or BTEQ command: .QUIT *** You are now logged off from the DBC. *** Exiting BTEQ... *** RC (return code) = 0 # exit Using BTEQ in BATCH Mode If you prefer to write all SQL statements in a single script file, there are two ways you may execute the script: Start BTEQ in interactive mode. Use the following BTEQ command to execute the script: .run file = mod2exer.scr Start BTEQ and redirect standard input to use the script file. $bteq < mod2exer.scr (Note: The dollar sign ‗$‘ corresponds to the UNIX prompt.) How to Capture BTEQ Session Output From a UNIX workstation, use the script <filename> command to capture the output of your session : $script <filename> Logs all input and output to <filename>. $bteq Starts BTEQ in interactive mode. .run file = <scriptname> Submits pre-written script which contains BTEQ
  • 18. commands and SQL statements. The contents of <scriptname> and responses from the Teradata database will be output to both the screen and the designated <filename> if one has been designated. How to Stop Capturing BTEQ Session Output From a UNIX workstation, issue the following UNIX command to stop the script command: $exit This closes the logging file but does not terminate the UNIX session. Identifying Syntax Errors BTEQ output results will display a "$" to indicate the location where the error was detected in either the script or request. The following is an example of captured output showing a syntax error: Script started on Thu Oct 24 16:21:21 1996 # bteq … Teradata BTEQ 04.00.00.00 for UNIX5. Enter your logon or BTEQ command: .logon L7544/tdxxx, *** Logon successfully completed. *** Transaction Semantics are ANSI. *** Character Set Name is 'ASCII'. *** Total elapsed time was 1 second. BTEQ -- Enter your DBC/SQL request or BTEQ command: SELECT department_number ,DISTINCT department_name FROM department; ,DISTINCT department_name $ *** Failure 3708 Syntax error, 'DISTINCT' that follows the ',' should be deleted. Statement# 1, Info =36 *** Total elapsed time was 1 second .BTEQ -- Enter your DBC/SQL request or BTEQ command:
  • 19. .quit *** You are now logged off from the DBC. *** Exiting BTEQ... *** RC (return code) = 8 # exit script done on Thu Oct 24 16:21:39 1996 The dollar sign points to the command DISTINCT. The error text tells us that DISTINCT should be deleted. The DISTINCT command must directly follow the SELECT command in your request. Lab For this set of lab questions you will need information from the Database Info document. To start the online labs, click on the Telnet button in the lower left hand screen of the course. Two windows will pop-up: a BTEQ Instruction Screen and your Telnet Window. Sometimes the BTEQ Instructions get hidden behind the Telnet Window. You will need these instructions to log on to Teradata. Be sure to change your default database to the Customer_Service database in order to run these labs. Question 4: A. See Labs A, B, and C from Module 2 that you did on paper. You can use NotePad or another text editor to create your SQL requests again, and then simply copy and paste them into the Telnet window after you've logged on with BTEQ. B. Use BTEQ to submit your two reports from Lab D in Module 2. Observe the number of rows returned in your output. Which rows were eliminated due to the DISTINCT option? Click on the Lab B button to see the answer for this Lab. C. Set the ANSI Flagger ON and observe the differences it produces. Do this by: Logging off of Teradata (.logoff). Setting the flagger on (.SET SESSION SQLFLAG ENTRY). Relogging on to Teradata Resubmit your query from Lab A.1. What differences do you observe? Why? (Note: the ANSI Flagger is covered in more detail in SQL Level 3.)
  • 20. Click on the Lab C button to see the answer for this Lab. D. 1) Determine the default system session transaction mode. What command did you use? 2) Set the session transaction mode to the opposite setting (e.g., set it to ANSI if the system default is BTET) then verify the new setting. Click on the Lab D button to see the answer for this Lab. Lab Answer A.A DATABASE Customer_Service; SELECT * FROM department ORDER BY 1; *** Query completed. 9 rows found. 4 columns returned. *** Total elapsed time was 1 second. department_number department_name budget_amount manager_employee_number ----------------------- --------------------- ------------------ --------------------------------- 100 president 400000.00 801 401 customer support 982300.00 1003 403 education 932000.00 1005 402 software support 308000.00 1011 302 product planning 226000.00 1016 501 marketing sales 308000.00 1017 301 research and development 465600.00 1019 201 technical operations 293800.00 1025 600 None ? 1099 Note: Order is random. And user input is highlighted in red Lab Answer A.B SELECT last_name ,first_name ,salary_amount FROM employee WHERE manager_employee_number = 1019 ORDER BY last_name ; *** Query completed. 2 rows found. 3 columns returned. last-name first-name salary-amount Kanieski Carol 29250.00 Stein John 29450.00
  • 21. Lab Answer A.C SELECT last_name ,department_number ,salary_amount FROM employee WHERE manager_employee_number = 801 ORDER BY last_name ; *** Query completed. 8 rows found. 3 columns returned. last_name department_number salary_amount Daly 402 52500.00 Kubic 301 57700.00 Rogers 302 56500.00 Runyon 501 66000.00 Ryan 403 31200.00 Short 201 34700.00 Trader 401 37850.00 Trainer 100 100000.00 Lab Answer B
  • 22. SELECT department_number ,manager_employee_number FROM employee ; *** Query completed. 26 rows found. 2 columns returned. department_number manager_employee_number 301 1019 501 801 100 801 401 801 402 1011 301 801 301 1019 402 801 401 1003 403 1005 401 1003 403 1005 403 801 201 801 201 1025 501 1017 403 1005 501 1017 401 1003 401 1003 401 1003 403 1005 403 1005 401 1003 501 1017 302 801 SELECT DISTINCT department_number ,manager_employee_number FROM employee ; *** Query completed. 14 rows found. 2 columns returned. department_number manager_employee_number 100 801 201 801 201 1025 301 801 301 1019 302 801 401 801 401 1003
  • 23. 402 801 402 1011 403 801 403 1005 501 801 501 1017
  • 24. Lab Answer C Note: Actual warning messages generated will vary depending on how you have written your queries. Remember that ANSI does not support any lower case syntax. .SET SESSION SQLFLAG ENTRY .LOGON RPC1042/tdxxx; SELECT * FROM department ; *** Query completed. 9 rows found. 4 columns returned. *** Total elapsed time was 1 second. FROM department $ *** SQL Warning 5836 Token is not an entry level ANSI Identifier or Keyword. department_number department_name budget_amount manager_employ ----------------- ----------------------- ------------- -------- ------ 100 president 400000.00 801 401 customer support 982300.00 1003 403 education 932000.00 1005 402 software support 308000.00 1011 302 product planning 226000.00 1016 501 marketing sales 308000.00 1017 301 research and development 465600.00 1019 201 technical operations 293800.00 1025 600 None ? 1099 The warning message is generated because the ANSI flagger is enabled and is reporting that ANSI mode does not support lowercase syntax. Lab Answer D
  • 25. .SHOW CONTROL . . . [SET] SESSION SQLFLAG = ENTRY [SET] SESSION TRANSACTION = BTET . . . .LOGOFF .SET SESSION TRANSACTION ANSI .SHOW CONTROL . . . [SET] SESSION SQLFLAG = ENTRY [SET] SESSION TRANSACTION = ANSI . . . HELP Functions Module 4 Objectives After completing of this module, you should be able to: Obtain the definition of an existing Database, Table, View, or Macro using the HELP and SHOW statements. Determine how the Teradata RDBMS will process a SQL request using the EXPLAIN statement. Teradata SQL Extensions Several commands in our software are Teradata-specific. Here is a list of Teradata extensions covered within this course. ADD_MONTHS BEGIN/ END TRANSACTION COLLECT/ DROP COMMENT ON STATISTICS CONCATENATION EXPLAIN FALLBACK FORMAT
  • 26. HELP INDEX LOCKING MACRO Facility • CREATE • REPLACE • DROP • EXECUTE NAMED NULLIFZERO/ZEROIFNULL SHOW SUBSTR TITLE TRIM WITH WITH . . . BY In this module, we focus on the following functions: EXPLAIN HELP SHOW HELP Commands: Database objects The HELP Command is used to display information about database objects such as (but not limited to): Databases and Users Tables Views Macros HELP retrieves information about these objects from the Data Dictionary. Below are the syntactical options for various forms of the HELP command: HELP Command HELP DATABASE databasename; HELP USER username; HELP TABLE tablename; HELP VIEW viewname; HELP MACRO macroname; HELP COLUMN table or viewname.*; (all columns) HELP COLUMN table or viewname.colname . . ., colname; Some of the other HELP commands which will be seen later in this course include:
  • 27. HELP INDEX tablename; HELP STATISTICS tablename; HELP CONSTRAINT constraintname; HELP JOIN INDEX join_indexname; HELP TRIGGER triggername; The HELP DATABASE Command The HELP DATABASE command in the following example shows all objects in the Customer_Service database. Objects may be recognized by their 'Kind' designation as follows: Table =T View =V Macro =M Trigger =G Join Index =J Stored Procedure =P HELP DATABASE Customer_Service; Results will be displayed as follows: Table/View/Macro Kind Comment Name contact T ? customer T ? department T ? employee T ? employee_phone T ? job T ? location T ? location_employee T ? location_phone T ? All objects in this database are tables. The '?' is how BTEQ displays a null, indicating that no user comments have been entered. Note: To return HELP information on an object, a user must either own the object or have at least one privilege on it.
  • 28. The HELP TABLE Command The HELP TABLE command shows the name, data type, and comment (if applicable), of all columns in the specified table: HELP TABLE Customer_Service.employee ColumnName Type Comment employee_number I System assigned identification manager_employee_number I ? department_number I Department employee works in job_code I Job classification designation last_name CF Employee surname first_name CV Employee given name hire_date DA Date employee was hired birthdate DA ? salary_amount D Annual compensation amount Data types are as follows: Type Description Type Description CF CHARACTER FIXED F FLOAT CV CHARACTER VARIABLE BF BYTE D DECIMAL BV VARBYTE DA DATE AT TIME I INTEGER TS TIMESTAMP I1 BYTEINT I2 SMALLINT HELP Commands: Session Characteristics Use the HELP SESSION; command to see specific information about your SQL session. The following displays the user name with which you logged in log-on date and time, your default database, and other information related to your current session: User Name DBC Account Name DBC Log on Date 05/02/18 Log on Time 11:54:46 Current DataBase DBC
  • 29. Collation ASCII Character Set ASCII Transaction Semantics Teradata Current DateForm IntegerDate Session Time Zone 00:00 Default Character Type LATIN Export Latin 1 Export Unicode 1 Export Unicode Adjust 0 Export KanjiSJIS 1 Export Graphic 0 Default Date Format None To produce the formatting shown above use: .SET FOLDLINE ON .SET SIDETITLES ON The SHOW Command The SHOW command displays the current Data Definition Language (DDL) of a database object (e.g., Table, View, Macro, Trigger, Join Index or Stored Procedure). The SHOW command is used primarily to see how an object was created. Sample Show Commands Command Returns CREATE TABLE SHOW TABLE tablename; statement CREATE VIEW SHOW VIEW viewname; statement CREATE MACRO SHOW MACRO macroname; statement BTEQ also has a SHOW command (.SHOW CONTROL) which is different from the SQL SHOW command. It provides information on formatting and display settings for the current BTEQ session. The SHOW TABLE Command
  • 30. The SHOW TABLE command seen here returns the CREATE TABLE statement that was used to create the employee table. To perform a SHOW TABLE, the user must have a privilege on either the table itself or the containing database. CREATE SET TABLE CUSTOMER_SERVICE.employee ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( employee_number INTEGER, manager_employee_number INTEGER, department_number INTEGER, job_code INTEGER, last_name CHAR(20) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL, first_name VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC NOT NULL, hire_date DATE NOT NULL, birthdate DATE NOT NULL, salary_amount DECIMAL(10,2) NOT NULL) UNIQUE PRIMARY INDEX (employee_number); Note: If a table is subsequently altered after it has been created, the SHOW command will always reflect the most current alterations. The SHOW VIEW Command The SHOW VIEW command shows you the CREATE VIEW statement used to create a view: SHOW VIEW dept; Result CREATE VIEW dept (dept_num ,dept_name ,budget ,manager) AS SELECT department_number ,department_name ,budget_amount ,manager_employee_number FROM CUSTOMER_SERVICE.department; The view may be accessed instead of the table: SELECT * FROM dept; Result dept_num dept_name budget manager
  • 31. --------- ----------- -------- --------- 301 research & development 46560000 1019 302 product planning 22600000 1016 501 marketing sales 80050000 1017 403 education 93200000 1005 402 software support 30800000 1011 401 customer support 98230000 1003 201 technical operations 29380000 1025 The SHOW Macro Command The SHOW MACRO command shows you the statement used to create a macro: SHOW MACRO get_depts; Result CREATE MACRO get_depts AS (SELECT department_number ,department_name ,budget_amount ,manager_employee_number FROM department; ); The EXPLAIN Command The EXPLAIN function looks at a SQL request and responds in English how the optimizer plans to execute it. It does not actually execute the SQL statement however it is a good way to see what database resources will be used in processing your request. For instance, if you see that your request will force a full-table scan on a very large table or cause a Cartesian Product Join, you may decide to re-write a request so that it executes more efficiently. EXPLAIN provides a wealth of information, including the following: 1. Which indexes if any will be used in the query. 2. Whether individual steps within the query may execute concurrently (i.e. parallel steps). 3. An estimate of the number of rows which will be processed. 4. An estimate of the cost of the query (in time increments).
  • 32. EXPLAIN SELECT * FROM department; *** Query completed. Ten rows found. One column returned. Explanation 1. First, we lock a distinct CUSTOMER_SERVICE."pseudo table" for read on a RowHash to prevent global deadlock for CUSTOMER_SERVICE.department. 2. Next, we lock CUSTOMER_SERVICE.department for read. 3. We do an all-AMPs RETRIEVE step from CUSTOMER_SERVICE.department by way of an all-rows scan with no residual conditions into Spool 1, which is built locally on the AMPs. The size of Spool 1 is estimated with low confidence to be 4 rows. The estimated time for this step is 0.15 seconds. 4. Finally, we send out an END TRANSACTION step to all AMPs involved in processing the request. The contents of Spool 1 are sent back to the user as the result of statement 1. The total estimated time is 0.15 seconds. Lab For this set of lab questions you will need information from the Database Info document. To start the online labs, click on the Telnet button in the lower left hand screen of the course. Two windows will pop-up: a BTEQ Instruction Screen and your Telnet Window. Sometimes the BTEQ Instructions get hidden behind the Telnet Window. You will need these instructions to log on to Teradata. A. Use the HELP DATABASE command to find all tables, views, and macros names in the CS_Views database. What kind of objects do you find there? Do a similar HELP command on the Customer_Service database. What kind of objects do you find there? B. To see the names of the columns in the department table, use the appropriate HELP command. (Since the table is in the Customer_Service database, not your default database, you'll have to qualify the table name with the database name.) This is the command you may wish to use in the future to research data names. C. In Lab A, you may have noticed that the CS_Views database includes a view called emp. SHOW that view. Notice the list of short names the emp view uses in place of full column names. To save typing, you may use the emp view with the shortened names in place of the employee table in any labs throughout this course. (All lab solutions shown in this book use the employee table in Customer_Service.) D. Modify Lab A.1 from the previous module to cause the answer set to appear in department name sequence. To find out how Teradata plans to handle this request, submit it with EXPLAIN in front of it. E. Use the appropriate SHOW command to see the table definition of the employee_phone table in the Customer Service database.
  • 33. F. Use the appropriate HELP command to see what kinds of indexes exist on the customer table. To get information about your session, use another HELP command. Change the display settings for sidetitles and foldline to better view the session information. Be sure to reset display attributes once you have seen results. G. Change your current database setting to Customer_Service using the DATABASE command. Try to do a SELECT of all columns and rows in the emp view. Does it work? If not, how can you make it work? Lab Answer A HELP DATABASE cs_views; *** Help information returned. 15 rows found. Table/View/Macro name Kind Comment agent_sales V ? contact V ? customer V ? daily_sales V ? department V ? emp V ? employee V ? employee_phone V ? jan_sales V ? job V ? location V ? location_employee V ? location_phone V ? repair_time V ? sales_table V ? HELP DATABASE customer_service; *** Help information returned. 14 rows found. Table/View/Macro name Kind Comment agent_sales T ? contact T ? customer T ? daily_sales T ? department T ? employee T ? employee_phone T ? jan_sales T ? job T ? location T ? location_employee T ? location_phone T ?
  • 34. repair_time T ? sales_table T ? Lab Answer B HELP TABLE customer_service.department; *** Help information returned. 4 rows found. Column Name Type Comment ------------------------------ ---- ----------- department_number I2 ? department_name CF ? budget_amount D ? manager_employee_number I ? Lab Answer C SHOW VIEW cs_views.emp; *** Text of DDL statement returned. CREATE VIEW emp (emp ,mgr ,dept ,job ,last ,first ,hire ,birth ,sal) AS SELECT employee_number ,manager_employee_number ,department_number ,job_code ,last_name ,first_name ,hire_date ,birthdate
  • 35. ,salary_amount FROM CUSTOMER_SERVICE.employee; Lab Answer D EXPLAIN SELECT * FROM customer_service.department ORDER BY department_name ; *** Help information returned. 11 rows found. Explanation 1. First, we lock a distinct customer_service."pseudo table" for read on a RowHash to prevent global deadlock for customer_service.department. 2. Next, we lock customer_service.department for read. 3. We do an all-AMPs RETRIEVE step from customer_service.department by way of an all-rows scan with no residual conditions into Spool 1, which is built locally on the AMPs. Then we do a SORT to order Spool 1 by the sort key in spool field1. The size of Spool 1 is estimated with low confidence to be 12 rows. The estimated time for this step is 0.15 seconds. 4. Finally, we send out an END TRANSACTION step to all AMPs involved in processing the request. -> The contents of Spool 1 are sent back to the user as the result of statement 1. The total estimated time is 0.15 seconds. Lab Answer E SHOW TABLE Customer_Service.employee_phone; *** Text of DDL statement returned. CREATE TABLE customer_service.employee_phone ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( employee_number INTEGER NOT NULL, area_code SMALLINT NOT NULL, phone INTEGER NOT NULL, extension INTEGER, comment_line CHAR(72) CHARACTER SET LATIN NOT CASESPECIFIC)
  • 36. PRIMARY INDEX( employee_number ) ; Lab Answer F HELP INDEX Customer_Service.customer; *** Help information returned. One row. Primary or Unique Secondary Column Names Y P customer_number .SET SIDETITLES ON .SET FOLDLINE ON HELP SESSION; User Name tdxxx Account Name $M_P0623_&D Logon Date 00/11/29 Logon Time 11:52:18 Current DataBase tdxxx Collation ASCII Character Set ASCII Transaction Semantics Teradata Current DateForm IntegerDate Session Time Zone 00:00 Default Character Type LATIN Export Latin 1 Export Unicode 1 Export Unicode Adjust 0 Export KanjiSJIS 1 Export Graphic 0 Default Date Format None .SET SIDETITLES OFF .SET FOLDLINE OFF Lab Answer G DATABASE Customer_Service; SELECT * FROM emp;
  • 37. (Fails because the emp view is not in database customer_service. To make it work, fully qualify the view name.) SELECT * FROM CS_Views.emp; (You may also change the default database.) DATABASE CS_Views; SELECT * FROM emp; Logical and Conditional Expressions Module 5 Objectives After completing this module, you should be able to: Combine the following types of operators into logical expressions:  comparison operators  [NOT] IN  IS [NOT] NULL  LIKE Form expressions involving NULL values. Qualify a range of values. Search for a partial string within a string expression. Combine multiple logical expressions into a conditional expression using AND and OR. Logical Operators Operators are symbols or words that cause an 'operation' to occur on one or more elements called 'operands'. Logical expressions combine operands and operators to produce a Boolean (true/false) result. Logical expressions can be combined into conditional expressions which are used in the WHERE clause of a SELECT statement. Types of Operators in Logical Expressions Operator Syntax Meaning = equal <> not equal > greater than
  • 38. < less than >= greater than or equal to <= less than or equal to BETWEEN <a> AND <b> inclusive range [NOT] IN <expression> is in a list or <expression> is not in a list IS [NOT] NULL <expression> is null or <expression> is not null [NOT] EXISTS* table contains at least 1 row or table contains no rows LIKE partial string operator The EXISTS operator is covered in the Teradata Advanced SQL course. BETWEEN -- Numeric Range Testing To locate rows for which a numeric column is within a range of values, use the BETWEEN <a> AND <b> operator. Specify the upper and lower range of values that qualify the row. The BETWEEN operator looks for values between the given lower limit <a> and given upper limit <b> as well as any values that equal either <a> or <b> (i.e., BETWEEN is inclusive.) Example Select the name and the employee's manager number for all employees whose job codes are in the 430000 range. SELECT first_name ,last_name ,manager_employee_number FROM employee WHERE job_code BETWEEN 430000 AND 439999; An alternative syntax is shown below: SELECT first_name ,last_name ,manager_employee_number FROM employee WHERE job_code >= 430000 AND job_code <= 439999;
  • 39. first_name last_name manager_employee_number ----------- ----------- ------------------------------ Loretta Ryan 801 Armando Villegas 1005 BETWEEN -- Character Range Testing Use the BETWEEN <a> AND <b> operator to locate rows for which a character column is within a range of values. Specify the upper and lower range of values that qualify the row. BETWEEN will select those values which are greater than or equal to <a> and less or equal to <b>. (BETWEEN is inclusive.) SELECT last_name FROM employee WHERE last_name BETWEEN 'r' AND 's'; last_name ------------ Ryan Note: 'Stein' is not included because 'S_____' sorts lower than 'Stein'. (Teradata is not case-sensitive by default.) Set Operator IN Use the IN operator as shorthand when multiple values are to be tested. Select the name and department for all employees in either department 401 or 403. This query may also be written using the OR operator which we shall see shortly. SELECT first_name ,last_name ,department_number FROM employee WHERE department_number IN (401, 403); first_name last_name department_number ----------- ----------- ---------------------
  • 40. Darlene Johnson 401 Loretta Ryan 403 Armando Villegas 403 James Trader 401 Set Operator NOT IN Use the NOT IN operator to locate rows for which a column does not match any of a set of values. Specify the set of values which disqualifies the row. SELECT first_name ,last_name ,department_number FROM employee WHERE department_number NOT IN (401, 403) ; first_name last_name department_number ----------- ----------- --------------------- Carol Kanieski 301 John Stein 301
  • 41. NOT IN vs. OR NOT IN provides a shorthand version of a 'negative OR' request. The following is an example using the OR operator for the query example given above. Select the name and the department for all employees who are NOT members of departments 401 and 403. SELECT first_name ,last_name ,department_number FROM employee WHERE NOT (department_number=401 OR department_number=403); first_name last_name department_number ----------- ----------- --------------------- Carol Kanieski 301 John Stein 301 NULL The following are facts about nulls: NULL is used to represent the absence of a data value. NULL is not the same as having a value of zero or spaces. NULL indicates that a data value is missing or unknown. NULL in a comparison operation produces an unknown result. When doing an ascending sort on a column with NULL, NULLs sort before negative values (numeric) and before blank values (character). To prohibit NULLs, a column must be defined as NOT NULL. Null columns may be compressed to occupy zero row space. Arithmetic and Comparison Operation on NULL The following logic applies to operations on NULLs: Col A Operation Col B Results 10 + NULL NULL 10 - NULL NULL 10 * NULL NULL 10 / NULL NULL 10 > NULL UNKNOWN
  • 42. 10 < NULL UNKNOWN 10 >= NULL UNKNOWN 10 <= NULL UNKNOWN 10 = NULL UNKNOWN 10 <> NULL UNKNOWN NULL > NULL UNKNOWN NULL < NULL UNKNOWN NULL >= NULL UNKNOWN NULL <= NULL UNKNOWN NULL = NULL UNKNOWN NULL <> NULL UNKNOWN Using NULL in a Select Use NULL in a SELECT statement, to define that a range of values either IS NULL or IS NOT NULL. The following table lists two employees with unknown telephone extensions: To list employee numbers in this table with unknown extensions: SELECT employee_number FROM employee_phone WHERE extension IS NULL; employee_number -------------------- 1025 1005 To list employee numbers of people with known extensions:
  • 43. SELECT employee_number FROM employee_phone WHERE extension IS NOT NULL; employee_number -------------------- 1008 1013 LIKE Operator The LIKE operator searches for patterns matching character data strings. You must provide two parameters for the LIKE operator: a string expression to be searched and a string pattern for which to search. The string can contain specific characters, as well as the following "wildcards": % (indicates zero or more character positions) _ (indicates a single character position) Here are some examples using the LIKE operator: String pattern Meaning: example: LIKE 'JO%' begins with 'JO' LIKE '%JO%' contains 'JO' anywhere LIKE '__HN' contains 'HN' in 3rd and 4th position LIKE '%H_' contains 'H' in next to last position LIKE Operator -- Case-Blind Comparison Case-Sensitivity: ANSI vs. BTET session transaction mode Case-sensitivity of string comparisons is handled differently in the two different session transaction modes (ANSI or BTET). This can lead to different results for a comparison when run from sessions with different transaction modes. To ensure consistent behavior, either case-sensitive or case-blind compares, use the following: UPPER or LOWER operators for case-blind comparisons CASESPECIFIC operator for case-sensitive comparisons Case-Blind Compare The UPPER function converts a string to uppercase. Use the UPPER string function on both strings being compared to ensure a case-blind comparison regardless of the session transaction mode. The LOWER function may be similarly used.
  • 44. The NOT CASESPECIFIC data attribute can also be used to force case-blind compares, however it is not an ANSI-compliant operator. Problem Display the full name of employees whose last name contains the letter "r" followed by the letter "a". Teradata Mode Solution SELECT first_name ,last_name FROM employee WHERE last_name LIKE '%ra%'; first_name last_name ------------------------------ -------------------- James Trader Peter Rabbit I.B. Trainer Robert Crane Larry Ratzlaff Since we are in Teradata (BTET) mode, the default for comparisons is non-case- specific. Thus, we could have also used LIKE '%Ra%' or LIKE '%RA%' and produced the same result. ANSI Mode Solution SELECT first_name ,last_name FROM employee WHERE last_name LIKE '%ra%'; first_name last_name ------------------------------ -------------------- James Trader I.B. Trainer Robert Crane Since we are in ANSI mode, the default for comparisons is case-specific. Thus, we will not pick up Ratzlaff or Rabbit, unless we use 'case blind' testing, seen in the next example. SELECT first_name ,last_name FROM employee WHERE LOWER(last_name) LIKE LOWER('%ra%'); first_name last_name
  • 45. ------------------------------ -------------------- James Trader Peter Rabbit I.B. Trainer Robert Crane Larry Ratzlaff By applying the LOWER function to each side of the comparison, all testing is done in a 'case blind' mode. UPPER could have also been used. We could also have used LIKE '%ra%' (NOT CASESPECIFIC) to produce this result, however this is not an ANSI standard approach. LIKE Operator - Case-Sensitive Comparison Use the CASESPECIFIC data attribute on one or both of the string expressions being compared to ensure a case-sensitive comparison, regardless of the session transaction mode. CASESPECIFIC is a Teradata extension. Problem Display the full name of employees whose last name contains "Ra". This is a case- sensitive test. Teradata Mode Solution SELECT first_name ,last_name FROM employee WHERE last_name (CASESPECIFIC) LIKE '%Ra%'; first_name last_name ------------------------------ -------------------- Peter Rabbit Larry Ratzlaff The default comparison for Teradata mode is not case-specific. Use of the Teradata extension (CASESPECIFIC) forces a case-specific comparison. Because we used the case-specific designator, we don't get James Trader in our answer set but only get answers that contain an uppercase "R". The name 'LaRaye' would have also appeared in this answer set, if it existed in the table. Using LIKE 'Ra%' will return only names that begin with "Ra". ANSI Mode Solution SELECT first_name ,last_name FROM employee WHERE last_name LIKE '%Ra%'; first_name last_name ------------------------------ --------------------
  • 46. Peter Rabbit Larry Ratzlaff The default comparison for ANSI mode is case-specific. Use of the Teradata extension (CASESPECIFIC) is not required. This could have also been submitted with LIKE 'Ra%' and produced the same result, however it would have missed a name like 'LaRaye'. LIKE Operator -- Using Quantifiers To extend the pattern matching functions of the LIKE operator, use quantifiers. There are three such quantifiers: ANY — any single condition must be met (OR logic) SOME — same as ANY ALL — all conditions must be met (AND logic) ANY and SOME are synonyms. Using LIKE ANY and LIKE SOME will give the same result. Problem Display the full name of all employees with both "E" and "S" in their last name. Solution SELECT first_name ,last_name FROM employee WHERE last_name LIKE ALL ('%E%', '%S%'); first_name last_name ---------- ---------- John Stein Carol Kanieski Arnando Villegas
  • 47. Problem Display the full name of all employees with either an "E" or "S" in their last name. Solution SELECT first_name ,last_name FROM employee WHERE last_name LIKE ANY ('%E%', '%S%'); first_name last_name ----------- ----------- John Stein Carol Kanieski Arnando Villegas Darlene Johnson James Trader LIKE with ESCAPE Character The "_" and "%" symbols are used as 'wildcards' in the string expression of the LIKE construct. However, what if one of the wildcard symbols is in the expression you are evaluating. For example, to search for the substring "95%", you must define an ESCAPE character to instruct the Parser to treat the '%' as a non-wildcard character. To Summarize: The ESCAPE feature of LIKE lets wildcard characters be treated as non- wildcards. Characters following the escape character are not treated as wildcards. Problem List all objects defined in the Teradata Database Data Dictionary whose names contain "_" (underscore) as the second character. Solution SELECT tablename FROM dbc.tables WHERE tablename LIKE '_Z_%' ESCAPE 'Z'; TableName ------------------------------ M_7_B t_wt_erd1
  • 48. Things To Notice The defined escape character is the letter 'Z'. The first "_" (underscore) seen represents a wildcard - i.e., any single arbitrary character. The "Z_" sequence tells the Parser that the second "_" (underscore) is treated as a character, not as a wildcard. When you define an ESCAPE character, any use of the ESCAPE character in the string expression must be immediately followed by either the "_", "%", or the ESCAPE character itself. Assume the escape character is defined to be the letter 'G'. LIKE 'G_' means the underscore is treated as an underscore, not as a wildcard. LIKE 'G%' means the percent sign is treated as a percent sign, not as a wildcard. LIKE 'GG' means the two consecutive 'G' characters should be treated as a single 'G', not as an escape character. Example LIKE '%A%%AAA_' ESCAPE 'A' Searches for the following pattern: - any number of arbitrary characters, followed by - the "%" single character, followed by - any number of arbitrary characters, followed by - the "A" single character, followed by - the "_" single character, which is the last character in the string. Logical Operator -- AND Logical operators AND, OR and NOT allow you to specify complex conditional expressions by combining one or more logical expressions. Logical Operator AND The logical operator AND combines two expressions, both of which must be true in a given record for them to be included in the result set. Boolean Logic Table True AND True = True False AND True = False True AND False = False False AND False = False
  • 49. True OR True = True True OR False = True False OR True = True False OR False = False NOT True = False NOT false = True Problem Display the name and employee number of employees in department 403 who earn less than $35,000 per year. Solution SELECT first_name ,last_name ,employee_number FROM employee WHERE salary_amount < 35000.00 AND department_number = 403 ; first_name last_name employee_number ----------- ----------- -------------------- Loretta Ryan 1005 Logical Operator -- OR The logical operator OR combines two expressions. At least one must be true in a given record for it to be included in the result set. Problem Display the name and the employee number for employees who either earn less than $35,000 annually or work in department 403.
  • 50. Solution SELECT first_name ,last_name ,employee_number FROM employee WHERE salary_amount < 35000.00 OR department_number = 403; Result first_name last_name employee_number ---------- ---------- ---------------- Arnando Villegas 1007 Carol Kanieski 1008 Loretta Ryan 1005 John Stein 1006 Multiple AND . . . OR You want to find all employees in either department 401 or department 403 whose salaries are either under $35,000 or over $85,000. SELECT last_name ,salary_amount ,department_number FROM employee WHERE (salary_amount < 35000 OR salary_amount > 85000) AND (department_number = 401 OR department_number = 403) ; Logical Operators -- Combinations Operator Procedures Parentheses can be used to force an evaluation order. In the presence of parentheses, expressions are evaluated from the inner-most to outer-most set of parenthetical
  • 51. expressions. In the absence of parentheses, SQL uses the default precedence of the Boolean operators. By default, NOT has higher precedence than AND which has higher precedence than OR. Operators that have the same precedence level are evaluated from left to right (e.g., multiple ORs or multiple ANDs). If we remove the parentheses from the example above, our conditional expression gets evaluated in a totally different order. If we were to use it in a query, it would yield different results. NOT has the highest precedence of the three operators.
  • 52. Logical Operators -- Using Parentheses Problem Select the name, department number, and job code for employees in departments 401 or 403 who have job codes 412101 or 432101. Solution SELECT last_name ,department_number ,job_code FROM employee WHERE (department_number = 401 OR department_number = 403) AND (job_code = 412101 OR job_code = 432101) ; Result last_name department_number job_code ----------- --------------------- ---------- Villegas 403 432101 Johnson 401 412101 If we accidentally left the parentheses out of our statement, would we get the same results? SELECT last_name ,department_number ,job_code FROM employee WHERE department_number = 401 OR department_number = 403 AND job_code = 412101 OR job_code = 432101; last_name department_number job_code ---------- --------------------- --------- Villegas 403 432101
  • 53. Johnson 401 412101 Trader 401 411100 Question James Trader does not have either job code. Why was he selected? Answer Without parentheses, the default precedence causes the expression to be evaluated as follows: SELECT last_name ,department_number ,job_code FROM employee WHERE department_number = 401 OR (department-number = 403 AND job_code = 412101) OR job_code = 432101; Remember, if any of the expressions that OR combines are true, the result is true. Since James Trader is in department_number 401, that expression evaluates to true. Therefore the row qualifies for output. Multiple AND Use multiple ANDs if you need to locate rows which meet all of two or more sets of specific criteria. For example, what happens if we take the previous example, and replace all the ORs with ANDs? SELECT last_name ,department_number ,job_code FROM employee WHERE department_number = 401 AND department_number = 403 AND job_code = 412101 AND job_code = 432101; No rows will be found. Why? Answer For a row to be displayed in this answer set, an employee would have to be in department numbers 401 and 403. While we could conceive of an employee who works in two departments, the employee table has only one field for department number. There is no way that any row in this table can contain more than one department number. This query never will return any rows. A more realistic example follows.
  • 54. Problem Find all employees in department number 403 with job_code 432101 and a salary greater than $25,000. Solution SELECT last_name ,department_number ,job_code ,salary FROM employee WHERE department_number = 403 AND job_code = 432101 AND salary_amount > 25000.00 ; Result last_name department_number job_code salary_amount ----------- ---------------------- ---------- ---------------- Lombardo 403 432101 31000.00 Villegas 403 432101 49700.00 Charles 403 432101 39500.00 Hopkins 403 432101 37900.00 Brown 403 432101 43700.00 Logical NOT Place the NOT operator in front of a conditional expression or in front of a comparison operator if you need to locate rows which do not meet specific criteria. Problem Select the name and employee number of employees NOT in department 301. Solution for NOT Operator SELECT first_name ,last_name ,employee_number FROM employee WHERE department_number NOT = 301; Solution for NOT Condition SELECT first_name ,last_name
  • 55. ,employee_number FROM employee WHERE NOT (department_number = 301); Result (Note that both approaches return the same result.) first_name last_name employee_number ------------ ------------ -------------------- Arnando Villegas 1007 James Trader 1003 Loretta Ryan 1005 Darlene Johnson 1004 SQL Lab Databases Info Document: Your assigned user-id has SELECT access to the ‗Customer_Service‘ and the ‗Student‘ databases. These databases are used for labs during this SQL course. When selecting from tables, either set your default database to Customer_Service, Student, or your own user- assigned database (depending on the lab requirements) or alternatively, qualify your table names to reflect the appropriate database. The following pages include table definitions for the ‗Customer_Service‘ database and the ‗Student‘ database. You may want to print this document for reference throughout this course. ‗Customer_Service‘ Table Definitions CREATE SET TABLE agent_sales ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( agent_id INTEGER, sales_amt INTEGER) UNIQUE PRIMARY INDEX ( agent_id ); -- CREATE TABLE clob_files (Id INTEGER NOT NULL, text_file CLOB(10000)) UNIQUE PRIMARY INDEX ( Id ); -- CREATE TABLE contact, FALLBACK (contact_number INTEGER ,contact_name CHAR(30) NOT NULL ,area_code SMALLINT NOT NULL ,phone INTEGER NOT NULL ,extension INTEGER ,last_call_date DATE NOT NULL) UNIQUE PRIMARY INDEX (contact_number); -- CREATE TABLE customer, FALLBACK
  • 56. (customer_number INTEGER ,customer_name CHAR(30) NOT NULL ,parent_customer_number INTEGER ,sales_employee_number INTEGER ) UNIQUE PRIMARY INDEX (customer_number); -- CREATE SET TABLE daily_sales ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( itemid INTEGER, salesdate DATE FORMAT 'YY/MM/DD', sales DECIMAL(9,2)) PRIMARY INDEX ( itemid ); -- CREATE SET TABLE daily_sales_2004 ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( itemid INTEGER, salesdate DATE FORMAT 'YY/MM/DD', sales DECIMAL(9,2)) PRIMARY INDEX ( itemid ); -- CREATE TABLE department, FALLBACK (department_number SMALLINT ,department_name CHAR(30) NOT NULL ,budget_amount DECIMAL(10,2) ,manager_employee_number INTEGER ) UNIQUE PRIMARY INDEX (department_number) ,UNIQUE INDEX (department_name); -- CREATE TABLE employee, FALLBACK (employee_number INTEGER ,manager_employee_number INTEGER ,department_number INTEGER ,job_code INTEGER ,last_name CHAR(20) NOT NULL ,first_name VARCHAR(30) NOT NULL ,hire_date DATE NOT NULL ,birthdate DATE NOT NULL ,salary_amount DECIMAL(10,2) NOT NULL ) UNIQUE PRIMARY INDEX (employee_number); -- CREATE TABLE employee_phone, FALLBACK (employee_number INTEGER NOT NULL
  • 57. ,area_code SMALLINT NOT NULL ,phone INTEGER NOT NULL ,extension INTEGER ,comment_line CHAR(72) ) PRIMARY INDEX (employee_number); -- CREATE SET TABLE Jan_sales ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( itemid INTEGER, salesdate DATE FORMAT 'YY/MM/DD', sales DECIMAL(9,2)) PRIMARY INDEX ( itemid ); -- CREATE TABLE job, FALLBACK (job_code INTEGER ,description VARCHAR(40) NOT NULL ,hourly_billing_rate DECIMAL(6,2) ,hourly_cost_rate DECIMAL(6,2) ) UNIQUE PRIMARY INDEX (job_code) ,UNIQUE INDEX (description); -- CREATE TABLE location, FALLBACK (location_number INTEGER ,customer_number INTEGER NOT NULL ,first_address_line CHAR(30) NOT NULL ,city VARCHAR(30) NOT NULL ,state CHAR(15) NOT NULL ,zip_code INTEGER NOT NULL ,second_address_line CHAR(30) ,third_address_line CHAR(30) ) PRIMARY INDEX (customer_number); -- CREATE TABLE location_employee, FALLBACK (location_number INTEGER NOT NULL ,employee_number INTEGER NOT NULL ) PRIMARY INDEX (employee_number); -- CREATE TABLE location_phone, FALLBACK (location_number INTEGER ,area_code SMALLINT NOT NULL ,phone INTEGER NOT NULL ,extension INTEGER ,description VARCHAR(40) NOT NULL ,comment_line LONG VARCHAR )
  • 58. PRIMARY INDEX (location_number); -- CREATE TABLE phonelist ( LastName CHAR(20), FirstName CHAR(20), Number CHAR(12) NOT NULL, Photo BLOB(10000)) UNIQUE PRIMARY INDEX ( Number ); -- CREATE TABLE repair_time ( serial_number INTEGER ,product_desc CHAR(8) ,start_time TIMESTAMP(0) ,end_time TIMESTAMP(0)) UNIQUE PRIMARY INDEX (serial_number); -- CREATE SET TABLE salestbl ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( storeid INTEGER, prodid CHAR(1), sales DECIMAL(9,2)) PRIMARY INDEX ( storeid ); ‗Student‘ Database Table Definitions CREATE TABLE city ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( cityname CHAR(15) NOT CASESPECIFIC, citystate CHAR(2) NOT CASESPECIFIC, citypop INTEGER) PRIMARY INDEX ( cityname ); CREATE TABLE customers ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( cust_id integer not null ,cust_name char(15) ,cust_addr char(25) compress) PRIMARY INDEX ( cust_id);
  • 59. CREATE TABLE orders ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( order_id INTEGER NOT NULL ,order_date DATE FORMAT 'YYYY-MM-DD' ,cust_id INTEGER ,order_status CHAR(1)) UNIQUE PRIMARY INDEX ( order_id ); CREATE TABLE state ,NO FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL ( stateid CHAR(2) NOT CASESPECIFIC NOT NULL, statename CHAR(15) NOT CASESPECIFIC, statepop INTEGER NOT NULL, statecapitol CHAR(15) NOT CASESPECIFIC) PRIMARY INDEX ( stateid ); Lab For this set of lab questions you will need information from the Database Info document. To start the online labs, click on the Telnet button in the lower left hand screen of the course. Two windows will pop-up: a BTEQ Instruction Screen and your Telnet Window. Sometimes the BTEQ Instructions get hidden behind the Telnet Window. You will need these instructions to log on to Teradata. Be sure to change your default database to the Customer_Service database in order to run these labs. A. Management needs a list with employee number, last name, salary and job code of all employees earning between $40,001 and $50,000. Produce this report using the comparison operators and sort by last name. Modify the query to use the BETWEEN operator and sort by salary descending. B. Management requests a report of all employees in departments 501, 301, and 201 who earn more than $30,000. Show employee number, department number, and salary. Sort by department number and salary amount within department. C. Display location number, area code, phone number, extension, and description from the location_phone table if the description contains the string ‘manager'. Sort by location number. D. List customers from the customer table identified by: 1. An unknown parent customer number; and 2. A known sales employee number.
  • 60. Display all columns except parent customer number. Order results by customer number. E. Create a report that lists all location numbers in area code 415 not dedicated to any manager. Include all columns except comment and extension. Sequence by phone number. F. List all job codes in the 400000 series that are management and all Analyst positions regardless of job code value. List job code and description for the selected rows. Sort by description. Submit again using EXPLAIN to look at how the Teradata RDBMS handled this request. G. List the location numbers in area codes 415 or 617 which have no phone extensions. Order by area code and phone number. Include all columns of the table except for description and comment line columns. Notice how NULLs appear in your output. Lab Answer A DATABASE Customer_Service; SELECT employee_number ,last_name ,salary_amount ,job_code FROM employee WHERE salary_amount >= 40001 AND salary_amount <= 50000 ORDER BY last_name ; *** Query completed. 4 rows found. 4 columns returned. employee_number last_name salary_amount job_code 1024 Brown 43700.00 432101 1002 Brown 43100.00 413201 1010 Rogers 46000.00 412101 1007 Villegas 49700.00 432101 SELECT employee_number ,last_name ,salary_amount ,job_code FROM employee WHERE salary_amount BETWEEN 40001 AND 50000 ORDER BY salary_amount DESC ; *** Query completed. 4 rows found. 4 columns returned. employee_number last_name salary_amount job_code 1007 Villegas 49700.00 432101
  • 61. 1010 Rogers 46000.00 412101 1024 Brown 43700.00 432101 1002 Brown 43100.00 413201 Lab Answer B SELECT employee_number ,department_number ,salary_amount FROM employee WHERE salary_amount > 30000 AND department_number IN (501,301,201) ORDER BY department_number ,salary_amount ; *** Query completed. 6 rows found. 3 columns returned. employee_number department_number salary_amount 1025 201 34700.00 1021 201 38750.00 1019 301 57700.00 1015 501 53625.00 1018 501 54000.00 1017 501 66000.00 Lab Answer C SELECT location_number ,area_code ,phone ,extension ,description FROM location_phone WHERE description LIKE '%Manager%' ORDER BY location_number ; *** Query completed. 5 rows found. 5 columns returned. location_number area_code phone extension description 5000001 415 4491225 ? System Manager 14000020 312 5692136 ? System Manager
  • 62. 22000013 617 7562918 ? System Manager 31000004 609 5591011 224 System Manager 33000003 212 7232121 ? System Manager Lab Answer D SELECT customer_number ,customer_name ,sales_employee_number FROM customer WHERE parent_customer_number IS NULL AND sales_employee_number IS NOT NULL ORDER BY 1 ; *** Query completed. 14 rows found. 3 columns returned. customer_number customer_name sales_employee_number -------------- ---------------------------- - ---------------------- 1 A to Z Communications, Inc. 1015 3 First American Bank 1023 5 Federal Bureau of Rules 1018 6 Liberty Tours 1023 7 Cream of the Crop 1018 8 Colby Co. 1018 9 More Data Enterprise 1023 10 Graduates Job Service 1015 11 Hotel California 1015 12 Cheap Rentals 1018 14 Metro Savings 1018 15 Cates Modeling 1015 17 East Coast Dating Service 1023 18 Wall Street Connection 1023 Lab Answer E
  • 63. SELECT location_number ,area_code ,phone ,description FROM location_phone WHERE area_code = 415 AND description NOT LIKE '%Manager%' ORDER BY phone ; *** Query completed. 6 rows found. 4 columns returned. location_number area_code phone description --------------- --------- ----------- ------------- 5000010 415 2412021 Alice Hamm 5000011 415 3563560 J.R. Stern 5000001 415 4491221 FEs office 5000001 415 4491244 Secretary 5000019 415 6567000 Receptionist 5000002 415 9237892 Receptionist Lab Answer F
  • 64. SELECT job_code ,description FROM job WHERE (job_code BETWEEN 400000 AND 499999 AND description LIKE '%manager%') OR (description LIKE '%analyst%') ORDER BY description ; *** Query completed. 6 rows found. 2 columns returned. job_code description ----------- ----------------------------- 411100 Manager - Customer Support 431100 Manager - Education 421100 Manager - Software Support 422101 Software Analyst 222101 System Analyst 412103 System Support Analyst Note: EXPLAIN text varies depending on optimizer path. Lab Answer G
  • 65. SELECT location_number ,area_code ,phone ,extension FROM location_phone WHERE extension IS NULL AND area_code IN (415,617) ORDER BY area_code ,phone ; *** Query completed. 9 rows found. 4 columns returned. location_number area_code phone extension --------------- --------- ----------- ----------- 5000010 415 2412021 ? 5000011 415 3563560 ? 5000001 415 4491221 ? 5000001 415 4491225 ? 5000001 415 4491244 ? 5000019 415 6567000 ? 5000002 415 9237892 ? 22000013 617 7562918 ? 22000013 617 7567676 ? Data Types and Conversions Module:- 6 Objectives After completing this module, you should be able to: Define the data type for a column in a table. Compute values using arithmetic functions and operators. Convert data from one type to another. Manipulate the DATE data type. Data Types Every column in a row is associated with a data type that defines the kind of values it accepts. These data types are associated with the fields when the table is created. Data types fall into one of the four categories shown below: Data Type Holds Character data Character Strings Byte data Binary Data Strings
  • 66. Numeric data Numbers Dates,Times,Timestamps,Time Intervals (Note: Time, Timestamps and Intervals Date/Time data are covered in the Teradata SQL Advanced course) Character Data There are two data types for holding character data: CHAR - has fixed-length character strings. VARCHAR - has variable-length character strings. In both cases, the maximum string length is 64,000 characters. String size is specified in parentheses after the keyword CHAR or VARCHAR as in CHAR(20) or VARCHAR(20). There are subtle differences between the two. In the case of CHAR, if you insert a character string less than the specified size (20 in the above example), the system will append and store trailing blanks as needed to expand the string to the specified length. The size specified on a VARCHAR field represents a maximum length. The system will not pad the contents with trailing blanks. (It will use two extra bytes to store the length internally however.) When you know that data will always be a specific length (e.g., a Mail Stop that is a four-character length) use CHAR. You save the two bytes that VARCHAR would use to store the length. When data does not have a fixed length (e.g., last names), VARCHAR makes more efficient use of the space, because it does not pad values with trailing blanks. Character Data Description Example CHAR (size) Fixed length string last_name CHAR(20) Max: 64,000 characters Sample contents: 'Ryan__________' VARCHAR (size) Variable length string first_name VARCHAR(30) CHAR VARYING (size) Max: 64,000 characters CHARACTER VARYING Sample contents: (size) 'Loretta' LONG VARCHAR Equivalent to VARCHAR (64000) Note: VARCHAR(size), CHAR VARYING(size), and CHARACTER VARYING(size) are all equivalent synonyms. LONG VARCHAR is equivalent to a maximum VARCHAR.
  • 67. Character strings may be defined using any one of the following character sets: Character Set Max Length Latin 64,000 (English language default) Kanji1 64,000 KanjiSJIS 64,000 Unicode 32,000 (two bytes per character) Graphic 32,000 (two bytes per character) Examples first_name VARCHAR(30) CHARACTER SET LATIN image_abc CHAR(32000) CHARACTER SET GRAPHIC Byte Data Teradata supports two data types for holding binary data: BYTE. VARBYTE. BYTE is for fixed length binary strings. VARBYTE is for variable length binary strings. These data types are used for storing binary objects such as digital images, executable objects, flat files, etc. Byte Data Description BYTE (size) Fixed length Binary string Default: (1) Max: 64,000 bytes VARBYTE (size) Variable length Binary string Default: (1) Max: 64,000 bytes Note: BYTE columns are not covertible to other data types. Numeric Data
  • 68. The following numeric data types are available: Data Type Description Examples BYTEINT* Whole number basket_count Range -128 to 127 BYTEINT Storage: 1 byte +125 SMALLINT Whole number area_code Range: -32,768 to 32,767 SMALLINT Storage: 2 bytes +00213 (up to 5 digits) INTEGER Whole number phone Range: -2,147,483,648 to INTEGER 2,147,483,647 +0006495252 (up to 10 digits) Storage: 4 bytes BIGINT Whole number international_phone Range ± BIGINT 9,233,372,036,854,775,80 +0000010807934842145 (up to 19 digits) 7 Storage: 8 bytes DEC(m, n) 'm' is total number of digits. salary_amount DECIMAL(m,n) (m <= 18) DEC (10,2) NUMERIC(m,n 'n' is precision places to the +00035000.00 ) right of decimal point. (Small Decimal) Max Size =18 digits Storage: 2 to 8 bytes DEC(m, n) 'm' is total number of digits. sheet_thickness DECIMAL(m,n) (18 < m <= 38) DEC (32,30) NUMERIC(m,n 'n' is precision places to the +01.12349878279278758297727849782 ) right of decimal point. 7 (Large Decimal) Max Size = 38 digits Storage: 16 bytes FLOAT Floating Point Format salary_factor (IEEE) FLOAT 2x10-307 to 2x10+308 4.35400000000000E-001 Storage: 8 bytes FLOAT Internally represented [(precision)] as FLOAT REAL Internally represented as FLOAT DOUBLE Internally represented PRECISION as FLOAT * Non-ANSI standard data type Date Data
  • 69. DATE represents a calendar date. It simplifies handling and formatting dates common to business applications. DATE is stored as an integer, using the following formula: (year - 1900) * 10000 + (month * 100) + day. The DATE data type, shown here, is used in several forthcoming examples. Data Type Description Examples DATE Specially formatted integer: hire_date DATE YYMMDD thru 1999 +0000990921 YYYMMDD from 2000 onward +0001000215 In the first example, the date being represented is September 21, 1999. In the second example, the date being represented is February 15, 2000. Note that the year is represented as an offset from the year 1900 in both cases. Note, this is how the date is stored internally. How you see the date in a report depends on how the date is formatted. The recommended display format for DATE values is ‗YYYY-MM-DD‘. This format will avoid problems that may occur from formats specifying only two digits for the year. This is a significant issue as dates for the year 2000 and beyond are now commonly entered. Example 2006-03-14 formatted as ‘YY-MM-DD’ displays ad 01-03-14, which is also the representation for 1901-03-14. 2006-03-14 formatted as ‘YYYY-MM-DD’ displays as 2006-03-14, which is unambiguous. Note: Formatting techniques for dates are discussed in the forthcoming module 'Output Attributes'. Arithmetic Operators Teradata provides six binary arithmetic operators and two unary arithmetic operators. They are defined in the tables below: Binary Operators (require two operands) Operator Definition ** exponentiation * Multiply / Divide MOD Modulos (remainders) + Add - Subtract