undefinedIntroduction to Teradata SQL (Module 1)ObjectivesAfter 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 thetable represent instances of an entity, in this case an employee or a department. Columnsrepresent the data fields which comprise the rows. Relations between tables occur when acolumn 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 withRelational 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 TeradataDatabase.SQL is a non-procedural language, meaning it contains no procedural-type statements such asthose listed here: GO TO PERFORM DO LOOP OPEN FILE
CLOSE FILE END OF FILESQL CommandsSQL 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)ObjectivesAfter 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.SELECTStructured Query Language (SQL) consists of three types of statements, previously definedas:Data Definition Language (DDL) - Used to create, drop and modify objectsData Manipulation Language(DML) - Used to add, delete, update and read data rows in a tableData 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 theSELECT 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 employeeWHERE department_number = 401;The asterisk, "*", indicates that we wish to see all of the columns in the table. The FROM clausespecifies from which table in our database to retrieve the rows. The WHERE clause acts as a filterwhich returns only rows that meet the specified condition, in this case, records of employees indepartment 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 willinclude 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 columnsseparated by commas:SELECT employee_number ,hire_date ,last_name ,first_nameFROM employeeWHERE department_number = 401;employee_number hire_date last_name first_name-------------------- ---------- ----------- -----------1004 76/10/15 Johnson Darlene1003 76/07/31 Trader James1013 77/04/01 Phillips Charles1010 77/03/01 Rogers Frank1022 79/03/01 Machado Albert1001 76/06/18 Hoover William1002 76/07/31 Brown AlanUnsorted ResultsResults come back unsorted unless you specify that you want them sorted in a certain way. Howto retrieve ordered results is covered in the next section.ORDER BY ClauseUse the ORDER BY clause to have your results displayed in a sorted order. Without the ORDERBY clause, resulting output rows are displayed in a random sequence.SELECT employee_number ,last_name ,first_name ,hire_dateFROM employeeWHERE department_number = 401ORDER BY hire_date;Sort DirectionIn the example above, results will be returned in ascending order by hire date. Ascending orderis 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 anexample of a sort using descending sequence.ORDER BY hire_date DESC;Naming the Sort ColumnYou may indicate the sort column by naming it directly (e.g., hire_date) or by specifying itsposition within the SELECT statement. Since hire_date is the fourth column in the SELECTstatement, the following ORDER BY clause is equivalent to saying ORDER BY hire_date.ORDER BY 4;Multiple ORDER BY ColumnsAn ORDER BY clause may specify multiple columns. No single column in an ORDER BY clauseshould 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 namedfirst is the major sort column. The second and subsequent are minor sort columns. In thefollowing example, results are sorted by department number in ascending order. Wheremultiple records share the same department number, those rows are sorted by job_code inascending order. The following are examples:SELECT employee_number ,department_number ,job_codeFROM employeeWHERE department_number < 302ORDER 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 312102Note: Each column specified in the ORDER BY clause can have its own sort order, eitherascending or descending.SELECT employee_number ,department_number ,job_codeFROM employeeWHERE department_number < 302ORDER 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 311100DISTINCTThe DISTINCT operator will consolidate duplicate output rows to a single occurrence.Example Without DISTINCTSELECT department_number ,job_codeFROM employeeWHERE department_number = 501; department_number job_code ---------------------- ---------- 501 512101 501 512101 501 511100Note: Two people in department 501 have the same job code (512101). If our purpose issimply to find out which job codes exist in department 501, we could use DISTINCT to avoidseeing duplicate rows.Example With DISTINCTSELECT DISTINCT department_number ,job_codeFROM employeeWHERE department_number = 501; department_number job_code ---------------------- ---------- 501 511100 501 512101Note: DISTINCT appears directly after SELECT, and before the first named column. It mayappear to apply only to the first column, but in fact, DISTINCT applies to all columns named inthe query. Two rows in our result example set both have department_number 501. Thecombination of department_number and job_code are distinct since the job codes differ.Naming Database ObjectsAll 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:AccountsAccounts_2005accounts_over_$2000Account#EquivalenceAccounts and accounts represent the same table. Case is not considered.Naming RulesNaming 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.ColumnnameExample 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 ConventionsSQL is considered a free form language, that is, it can cover multiple lines of code and thereis no restriction on how much white space (i.e., blanks, tabs, carriage returns) may beembedded 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 PracticeSELECT last_name ,first_name ,hire_date ,salary_amountFROM employeeWHERE department_number = 401ORDER BY last_name;Not Recommended Practiceselect last_name, first_name, hire_date, salary_amountfrom employee where department_number = 401 order by last_name;The first example is easy to read and troubleshoot (if necessary). The second exampleappears to be a jumble of words. Both, however, are valid SQL statements.Default DatabaseSetting the Default DatabaseAs a valid user, you will normally have access rights to your own user database and theobjects 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 youwere created as a user.)
For example, if you log on as: .logon rayc; password: xyzthen "rayc" is normally your default database.Note the dot (.) before "logon". Commands that begin with a dot are BTEQ commands, notSQL commands. The BTEQ command processor will read this command; the SQL processorwill not see it.Queries you make that do not specify the database name will be made against your defaultdatabase.Changing the Default DatabaseThe 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 areheld) are made against the payroll database.LabFor 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 asyou 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 1019s 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 801s employees instead of manager 1019s. D. Prepare a report of the department numbers and the managers 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 usingBTEQ scripts for the Labs in Module 3.Simple BTEQ (Module 3)
ObjectivesAfter 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 Queryprogram.BTEQ is client software that resides on your network or channel-attached host. After startingBTEQ, you will log on to Teradata using a TDP-id (Teradata Director Program id), your userid and password. The TDP-id identifies the instance of Teradata you are going to access.TDPs 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) whichvalidates your request and passes it to the Access Module Processors (AMPs). AMPs retrievethe answer sets from the disks and send the response set back to the PE which in turnforwards 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 attachedclients. It operates under all host systems and local area networks (LANs).BTEQ CommandsFacts 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, simplytyping in the command bteq is required.For purposes of this course, instructions for starting a lab session are contained on each labpage.Using BTEQ Interactively
Submitting SQL Statements with BTEQThere 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 ParametersSession 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 activatesdifferent case-sensitivity and data conversion defaults, and so the same query might returndifferent results in each mode.For purposes of this course, Teradata-mode sessions will be assumed unless otherwisespecified. 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 compliantsyntax with a warning but still returns the expected answer set.Example.SET SESSION SQLFLAG ENTRY; /* Causes non-Entry level ANSI syntax to beflagged */SELECT DATE; /* Causes a warning because keyword DATE is not ANSIstandard*/*** 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/12Note: In both cases, the date was returned.You need to establish your session parameters prior to logging on. Teradata extensionscannot be disabled, but they can be flagged using the ANSI flagger.The SHOW CONTROL CommandThe BTEQ .SHOW CONTROL command displays BTEQ settings. The following output showsthe 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 = 75BTEQ ScriptsA BTEQ script is a file that contains BTEQ commands and SQL statements. A script is builtfor sequences of commands that are to be executed on more than one occasion, i.e.monthly, weekly, daily.How to create a BTEQ ScriptTo create and edit a BTEQ script, use an editor on your client workstation. For example, ona UNIX workstation, use either the vi or text editor.How to Submit a BTEQ ScriptStart BTEQ, then enter the following BTEQ command to submit a BTEQ script: .run file = <scriptname>BTEQ Comments -- Teradata ExtensionsThe 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 ExampleLets look at an example of a BTEQ script using ANSI standard comments. The ANSIcomment 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; .QUITNote: Both Teradata style (/* */) and ANSI style (--) comments may be included in anySQL 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$ bteqTeradata 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.scrTeradata 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_nameFROM 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# exitUsing BTEQ in BATCH ModeIf you prefer to write all SQL statements in a single script file, there are two ways youmay 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 OutputFrom a UNIX workstation, use the script <filename> command to capture the output ofyour 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 outputto both the screen and the designated <filename> if one has been designated.How to Stop Capturing BTEQ Session OutputFrom a UNIX workstation, issue the following UNIX command to stop the scriptcommand: $exitThis closes the logging file but does not terminate the UNIX session.Identifying Syntax ErrorsBTEQ output results will display a "$" to indicate the location where the error wasdetected in either the script or request. The following is an example of captured outputshowing 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 bedeleted. 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# exitscript done on Thu Oct 24 16:21:39 1996The dollar sign points to the command DISTINCT. The error text tells us that DISTINCTshould be deleted. The DISTINCT command must directly follow the SELECT command inyour request.LabFor 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 thecourse. 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 inorder 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 youve 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.ADATABASE 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 ? 1099Note: Order is random. And user input is highlighted in redLab 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_amountDaly 402 52500.00Kubic 301 57700.00Rogers 302 56500.00Runyon 501 66000.00Ryan 403 31200.00Short 201 34700.00Trader 401 37850.00Trainer 100 100000.00Lab Answer B
Lab Answer CNote: Actual warning messages generated will vary depending on how you havewritten 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 orKeyword.department_number department_name budget_amountmanager_employ----------------- ----------------------- ------------- -------------- 100 president 400000.00801 401 customer support 982300.001003 403 education 932000.001005 402 software support 308000.001011 302 product planning 226000.001016 501 marketing sales 308000.001017 301 research and development 465600.001019 201 technical operations 293800.001025 600 None ?1099The warning message is generated because the ANSI flagger is enabledand 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 4ObjectivesAfter 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 ExtensionsSeveral commands in our software are Teradata-specific. Here is a list of Teradataextensions covered within this course.ADD_MONTHS BEGIN/ END TRANSACTIONCOLLECT/ DROP COMMENT ONSTATISTICSCONCATENATION EXPLAINFALLBACK FORMAT
HELP INDEXLOCKING MACRO Facility • CREATE • REPLACE • DROP • EXECUTENAMED NULLIFZERO/ZEROIFNULLSHOW SUBSTRTITLE TRIMWITH WITH . . . BYIn this module, we focus on the following functions: EXPLAIN HELP SHOWHELP Commands: Database objectsThe HELP Command is used to display information about database objects such as (butnot limited to): Databases and Users Tables Views MacrosHELP retrieves information about these objects from the Data Dictionary. Below are thesyntactical options for various forms of the HELP command:HELP CommandHELP 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 CommandThe HELP DATABASE command in the following example shows all objects in theCustomer_Service database. Objects may be recognized by their Kind designation asfollows: 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 CommentNamecontact 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 thatno user comments have been entered.Note: To return HELP information on an object, a user must either own the object orhave at least one privilege on it.
The HELP TABLE CommandThe HELP TABLE command shows the name, data type, and comment (if applicable), ofall columns in the specified table: HELP TABLE Customer_Service.employeeColumnName Type Commentemployee_number I System assigned identificationmanager_employee_number I ?department_number I Department employee works injob_code I Job classification designationlast_name CF Employee surnamefirst_name CV Employee given namehire_date DA Date employee was hiredbirthdate DA ?salary_amount D Annual compensation amountData types are as follows:Type Description Type DescriptionCF CHARACTER FIXED F FLOATCV CHARACTER VARIABLE BF BYTED DECIMAL BV VARBYTEDA DATE AT TIMEI INTEGER TS TIMESTAMPI1 BYTEINTI2 SMALLINTHELP Commands: Session CharacteristicsUse 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 NoneTo produce the formatting shown above use: .SET FOLDLINE ON .SET SIDETITLES ONThe SHOW CommandThe SHOW command displays the current Data Definition Language (DDL) of adatabase 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 CommandsCommand Returns CREATE TABLESHOW TABLE tablename; statement CREATE VIEWSHOW VIEW viewname; statement CREATE MACROSHOW MACRO macroname; statementBTEQ also has a SHOW command (.SHOW CONTROL) which is different from the SQLSHOW command. It provides information on formatting and display settings for thecurrent BTEQ session.The SHOW TABLE Command
The SHOW TABLE command seen here returns the CREATE TABLE statement that wasused to create the employee table. To perform a SHOW TABLE, the user must have aprivilege 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 commandwill always reflect the most current alterations.The SHOW VIEW CommandThe SHOW VIEW command shows you the CREATE VIEW statement used to create aview: SHOW VIEW dept;ResultCREATE VIEW dept(dept_num,dept_name,budget,manager)ASSELECTdepartment_number,department_name,budget_amount,manager_employee_numberFROM CUSTOMER_SERVICE.department;The view may be accessed instead of the table: SELECT * FROM dept;Resultdept_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 1025The SHOW Macro CommandThe SHOW MACRO command shows you the statement used to create a macro:SHOW MACRO get_depts;ResultCREATE MACRO get_deptsAS (SELECT department_number ,department_name ,budget_amount ,manager_employee_numberFROM department;);The EXPLAIN CommandThe EXPLAIN function looks at a SQL request and responds in English how theoptimizer plans to execute it. It does not actually execute the SQL statement howeverit is a good way to see what database resources will be used in processing yourrequest.For instance, if you see that your request will force a full-table scan on a very largetable or cause a Cartesian Product Join, you may decide to re-write a request so that itexecutes 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.LabFor this set of lab questions you will need information from the Database Infodocument.To start the online labs, click on the Telnet button in the lower left hand screen of thecourse. Two windows will pop-up: a BTEQ Instruction Screen and your TelnetWindow. 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, youll 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 AHELP DATABASE cs_views;*** Help information returned. 15 rows found.Table/View/Macro name Kind Commentagent_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 Commentagent_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 BHELP 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 CSHOW VIEW cs_views.emp;*** Text of DDL statement returned.CREATE VIEW emp (emp ,mgr ,dept ,job ,last ,first ,hire ,birth ,sal)ASSELECT employee_number ,manager_employee_number ,department_number ,job_code ,last_name ,first_name ,hire_date ,birthdate
,salary_amountFROM CUSTOMER_SERVICE.employee;Lab Answer DEXPLAIN SELECT * FROM customer_service.department ORDER BYdepartment_name ;*** Help information returned. 11 rows found. Explanation1. First, we lock a distinct customer_service."pseudo table" forread on a RowHash to prevent global deadlock forcustomer_service.department.2. Next, we lock customer_service.department for read.3. We do an all-AMPs RETRIEVE step fromcustomer_service.department by way of an all-rows scan with noresidual conditions into Spool 1, which is built locally on theAMPs. Then we do a SORT to order Spool 1 by the sort key inspool field1. The size of Spool 1 is estimated with lowconfidence to be 12 rows. The estimated time for this step is0.15 seconds.4. Finally, we send out an END TRANSACTION step to all AMPsinvolved in processing the request.-> The contents of Spool 1 are sent back to the user as theresult of statement 1. The total estimated time is 0.15 seconds.Lab Answer ESHOW 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 NOTCASESPECIFIC)
PRIMARY INDEX( employee_number );Lab Answer FHELP INDEX Customer_Service.customer;*** Help information returned. One row. Primary orUnique Secondary Column NamesY P customer_number.SET SIDETITLES ON.SET FOLDLINE ONHELP 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:00Default 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 OFFLab Answer GDATABASE Customer_Service;SELECT * FROM emp;
(Fails because the emp view is not in database customer_service. Tomake 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 5ObjectivesAfter 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 OperatorsOperators are symbols or words that cause an operation to occur on one or moreelements called operands.Logical expressions combine operands and operators to produce a Boolean(true/false) result. Logical expressions can be combined into conditionalexpressions 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 operatorThe EXISTS operator is covered in the Teradata Advanced SQL course.BETWEEN -- Numeric Range TestingTo locate rows for which a numeric column is within a range of values, use theBETWEEN <a> AND <b> operator. Specify the upper and lower range of values thatqualify the row.The BETWEEN operator looks for values between the given lower limit <a> andgiven upper limit <b> as well as any values that equal either <a> or <b> (i.e.,BETWEEN is inclusive.)ExampleSelect the name and the employees manager number for all employees whose jobcodes 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 801Armando Villegas 1005BETWEEN -- Character Range TestingUse the BETWEEN <a> AND <b> operator to locate rows for which a character columnis within a range of values. Specify the upper and lower range of values that qualifythe row. BETWEEN will select those values which are greater than or equal to <a> andless or equal to <b>. (BETWEEN is inclusive.)SELECT last_nameFROM employeeWHERE last_name BETWEEN r AND s;last_name------------RyanNote: Stein is not included because S_____ sorts lower than Stein. (Teradata isnot case-sensitive by default.)Set Operator INUse the IN operator as shorthand when multiple values are to be tested. Select thename and department for all employees in either department 401 or 403. This querymay 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 401Loretta Ryan 403Armando Villegas 403James Trader 401Set Operator NOT INUse the NOT IN operator to locate rows for which a column does not match any of aset 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 301John Stein 301
NOT IN vs. ORNOT IN provides a shorthand version of a negative OR request. The following is anexample using the OR operator for the query example given above.Select the name and the department for all employees who are NOT members ofdepartments 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 301John Stein 301NULLThe 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 NULLThe 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 UNKNOWNUsing NULL in a SelectUse NULL in a SELECT statement, to define that a range of values either IS NULL or ISNOT 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--------------------10251005To list employee numbers of people with known extensions:
SELECT employee_number FROM employee_phone WHERE extension IS NOT NULL;employee_number--------------------10081013LIKE OperatorThe LIKE operator searches for patterns matching character data strings.You must provide two parameters for the LIKE operator: a string expression to be searchedand 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 JOLIKE %JO% contains JO anywhereLIKE __HN contains HN in 3rd and 4th positionLIKE %H_ contains H in next to last positionLIKE Operator -- Case-Blind ComparisonCase-Sensitivity: ANSI vs. BTET session transaction modeCase-sensitivity of string comparisons is handled differently in the two different sessiontransaction modes (ANSI or BTET). This can lead to different results for a comparisonwhen run from sessions with different transaction modes. To ensure consistentbehavior, either case-sensitive or case-blind compares, use the following:UPPER or LOWER operators for case-blind comparisonsCASESPECIFIC operator for case-sensitive comparisonsCase-Blind CompareThe UPPER function converts a string to uppercase. Use the UPPER string function onboth strings being compared to ensure a case-blind comparison regardless of thesession transaction mode. The LOWER function may be similarly used.
The NOT CASESPECIFIC data attribute can also be used to force case-blindcompares, however it is not an ANSI-compliant operator.ProblemDisplay the full name of employees whose last name contains the letter "r" followed bythe letter "a".Teradata Mode Solution SELECT first_name ,last_name FROM employee WHERE last_name LIKE %ra%;first_name last_name------------------------------ --------------------James TraderPeter RabbitI.B. TrainerRobert CraneLarry RatzlaffSince 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% andproduced the same result.ANSI Mode SolutionSELECT first_name ,last_nameFROM employeeWHERE last_name LIKE %ra%;first_name last_name------------------------------ --------------------James TraderI.B. TrainerRobert CraneSince we are in ANSI mode, the default for comparisons is case-specific. Thus, we willnot pick up Ratzlaff or Rabbit, unless we use case blind testing, seen in the nextexample.SELECT first_name ,last_nameFROM employeeWHERE LOWER(last_name) LIKE LOWER(%ra%);first_name last_name
------------------------------ --------------------James TraderPeter RabbitI.B. TrainerRobert CraneLarry RatzlaffBy applying the LOWER function to each side of the comparison, all testing is done ina 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 ANSIstandard approach.LIKE Operator - Case-Sensitive ComparisonUse the CASESPECIFIC data attribute on one or both of the string expressions beingcompared to ensure a case-sensitive comparison, regardless of the session transactionmode. CASESPECIFIC is a Teradata extension.ProblemDisplay 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 RabbitLarry RatzlaffThe 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 dont get James Trader in our answerset but only get answers that contain an uppercase "R". The name LaRaye would havealso appeared in this answer set, if it existed in the table. Using LIKE Ra% will returnonly 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 RabbitLarry RatzlaffThe default comparison for ANSI mode is case-specific.Use of the Teradata extension (CASESPECIFIC) is not required. This could have alsobeen submitted with LIKE Ra% and produced the same result, however it would havemissed a name like LaRaye.LIKE Operator -- Using QuantifiersTo 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 ANYALL — all conditions must be met (AND logic)ANY and SOME are synonyms. Using LIKE ANY and LIKE SOME will give the same result.ProblemDisplay 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 SteinCarol KanieskiArnando Villegas
ProblemDisplay 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 SteinCarol KanieskiArnando VillegasDarlene JohnsonJames TraderLIKE with ESCAPE CharacterThe "_" and "%" symbols are used as wildcards in the string expression of the LIKEconstruct. However, what if one of the wildcard symbols is in the expression you areevaluating. For example, to search for the substring "95%", you must define anESCAPE 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.ProblemList all objects defined in the Teradata Database Data Dictionary whose names contain"_" (underscore) as the second character.SolutionSELECT tablenameFROM dbc.tablesWHERE tablename LIKE _Z_% ESCAPE Z;TableName------------------------------M_7_Bt_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 stringexpression must be immediately followed by either the "_", "%", or the ESCAPEcharacter 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.ExampleLIKE %A%%AAA_ ESCAPE ASearches 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 -- ANDLogical operators AND, OR and NOT allow you to specify complex conditional expressionsby combining one or more logical expressions.Logical Operator ANDThe logical operator AND combines two expressions, both of which must be true in agiven record for them to be included in the result set. Boolean Logic TableTrue AND True = TrueFalse AND True = FalseTrue AND False = FalseFalse AND False = False
True OR True = TrueTrue OR False = TrueFalse OR True = TrueFalse OR False = FalseNOT True = FalseNOT false = TrueProblemDisplay the name and employee number of employees in department 403 who earn lessthan $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 1005Logical Operator -- ORThe logical operator OR combines two expressions. At least one must be true in a givenrecord for it to be included in the result set.ProblemDisplay 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;Resultfirst_name last_name employee_number---------- ---------- ----------------Arnando Villegas 1007Carol Kanieski 1008Loretta Ryan 1005John Stein 1006Multiple AND . . . ORYou want to find all employees in either department 401 or department 403 whosesalaries 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 -- CombinationsOperator ProceduresParentheses 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 Booleanoperators. By default, NOT has higher precedence than AND which has higher precedencethan 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 getsevaluated in a totally different order. If we were to use it in a query, it would yielddifferent results.NOT has the highest precedence of the three operators.
Logical Operators -- Using ParenthesesProblemSelect the name, department number, and job code for employees in departments 401or 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) ;Resultlast_name department_number job_code----------- --------------------- ----------Villegas 403 432101Johnson 401 412101If we accidentally left the parentheses out of our statement, would we get the sameresults? 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 412101Trader 401 411100QuestionJames Trader does not have either job code. Why was he selected?AnswerWithout parentheses, the default precedence causes the expression to be evaluated asfollows: 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. SinceJames Trader is in department_number 401, that expression evaluates to true.Therefore the row qualifies for output.Multiple ANDUse multiple ANDs if you need to locate rows which meet all of two or more sets ofspecific criteria.For example, what happens if we take the previous example, and replace all the ORswith 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?AnswerFor a row to be displayed in this answer set, an employee would have to be indepartment numbers 401 and 403. While we could conceive of an employee whoworks in two departments, the employee table has only one field for departmentnumber. There is no way that any row in this table can contain more than onedepartment number. This query never will return any rows. A more realistic examplefollows.
ProblemFind all employees in department number 403 with job_code 432101 and a salarygreater 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 ;Resultlast_name department_number job_code salary_amount----------- ---------------------- ---------- ----------------Lombardo 403 432101 31000.00Villegas 403 432101 49700.00Charles 403 432101 39500.00Hopkins 403 432101 37900.00Brown 403 432101 43700.00Logical NOTPlace the NOT operator in front of a conditional expression or in front of a comparisonoperator if you need to locate rows which do not meet specific criteria.ProblemSelect 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 1007James Trader 1003Loretta Ryan 1005Darlene Johnson 1004SQL Lab Databases Info Document:Your assigned user-id has SELECT access to the ‗Customer_Service‘and the ‗Student‘ databases. These databases are used for labsduring this SQL course. When selecting from tables, either set yourdefault database to Customer_Service, Student, or your own user-assigned database (depending on the lab requirements) oralternatively, qualify your table names to reflect the appropriatedatabase.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 thiscourse.‗Customer_Service‘ Table DefinitionsCREATE 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 DefinitionsCREATE 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 ADATABASE Customer_Service;SELECT employee_number ,last_name ,salary_amount ,job_codeFROM employeeWHERE salary_amount >= 40001AND salary_amount <= 50000ORDER 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 432101SELECT employee_number ,last_name ,salary_amount ,job_codeFROM employeeWHERE salary_amount BETWEEN 40001 AND 50000ORDER 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
22000013 617 7562918 ? System Manager 31000004 609 5591011 224 System Manager 33000003 212 7232121 ? System ManagerLab Answer DSELECT customer_number ,customer_name ,sales_employee_numberFROM customerWHERE parent_customer_number IS NULLAND sales_employee_number IS NOT NULLORDER BY 1;*** Query completed. 14 rows found. 3 columnsreturned.customer_number customer_namesales_employee_number -------------- ---------------------------- ----------------------- 1 A to Z Communications, Inc.1015 3 First American Bank1023 5 Federal Bureau of Rules1018 6 Liberty Tours1023 7 Cream of the Crop1018 8 Colby Co.1018 9 More Data Enterprise1023 10 Graduates Job Service1015 11 Hotel California1015 12 Cheap Rentals1018 14 Metro Savings1018 15 Cates Modeling1015 17 East Coast Dating Service1023 18 Wall Street Connection1023Lab Answer E
SELECT job_code ,descriptionFROM jobWHERE (job_code BETWEEN 400000 AND 499999AND 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 AnalystNote: EXPLAIN text varies depending on optimizer path.Lab Answer G
SELECT location_number ,area_code ,phone ,extensionFROM location_phoneWHERE extension IS NULLAND area_code IN (415,617)ORDER BY area_code ,phone;*** Query completed. 9 rows found. 4 columnsreturned.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:- 6ObjectivesAfter 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 TypesEvery column in a row is associated with a data type that defines the kind of values itaccepts. 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 HoldsCharacter data Character StringsByte data Binary Data Strings
Numeric data Numbers Dates,Times,Timestamps,Time Intervals (Note: Time, Timestamps and IntervalsDate/Time data are covered in the Teradata SQL Advanced course)Character DataThere 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 specifiedin 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 inthe above example), the system will append and store trailing blanks as needed toexpand the string to the specified length. The size specified on a VARCHAR fieldrepresents a maximum length. The system will not pad the contents with trailingblanks. (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 afour-character length) use CHAR. You save the two bytes that VARCHAR would use tostore the length. When data does not have a fixed length (e.g., last names), VARCHARmakes more efficient use of the space, because it does not pad values with trailingblanks.Character Data Description ExampleCHAR (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 charactersCHARACTER VARYING Sample contents:(size) LorettaLONG VARCHAR Equivalent to VARCHAR (64000)Note: VARCHAR(size), CHAR VARYING(size), and CHARACTER VARYING(size) are allequivalent 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 GRAPHICByte DataTeradata 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 bytesNote: BYTE columns are not covertible to other data types.Numeric Data