Chapter 8 Querying the Database. Teradata 2800
Reklamë
Reklamë
CHAPTER 8
Querying the Database
The tasks presented in this chapter, although not specifically required, represent best practices for querying the database. For best results you should read and consider the information presented. You can perform the tasks that apply to your implementation in any order.
Working with SQL Queries
Invoking SQL Statements
Teradata Database offers the following ways to invoke an executable SQL statement:
•
Interactively from a terminal
•
Embedded within an application program
•
Dynamically created within an embedded application
•
Embedded within an SQL procedure (a procedure that is written using SQL statements)
•
Embedded within an external procedure (a procedure that is written using C, C++, or
Java)
•
Dynamically created within an SQL procedure
•
Submitted in a BTEQ script as a batch job
•
Via a trigger
•
Embedded within a macro
Note: Teradata refers to a procedure as a stored procedure.
Reference Information
Information on...
•
SQL procedures (written using
SQL statements)
•
external procedures (written using C, C++, or Java) embedded SQL using dynamic SQL:
•
with embedded applications
•
in SQL procedures
Is available in...
“About Procedures and External Procedures” on page 404
SQL Stored Procedures and Embedded SQL, B035-1148
SQL Stored Procedures and Embedded SQL, B035-1148
Teradata Data Warehouse Appliance 2800 Implementation Guide 213
Chapter 8: Querying the Database
Working with SQL Queries
Information on...
BTEQ scripts triggers macros
Is available in...
“Using BTEQ Scripts to Create Database Objects” on page 196
“Working with Macros” on page 223
Using Single- and Multistatement Requests
In Teradata Database, a request consists of one or more SQL statements and can span any number of input lines:
•
A single-statement request is treated as a solitary unit of work.
•
A multistatement request consists of two or more SQL statements that are treated as a single unit of work. If one statement in the request fails, the entire request fails and the system rolls back the entire request.
How you specify a multistatement request depends on the application you use to submit the query.
For example, in BTEQ, a Teradata request terminates with a semicolon (;) character at the end of a line. A semicolon placed at any other point in the request does not terminate it. You can use this property to stack multiple SQL statements within a single request either by placing intermediate semicolons at the beginning of a subsequent line or in the middle of a line.
Example 1 Single-Statement Request in BTEQ
BTEQ submits the following statements to the Teradata Database as three single-statement requests:
SELECT * FROM Employee;
DELETE FROM Employee
WHERE Associate_Name = 'Winter' AND Associate_Id = 394;
SELECT Associate_Name FROM Employee;
Example 2 Multistatement Request in BTEQ
To submit the three statements in Example 1 as a single multistatement request, enter:
SELECT * FROM Employee
; DELETE FROM Employee
WHERE Associate_Name = 'Winter' AND Associate_Id = 394
; SELECT Associate_Name FROM Employee;
In SQL Assistant, the semicolon position of the request is ignored. You can enter multiple SQL statements in the Query Window, then use the Execute Parallel command to submit the
statements as a single request. See “Executing Multiple SQL Statements in Parallel” on page 220
.
The multistatement request improves performance for a variety of applications that can package more than one SQL statement at a time, such as BTEQ, CLI, and the SQL preprocessor.
214 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with SQL Queries
Multistatement requests improve system performance by reducing processing overhead. By performing a series of statements as one request, performance for the client, the Parser, and the Database Manager are all enhanced.
Because of this reduced overhead, using multistatement requests also decreases response time.
A multistatement request that contains 10 SQL statements could be as much as 10 times more efficient than the same 10 statements entered as separate requests (depending on the types of statements submitted).
There are a few restrictions on multistatement requests. For example, DDL statements are not valid in a multistatement request. Multistatement requests are non-ANSI standard.
Reference Information
Information on...
multistatement requests submitting single-statement and multistatement requests using BTEQ submitting single-statement and multistatement requests using SQL
Assistant
Is available in...
SQL Fundamentals, B035-1141
Basic Teradata Query Reference, B035-2414
•
“Using SQL Assistant to Submit a Query” on page 219
•
Teradata SQL Assistant for Microsoft Windows User
Guide, B035-2430
About Differences Between Teradata SQL and ANSI SQL
Teradata tries to conform to the ANSI SQL standard whenever possible. However, to create innovative features and capabilities, Teradata has also developed SQL language elements that do not conform to the ANSI SQL standard. Often, this was because a standard did not exist when the feature was designed.
Teradata SQL features conform to industry standards in the following ways:
•
The feature is fully ANSI SQL:2008 compliant
•
The feature is partially ANSI SQL:2008 compliant
•
The feature is a Teradata extension to the ANSI SQL standard
•
The feature is ANSI SQL:2008 compliant, but also has some options or capabilities that are
Teradata extensions to the ANSI SQL standard
•
The feature is ISO SQL/MM Spatial compliant
•
The feature is partially ISO SQL/MM Spatial compliant
Teradata Data Warehouse Appliance 2800 Implementation Guide 215
Chapter 8: Querying the Database
Working with SQL Queries
In the cases where the existing Teradata SQL dialect differs from the ANSI SQL standard,
Teradata adheres to the following policy:
•
If the difference between the Teradata SQL dialect and the ANSI SQL standard for an SQL feature is slight, the ANSI SQL is added to the Teradata SQL feature as an option.
•
If the difference between the Teradata SQL dialect and the ANSI SQL standard for an SQL feature is significant, both syntaxes are offered, and the user has a choice of:
•
using the Teradata SQL dialect by operating in Teradata session mode.
•
using the ANSI SQL standard by operating in ANSI session mode.
Reference Information
Information on...
•
SQL features available in Teradata, and which features are ANSI SQL compliant and which features are Teradata extensions
•
Terminology differences between ANSI
SQL and Teradata
Is available in...
SQL Fundamentals, B035-1141
About Session Modes and Transaction Processing
Teradata Database supports two session modes:
•
ANSI
•
Teradata
In ANSI session mode:
•
Transaction processing follows the rules defined by the ANSI SQL:2008 standard.
•
For Teradata SQL features that support both the ANSI SQL standard syntax and the
Teradata SQL dialect, the ANSI SQL standard syntax is used. See
Between Teradata SQL and ANSI SQL” on page 215
.
•
The default case specification for character data is CASESPECIFIC.
•
When a character string requires truncation, the excess pad characters are truncated without reporting an error. Truncation of characters other than trailing nonblank characters results in a truncation exception.
•
Cursors are always positioned. Updating or deleting the most current fetched cursor row using the UPDATE/DELETE … WHERE CURRENT OF statement is valid.
•
The default table type is MULTISET, which allows duplicate rows.
•
The TRIM function trims both leading and trailing pad characters by default.
In Teradata session mode:
•
Transaction processing follows the rules defined by Teradata before the emergence of the
ANSI SQL standard. These rules largely conform with ANSI semantics, but in some cases differ in important ways from the ANSI semantics.
216 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with SQL Queries
•
For Teradata SQL features that support both the ANSI SQL standard syntax and the
Teradata SQL dialect, the Teradata SQL syntax is used. See
Teradata SQL and ANSI SQL” on page 215 .
•
The default case specification for character data is NOT CASESPECIFIC. The exception is character data of type GRAPHIC, which is always CASESPECIFIC.
•
When a character string requires truncation, the string is truncated silently with no truncation notification given. This is true for truncation of pad or non-pad characters.
•
Cursors are never positioned. Updating or deleting the most current fetched cursor row using the UPDATE/DELETE … WHERE CURRENT OF statement is not valid.
•
The default table type is SET, which does not allow duplicate rows.
•
The TRIM function trims only trailing pad characters by default.
Note: Case specificity does not apply to CLOBs.
A transaction is a logical unit of work. The statements nested within the transaction either execute successfully as a group or do not execute. A Teradata SQL transaction can be a single
Teradata SQL statement, or a sequence of Teradata SQL statements.
Transaction Processing in ANSI Session Mode
In ANSI mode, transactions are always implicitly started and explicitly closed.
A transaction initiates when one of the following happens:
•
The first SQL request in a session executes
•
The first request following the close of a previous transaction executes
The COMMIT or ROLLBACK/ABORT statements close a transaction.
If a transaction includes a DDL statement (including DATABASE and SET SESSION, which are considered DDL statements in this context), it must be the last statement in the transaction other than the transaction closing statement.
If an error is found in a request, then that request is aborted. Normally, the entire transaction is not aborted; however, some failures will abort the entire transaction. Locks placed by erroneous statements are not released.
Sessions in ANSI mode do not support BEGIN TRANSACTION/END TRANSACTION statements.
Transaction Processing in Teradata Session Mode
In Teradata mode, transactions can be either implicit or explicit.
A request that is not enclosed by the BEGIN TRANSACTION and END TRANSACTION statements is treated as an implicit transaction.
An implicit transaction can be one of the following:
•
A single DML statement
•
A macro or trigger
•
A multistatement request
Teradata Data Warehouse Appliance 2800 Implementation Guide 217
Chapter 8: Querying the Database
Working with SQL Queries
DDL statements are not valid in a multistatement request and are therefore not valid in an implicit transaction composed of a multistatement request.
Explicit transactions contain one or more statements enclosed by BEGIN TRANSACTION and END TRANSACTION statements. The first BEGIN TRANSACTION initiates a transaction and the last END TRANSACTION terminates the transaction. Explicit transactions can contain multistatement requests.
When multiple statements are included in an explicit transaction, you can specify only a DDL statement if it is the last statement, and is immediately followed by END TRANSACTION.
If an error occurs, the request fails, the entire transaction is aborted and all locks are released.
Sessions in Teradata mode do not support the COMMIT statement. The END
TRANSACTION statement terminates a transaction with commit, while the ABORT and
ROLLBACK statements terminate a transaction with a rollback.
Setting the Session Mode
A system parameter specifies the default transaction mode for a site. You can override the default transaction processing mode for a session using one of the following:
•
SessionMode field of the DBS Control Record
•
BTEQ command .SET SESSION TRANSACTION
•
Preprocessor2 TRANSACT() option
•
Session Mode field of the Teradata ODBC Driver Options
•
JDBC TeraDataSource.setTransactMode() method
•
SQL Assistant when defining a .NET data source
Reference Information
Information on...
•
transaction, request, and statement processing
•
transaction processing in ANSI and
Teradata session mode
SQL statements for processing transactions:
•
BEGIN TRANSACTION/END
TRANSACTION
•
COMMIT
•
ABORT
•
ROLLBACK setting the SessionMode field of the DBS
Control Record using the SESSION TRANSACTION BTEQ command
Is available in...
SQL Request and Transaction Processing, B035-1142
SQL Data Manipulation Language, B035-1146
Utilities: Volume 1 (A-K), B035-1102
Basic Teradata Query Reference, B035-2414
218 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Using SQL Assistant to Submit a Query
Information on...
setting the Session Mode field in the Teradata
ODBC Driver Options dialog box setting the Session Mode field when defining a .Net data source using SQL Assistant
Is available in...
ODBC Driver for Teradata User Guide, B035-2509
Teradata SQL Assistant for Microsoft Windows User
Guide, B035-2430
Using SQL Assistant to Submit a Query
You can use Teradata SQL Assistant to compose an ad hoc SQL query, submit it to Teradata
Database, and view the results from your Windows client. In addition to querying the database, you can use SQL Assistant to create database objects, such as databases, tables, views, and users.
If you have many SQL statements in a file and you want to run it as a batch job, Teradata recommends that you use BTEQ instead. With BTEQ, you can scan saved query output for errors. You can also use BTEQ to submit end-user queries.
When deciding which program to use for submitting queries, consider the following comparisons:
BTEQ Capabilities
•
Allows use of conditional logic.
•
Creates reports, which you can format and print.
•
Requires you to store queries in outside files, which must be retrieved for reuse.
•
Can load only 64K per LOB.
SQL Assistant Capabilities
•
Does not allow use of conditional logic.
•
Returns results to a spreadsheet that can be manipulated online or saved to Excel, HTML,
PDF, or another format.
•
Keeps a history of previously used queries, which you can select for reuse.
•
Can load any LOB data that the database can store.
•
Can display pictures as part of the result set.
For more information on BTEQ, see “Working with the Basic Teradata Query Utility” on page 195
and
“Appendix C Advanced Features” .
Prerequisites
You must install the following software before using Teradata SQL Assistant:
•
Microsoft .NET Framework. See
“Installing Microsoft .NET Framework” on page 140
.
•
.NET Data Provider for Teradata. See
“Installation Guidelines” on page 138
.
•
ODBC Driver for Teradata. See “Working with ODBC Data Sources” on page 145
, which also describes how to define a Teradata data source (connection to the database).
Teradata Data Warehouse Appliance 2800 Implementation Guide 219
Chapter 8: Querying the Database
Using SQL Assistant to Submit a Query
Executing a Query Using SQL Assistant
1
To start Teradata SQL Assistant, select:
Start > Programs > Teradata Client > Teradata SQL Assistant
2
On the toolbar, select ODBC from the drop-down list located next to the Connect button
.
3
4
5
6
Click the Connect button (or select Tools > Connect).
Select the Teradata data source “Setting up Teradata as an ODBC Data Source” on page 145 .
Enter your Username and Password. For example, log on as user DBADMIN.
Do one of the following:
•
Enter an SQL statement in the Query Window.
•
Drag and drop a file from Windows Explorer into the Query Window.
7
Click the Execute button (or right-click in the Query Window and select Execute).
Executing Multiple SQL Statements in Parallel
You can run an entire query as a single request, allowing the database to execute all the statements in parallel. To do this:
1
Enter multiple SQL statements in the Query Window.
2
Click the Execute Parallel button
Reference Information
(or select Tools > Execute Parallel).
Information on...
setting query options setting formatting options for a query executing multiple SQL statements in a single request
Is available in...
Teradata SQL Assistant for Microsoft Windows User Guide,
B035-2430
“Using Single- and Multistatement Requests” on page 214
220 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with Commonly Used Queries
Working with Commonly Used Queries
The most commonly used and useful SQL queries include:
•
SELECT
•
INSERT
•
UPDATE
•
DELETE
For more details, including the complete syntax, see SQL Data Manipulation Language.
Using the SELECT Statement
The SELECT statement retrieves stored data from a table. All rows, specified rows, or specific columns of all or specified rows can be retrieved. The FROM, WHERE, ORDER BY,
DISTINCT, WITH, GROUP BY, HAVING, and TOP clauses provide for a fine detail of selection criteria.
To obtain data from specific rows of a table, use the WHERE clause of the SELECT statement.
That portion of the clause following the keyword WHERE causes a search for rows that satisfy the condition specified.
Example 1: SELECT Request With a WHERE Clause
The following SELECT request returns the last name of the employee who is employee number 1023, works in department 501, and was hired in 2006.
SELECT last_name
FROM Employee
WHERE employee_number = 1023
AND dept_number = 501
AND hire_date BETWEEN DATE '2006-01-01' AND DATE '2006-12-31';
Example 2: SELECT Request With a Subquery
The following SELECT request uses a subquery to return the names of the employees who have the highest salary in each department.
SELECT name
FROM personnel p
WHERE salary = (SELECT MAX(salary)
FROM personnel sp
WHERE p.department=sp.department);
Teradata Data Warehouse Appliance 2800 Implementation Guide 221
Chapter 8: Querying the Database
Working with Commonly Used Queries
Using the INSERT Statement
Example 1: INSERT Request
You can use the INSERT statement to add a new row to a table. The following INSERT request creates a local instance of global temporary table globdb.gt1 and populates it with a single row having the following values: f1=1, f2=980101, f3=11.1
INSERT globdb.gt1 (1, 980101, 11.1);
Example 2: INSERT...SELECT Request
You can use the INSERT … SELECT form of the statement to perform a bulk insert of rows by retrieving the new row data from another table. The following INSERT...SELECT request copies all the rows from table t3 and inserts them into table t1:
INSERT t1 SELECT * from t3;
Using the UPDATE Statement
You can use the UPDATE statement to modify data in one or more rows of a table. In the
UPDATE statement, you must specify the column name of the data to be modified along with the new value. You can also use a WHERE clause to qualify the rows to change.
After you create the following table and insert values into it:
CREATE SET TABLE t1 ( a INTEGER, b INTEGER)
PRIMARY INDEX (a);
INSERT INTO t1 VALUES (1,1);
INSERT INTO t1 VALUES (1,2); in the following UPDATE example, you update the table by decreasing the value of b by 1 whenever a =1.
UPDATE t1
SET b = b - 1
WHERE a = 1;
Using the DELETE Statement
The DELETE statement allows you to remove an entire row or rows from a table. A WHERE clause qualifies the rows that are to be deleted.
The following example counts how many books by a publisher exist in the library. If the answer is 0, the request deletes the row for that publisher.
DELETE FROM Publisher
WHERE 0 = (SELECT COUNT(*)
FROM book, publisher
WHERE book.PubNum=Publisher.pubnum);
222 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with Macros
Reference Information
Information on...
the INSERT, SELECT UPDATE, and
DELETE statements
Is available in...
SQL Data Manipulation Language
Working with Macros
Teradata Database supports macros, which consist of one or more SQL statements that are stored as a database object.
When you execute the macro, Teradata Database runs the SQL statements within the macro as a single request. Therefore, the system processes either all of the SQL statements successfully or none of the statements. Users do not receive responses to individual statements contained in the macro body until all the statements have been completed successfully.
Macros do not use any space. Only the macro definitions are stored in the Data Dictionary.
You can create a macro for your own use, or grant execution authorization to others.
Macros provide the following benefits:
•
Easy execution of simple, frequently-used SQL operations.
•
Useful for enforcing data integrity rules.
•
Useful for enforcing data security.
•
Multistatement requests can provide a performance benefit.
•
Can be used to define an appropriate level of locking.
To ensure data integrity and system security, Teradata recommends the following:
•
Set privileges so that general users cannot access or modify data tables directly.
•
Create macros which allow general users to access or modify only the table data they need.
Use macros to restrict users to performing specific queries and update functions.
•
Create macros in a Views Database. See “Working with Databases” on page 171
.
Instead of using macros, you may want to use procedures to execute more complex queries.
Procedures can process control and condition handling statements, as well as SQL statements.
See “About Procedures and External Procedures” on page 404 and “Differences between
Macros and Procedures” on page 404
.
Creating Macros
The following procedure shows how to create macros using BTEQ:
1
2
Log on to Teradata Database as user DBADMIN using BTEQ. See
Teradata Query Utility” on page 195
.
Create one or more macros using the CREATE MACRO statement. For example:
Teradata Data Warehouse Appliance 2800 Implementation Guide 223
Chapter 8: Querying the Database
Working with Macros
CREATE MACRO database_name.macro_name
(parameter_name data_type,
parameter_name data_type,
parameter_name data_type) AS
(SQL_statement;
SQL_statement;
SQL_statement;); where:
Syntax Element
database_name macro_name parameter_name data_type
SQL statement
Explanation
The name of the database where the macro will be created if it is different from the current database.
Recommendation: Specify the Views Database or a database located in the
Views Database. See “Working with Databases” on page 171
.
If database_name is not specified, the system creates the macro in the default database for the current session.
The name of the macro. The name must be unique within the database where it is created. Two identically named objects, for example, a macro named Test and a table named Test, cannot coexist in the same database.
The name of a parameter used for passing a value to the macro during execution. Parameters cannot be used for database object names. When referenced in the macro body, you must prefix a parameter name with the colon (:) character.
The data type of the parameter value.
A valid SQL statement to be executed when the macro is performed. The following rules apply:
•
A macro can include an EXECUTE statement that executes another macro.
•
For security reasons, the CREATE AUTHORIZATION or REPLACE
AUTHORIZATION statements are not allowed within a macro.
•
A data definition statement is allowed in a macro if it is the only SQL statement in that macro.
Unqualified references to database objects in a data definition statement are not resolved when the macro is created. They are resolved using the default database for the user submitting the EXECUTE statement when the macro is performed.
Unqualified references to database objects in DML statements are resolved using the default database for the user submitting the CREATE MACRO statement when the macro is created.
Recommendation: Fully qualify all references to database objects in the macro body for clarification.
Note: The example is the minimum recommended specification for creating a macro. You can specify additional macro options in the initial CREATE MACRO statement, or add them later using the REPLACE MACRO statement.
224 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with Macros
The following are common optional macro elements that you can specify in the CREATE/
REPLACE MACRO statement.
Syntax Element
data_type_attributes
USING modifier
LOCKING modifier
Explanation
The data type attributes, such as NOT NULL, UPPERCASE, or TITLE.
Not all of the data attributes that can be specified for table columns can be specified in macros. For example, the following attributes cannot be used with macro parameters:
•
CHECK constraints
•
COMPRESS phrase
Defines one or more parameters used to retrieve data from an external source such as a client data file.
Specifies the type of lock placed on a database, table, view, or row hash referenced by the subsequent SQL statement. Object referenced by a request are locked until the macro transaction is complete.
Recommendation: Use the LOCKING FOR ACCESS modifier to prevent deadlocks and increase performance, allowing concurrent access by read-only users and users who are modifying the data.
ACCESS locking is a tool that can be used to reduce the isolation of a user request, allowing that request to access valid, but uncommitted data that is subject to change.
Users that do not require precise results can access the data while modifications to the data are occurring. This can greatly improve performance because the users do not have to wait for the write operation to complete. For more information on the LOCKING clause,
see “Working with Database Locks” on page 227 .
3
To automate the creation of macros by using BTEQ scripts, see “Using BTEQ Scripts to
Create Database Objects” on page 196 .
Set privileges on the macro as follows:
•
Provide general users read-only access so they can use the macro to query data.
•
Provide privileged users with access so they can use the macro to modify data and database objects.
See
Chapter 10: “Setting Up Users,”
for information about granting privileges on the macro to users.
Example Macro
You can create macros to perform specific, narrow functions, such as adding a new employee into the database. By using a macro to perform this function, you limit the user to performing only the actions in the macro, which reduces the chance for errors. Also, the task is simpler to perform: executing the macro is easier than coding the INSERT statement.
The following request creates the New_Employee macro which inserts a row for a new employee in the Employee table, then performs a SELECT to verify that the information was
Teradata Data Warehouse Appliance 2800 Implementation Guide 225
Chapter 8: Querying the Database
Working with Macros entered correctly. If the user does not provide a value for Dept_No, the macro automatically inserts the value 300 as the default department number.
CREATE MACRO Views_Database.New_Employee
(Associate_Id INTEGER,
Associate_Name CHAR(25),
Salary DECIMAL(8,2),
DOB DATE,
Job_Title VARCHAR(25),
Dept_No SMALLINT DEFAULT 300,
Marital_Status CHAR,
No_Of_Dependents BYTEINT) AS
(INSERT INTO Tables_Database.Employee (Associate_Id, Associate_Name,
Salary, DOB, Job_Title, Dept_No, Marital_Status, No_Of_Dependents)
VALUES (:Associate_Id, :Associate_Name, :Salary, :DOB, :Job_Title,
:Dept_No, :Marital_Status, :No_Of_Dependents);
-- The following SELECT verifies the INSERT
SELECT *
FROM Tables_Database.Employee
WHERE Associate_Id = :Associate_Id; );
The example uses the -- comment construct to include a comment in the macro. Text appearing after -- and up to the end of the line is not performed.
After you create the macro, execute it as follows:
EXECUTE New_Employee (126, 'Taylor', 78000.00, '1978-12-29', 'Engineer',
400, 'S', 0);
You must have EXECUTE privilege on the macro.
Reference Information
2
2
2
For step...
2
2, 4
2
Information on...
overview of macros syntax, options, required privileges for:
•
CREATE MACRO/REPLACE MACRO
•
RENAME MACRO
•
DROP MACRO executing macros the default database data types and data type attributes
USING request modifier
Is available in...
•
Database Administration, B035-1093
•
SQL Fundamentals, B035-1141
SQL Data Definition Language, B035-
1184
SQL Data Manipulation Language,
B035-1146
SQL Fundamentals, B035-1141
•
“About Teradata Data Types” on page 393
•
SQL Data Types and Literals, B035-
1143
SQL Data Manipulation Language,
B035-1146
226 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with Database Locks
For step...
2
2
Information on...
LOCKING request modifier
Is available in...
“Working with Database Locks” on page 227
optimizing query performance with macros Database Design, B035-1094
Working with Database Locks
About Locks and Lock Levels
Teradata Database may use a different transaction isolation model than your current database.
You should review the transaction isolation needs of your queries and ensure that you have chosen the proper isolation level and method when migrating to Teradata.
The Teradata Lock Manager imposes concurrency control by locking the database object being accessed by each transaction and releasing those locks when the transaction either commits or rolls back its work.
The Lock Manager can lock an object at the following levels:
Lock Level
Database
Table
View
Row Hash
Description
Applies to all tables and views in the database.
All rows of all tables and their associated secondary index subtables are locked.
All rows in a base table and in any associated secondary index and fallback subtables are locked.
All underlying tables accessed by the view, including associated secondary indexes and fallback subtables are locked.
The primary copy of rows sharing the same row hash value are locked.
A row hash lock permits other users to access other data in the table. It is applied to the set of rows that shares the same hash code. It does not necessarily lock only one row.
A row hash lock is applied whenever a table is accessed using a unique primary index (UPI). For an update that uses a unique secondary index
(USI), the appropriate row of the secondary index subtable is also locked.
It is not necessary to lock the fallback copy of the row, nor any associated row, of a nonunique secondary index (NUSI) subtable.
The available lock severities, from most restrictive to least restrictive, are listed in the following table. The CHECKSUM and ACCESS locking severities are at the same level of restrictiveness.
Teradata Database always makes an effort to lock database objects at the least restrictive level and severity possible, to ensure database integrity while maintaining maximum concurrency.
Teradata Data Warehouse Appliance 2800 Implementation Guide 227
Chapter 8: Querying the Database
Working with Database Locks
Lock Severity
EXCLUSIVE
WRITE
READ
CHECKSUM
ACCESS
Description
Placed only on a database or table when the object is undergoing structural changes or when a database is being restored, copied, rolled back, rolled forward, or built by an Archive/Recovery utility command.
An EXCLUSIVE lock restricts access to the object by any other user.
Placed in response to an INSERT, UPDATE, or DELETE request or when a set of database objects is being recovered or restored by an Archive/Recovery utility command.
A WRITE lock enables a single user to modify the data and restricts access to the object by any other user, including those who want to read the object. However, if you are not concerned with data consistency, you can override the WRITE lock and read the data using an ACCESS lock.
Placed in response to a read operation such as a SELECT request. Archive requests can also place READ locks on database resources.
Multiple users can concurrently hold a READ lock on a base table. As long as a
READ lock is in place, no modification of the object is allowed.
Placed in response to a user-specified LOCKING FOR CHECKSUM modifier when using cursors in embedded SQL and procedures.
CHECKSUM locking is identical to ACCESS locking except that it adds checksums to the rows of a spool file to allow a test of whether a row in the cursor has been modified by another user or session at the time an update is being made through the cursor.
Placed in response to a user-specified LOCKING FOR ACCESS modifier, or by setting the session default isolation level to READ UNCOMMITTED using the
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL statement.
An ACCESS lock does not restrict access by another user except when an
EXCLUSIVE lock is required.
ACCESS locking can be used to reduce the isolation of a user request. It permits a user to have READ access to an object that might already be locked for READ or
WRITE. Because the data selected using an ACCESS lock might be modified concurrently while the object is being read, any query that requests an ACCESS lock will return valid, but uncommitted data that is subject to change. Therefore, the ACCESS lock is sometimes referred to as a dirty READ lock.
When using ACCESS locks, it is the responsibility of the database designer and the data requester to ensure the proper level of data consistency for each user.
This gives the designer a wide degree of flexibility in determining how data can be accessed.
Recommendation: To prevent deadlocks and improve performance, use
ACCESS locks whenever you are interested in a broad, statistical snapshot of the data, but you do not require precise results.
Changing the Default Lock Level
The Lock Manager imposes locks automatically. You can use the SQL LOCKING request modifier to override the default lock severities. You can use LOCKING with DML statements
228 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Working with Database Locks and with most DDL, DCL, SHOW, and HELP statements. In particular, you can use
LOCKING with the CREATE INDEX and COLLECT STATISTICS statements to prevent deadlocks. You can also use the LOCKING request modifier when defining views.
For example:
LOCKING lock_level object_name FOR lock_severity [NOWAIT] SQL_request; where:
Syntax Element Explanation
lock_level
Keyword specifying the level of the lock to be placed. The available lock levels are: DATABASE, TABLE, VIEW, and ROW.
The keyword ROW indicates that a row-hash level lock should be used.
Recommendation: Always specify the appropriate keyword. This clarifies which database object should be locked in case you have two database objects with the same name (for example, you have both a table and a database named Accounts).
object_name lock_severity
Specifies the name of the database, user, table, or view to be locked.
Specifies the severity level of the lock to be used. The available lock severities are:
ACCESS, READ, WRITE, EXCLUSIVE, and CHECKSUM.
NOWAIT
SQL_request
If the indicated lock cannot be obtained, the request should be aborted.
Recommendation: Specify this option for situations in which it is not desirable to have a request wait for resources, and possibly tie up resources another request could use.
Specifies a valid SQL request.
The specified lock will be used instead of the default lock while processing this
SQL request. The lock will remain for the duration of the transaction containing this SQL request.
The following rules apply:
•
You can specify an EXCLUSIVE lock for a DELETE, INSERT, MERGE,
SELECT, SELECT AND CONSUME, or UPDATE statement.
•
You can specify a WRITE, READ, or ACCESS lock for a SELECT statement.
•
You can specify a CHECKSUM lock only when using cursors in embedded
SQL or procedures.
•
You cannot specify LOCKING with the CALL statement.
•
You can specify LOCKING with most DDL, DCL, SHOW and HELP statements.
When a view is defined with a LOCKING modifier, the specified lock is placed on all underlying base tables each time the view is referenced in an SQL request. For example, if a view refers to tables t1 and t2, then a lock on that view would apply to both tables.
Example 1: Using the LOCKING Clause
The following LOCKING clause can be used to select data from the Employee table while it is being modified. This allows users quick access to the data without having to wait for any write
Teradata Data Warehouse Appliance 2800 Implementation Guide 229
Chapter 8: Querying the Database
Working with Database Locks operation to complete, and is perfect for users who need a statistical sample of the data, but do not require precise results.
LOCKING TABLE Tables_Database.Employee FOR ACCESS
SELECT Associate_Name, Salary
FROM Tables_Database.Employee
WHERE salary < 25000;
Example 2: LOCKING Multiple Objects
Multiple LOCKING modifiers can precede a request if it is necessary to lock more than one object at the same time, for example:
LOCKING TABLE Employee FOR ACCESS
LOCKING TABLE Department FOR ACCESS
SELECT Associate_Name, Location
FROM Employee, Department
WHERE (Associate_Id = Manager_Id);
Example 3: Converting FOR UPDATE to a Locking Modifier
In Oracle, the FOR UPDATE clause of the SELECT statement allows you to lock the selected rows so that other users cannot modify the rows until your transaction ends.
You can use the LOCKING modifier to get the same result in Teradata:
LOCKING ROW FOR WRITE
SELECT ...
Monitoring and Managing Locks
You can use the following tools to monitor and manage locks:
•
EXPLAIN request modifier
Use EXPLAIN with your SQL request to determine what locks are set when the request is executed.
•
Lock Display (lokdisp) utility.
•
The DBQL Lock Log
You can access the DBQL lock log through the Teradata Viewpoint Lock Viewer portlet or query the system table DBC.DBQLXMLLOCKTbl or the view DBC.QrylockLogXMLV.
•
Lock Viewer portlet in Teradata Viewpoint allows you to view lock data such as transaction, session, and lock object identifiers, and global deadlocks. You can get a report based on the DBQL Lock Log or Locking Logger utility data from the Lock Viewer portlet
You can locate locks:
•
In a specific database
•
Within a time frame
•
Caused by a specified user
•
That are blocking a specified user
230 Teradata Data Warehouse Appliance 2800 Implementation Guide
Chapter 8: Querying the Database
Checkpoint
Reference Information
Information on...
managing locks locking and transaction processing syntax and options for the LOCKING request modifier guidelines for changing default lock assignments syntax and options for the SET SESSION
CHARACTERISTICS AS TRANSACTION
ISOLATION LEVEL statement session isolation level specifying locking in views the EXPLAIN request modifier
Is available in...
Database Administration, B035-1093
SQL Request and Transaction Processing, B035-1142
SQL Data Manipulation Language, B035-1146
SQL Data Manipulation Language, B035-1146
SQL Data Definition Language, B035-1184
SQL Data Definition Language, B035-1184
“Working with Views” on page 191
“Using EXPLAIN to Analyze Query Plans” on page 239
Utilities: Volume 2 (L-Z), B035-1102 using the Lock Display (lokdisp) utility to display all active database locks using the DBQL Lock Log using Teradata Viewpoint to investigate locks, blocked users and blocked sessions the DBQL chapter of Database Administration, B035-
1093
“Investigating Query Blocks and Delays” on page 304
Checkpoint
Before leaving Chapter 8: “Querying the Database,” make sure that:
Result
You know several ways of invoking SQL statements in Teradata.
You understand the implications of ANSI and Teradata session modes.
You understand the differences between
Teradata and ANSI SQL.
You can execute a query in SQL Assistant.
You can create macros in BTEQ and SQL
Assistant.
Reference
“Working with SQL Queries” on page 213
“About Session Modes and Transaction
“About Differences Between Teradata SQL and ANSI SQL” on page 215
“Using SQL Assistant to Submit a Query” on page 219
“Working with Macros” on page 223
Teradata Data Warehouse Appliance 2800 Implementation Guide 231
Chapter 8: Querying the Database
Checkpoint
Result
•
You understand the default lock levels in
Teradata Database, and how to change them.
•
You know which utilities monitor locks.
•
You ensured that you chose the proper transaction isolation level when migrating to Teradata.
Reference
“Working with Database Locks” on page 227
If you do not have these results, return to the section in the Reference column and review that procedure.
232 Teradata Data Warehouse Appliance 2800 Implementation Guide
Shkarko
Reklamë