You are on page 1of 29

A

s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7



























Handout: SQL and Database
Testing
Version: DBTESTING/Handout/0108/1.0
Date: 21-01-08














Cognizant
500 Glen Pointe Center West
Teaneck, NJ 07666
Ph: 201-801-0233
www cognizant com






A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
TABLE OF CONTENTS

Introduction ................................................................................................................................... 4
About this Module ......................................................................................................................... 4
Target Audience ........................................................................................................................... 4
Module Objectives ........................................................................................................................ 4
Pre-requisite ................................................................................................................................. 4
Chapter 1: Database Fundamentals ............................................................................................. 5
Learning Objectives ...................................................................................................................... 5
What is a Database? .................................................................................................................... 5
Authentication ............................................................................................................................... 5
Authorities and Privileges ............................................................................................................. 5
What are Database Objects? ....................................................................................................... 6
Tables ........................................................................................................................................... 6
Unique Indexes ............................................................................................................................. 6
Primary Key .................................................................................................................................. 7
Foreign Key .................................................................................................................................. 7
Views ............................................................................................................................................ 8
Aliases .......................................................................................................................................... 8
Schemas ....................................................................................................................................... 8
Triggers ......................................................................................................................................... 8
User Defined Data Types ............................................................................................................. 9
User Defined Functions .............................................................................................................. 10
Sequence .................................................................................................................................... 10
Summary: ................................................................................................................................... 10
Test Your Understanding ............................................................................................................ 10
Chapter 2: SQL Queries ............................................................................................................... 12
Learning Objectives .................................................................................................................... 12
Overview ..................................................................................................................................... 12
Query .......................................................................................................................................... 12
Select Queries ............................................................................................................................ 13
Where Clause ............................................................................................................................. 14
Like Condition ............................................................................................................................. 15
Order by Statement .................................................................................................................... 15
AND & OR Operators ................................................................................................................. 16
SQL IN ........................................................................................................................................ 17
SQL BETWEEN AND Operator .............................................................................................. 18
Page 2
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
SQL JOIN ................................................................................................................................... 19
INNER JOIN ............................................................................................................................... 20
Left Join ...................................................................................................................................... 20
Right Join .................................................................................................................................... 21
Aggregate Functions .................................................................................................................. 21
Scalar Functions ......................................................................................................................... 21
Summary: ................................................................................................................................... 22
Test Your Understanding ............................................................................................................ 22
Chapter 3: Database Testing Concepts ..................................................................................... 23
Learning Objectives .................................................................................................................... 23
Basic Database Connectivity Concepts ..................................................................................... 23
Backend Test Requirements ...................................................................................................... 23
Record Count Testing In between tables ................................................................................... 24
Field Attribute Testing In Tables ................................................................................................. 24
Textual Conversion Testing ........................................................................................................ 25
Field Shifting Testing in Tables .................................................................................................. 25
Trim Functions Testing ............................................................................................................... 25
Tables Design Testing ................................................................................................................ 25
Triggers and Referential Constraints Testing ............................................................................. 25
Summary: ................................................................................................................................... 26
Test Your Understanding ............................................................................................................ 26
References .................................................................................................................................... 28
Websites ..................................................................................................................................... 28
Books: ......................................................................................................................................... 28
STUDENT NOTES: ........................................................................................................................ 29





Page 3
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Introduction
About this Module
This module introduces the reader about the database concepts, objects which are
available in a database and SQL operations. This module also explains the testing which
needs to be performed in a database testing.
Target Audience
This module is for all those who will be a stake holder in a project.
Module Objectives
After completing this module, you will be able to:
Define database
List the objects present in a database
Explain SQL commands and their uses
Describe testing concepts related to database testing
Test the data residing in database tables
Pre-requisite
A reader should have a minimum knowledge on testing process.













Page 4
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Chapter 1: Database Fundamentals

Learning Objectives
After completing this chapter, you will be able to:
Define a Database
Define Authorities and Privileges
List the objects available in a database
List the functionalities of database objects
List the uses of the database objects
List the uses of the objects present in a database
What is a Database?
A database is an application that manages data and allows fast storage and retrieval of that data.
It collects information and organizes it so that a computer program can easily access, manage,
and update the data residing in it.
Authentication
The first security portal most users must pass through on their way to gain access to a database is
a process known as Authentication. The purpose of authentication is to verify that a user really is
who they say they are. Typically, authentication is performed by an external security facility that is
not part of the database. This security facility may be part of the operating system (as is the case
with AIX, Solaris, Linux, HP-UX, Windows 200/NT and many others). It may be a separate add-on
product (for example, Distributed Computing Environment (DCE) Security services). Or it may not
exist at all (which, by default, is the case with Windows 95, Windows 98 and Windows Millennium
Edition). If a security facility does exist, it must be presented with two specific items before a user
can be authenticated: a unique user ID and a corresponding password. The user ID identifies the
user to the security facility, while the password, which is information that is known only by both the
user and the security facility, is used to verify that the user is indeed who they claim to be.
Authorities and Privileges
Once a user has been authenticated and an attachment to an instance or a connection to a
database has been established, the Database Manager evaluates any authorities and privileges
that have been assigned to the user (these can be assigned directly to a user, or they can be
obtained indirectly from group privileges that have been assigned to a group the user is a member
of) to determine what operations the user is allowed to perform. Authorities convey a set of
privileges and/or the right to perform high-level administrative and maintenance/utility operations
against an instance or a database. Privileges, on the other hand, convey the rights to perform
certain actions against specific database resources (such as tables and views). Together,
authorities and privileges act to control access to any Database Manager for an instance, to one or
more databases running under that instances control and to a particular databases objects.
Users can only work with those objects for which they have been given that appropriate
authorization- that is, the required authority or privilege.

Page 5
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Specific Authorities are defined to secure operations like System Administration, System Control,
System Maintenance, Database Administration and Load Process.

Similarly there are tow major types of privileges as Database Privileges & Database Object
privileges. Database privileges apply to a database as a whole, and for most user, they act as
identification that gets verified at the second security checkpoint that must be cleared before
access to data is provided.
What are Database Objects?
Database objects otherwise known as data objects are used to logically store and manipulate
data, as well as to control how all user data (some system data) is organized. Database objects
include
Tables
Unique Indexes, Primary Key, Foreign Key
Views
Aliases
Schemas
Triggers
User defined data types
User defined functions
Sequences
Tables
A table is a logical database object that acts as the main repository in a database. Tables present
data as a collection of unordered rows with a fixed number of columns. Each column contains
values of the same data type or one of its subtypes, and each row contains a set of values for
every column available. Usually the columns in a table are logically related and additional
relationships can be defined between two or more tables.

Record: The storage representation of a row in a table is called a record.
Field: The storage representation of a column in a table is called a field.
Value: Each intersection of a row and column in a table is called a value.

Example:





EMPLOYEE ID EMPLOYEE NAME LOCATION
100121 JOHN CHENNAI
100124 SELVARAJ MUMBAI
100125 MANI DELHI
100127 MURALI KOLKOTA
100129 ADAM CHENNAI
Unique Indexes
An index is an object that contains an ordered set of pointers that refer to rows in a base table.
Each index is based upon one or more columns in the base table they refer to, yet they are stored
as separate entities.
Page 6
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Indexes are used primarily to enforce record uniqueness and to help the Database Manager
quickly locate records in response to a query. Indexes can also provide greater concurrency in
multi-user environments because records can be located faster, acquired locks do not have to be
held as long.

If an index is created for an empty table, that index will not have any entries stored in it until the
table the index is associated with is populated. On the other hand, if an index is created for a table
that already contains data, index entries will be generated for the existing data and added to the
index as soon as it is created. Any number of indexes can be created for a table, using a wide
variety of combinations of columns. However creating large number of indexes for a table that is
modified frequently will decrease the overall performance for all operations except data retrieval.
So tables that are used or data mining, business intelligence, business warehousing, and other
applications that execute many queries while rarely modifying data are prime targets for multiple
indexes. On the other hand, tables that are used for OLTP (On-Line Transactional Processing)
environments or other environments where data throughput is high should use indexes sparingly.

Example:

EMPLOYEE ID DEPARTMENT NAME LOCATION
100121 DEVELOPMENT CHENNAI
100124 TESTING MUMBAI
100125 BUSINESS ANALYSIS DELHI
100127 ADMIN KOLKOTA
100129 TRAVEL CHENNAI


Index






EMPLOYEE ID ROW
100127 4
100124 2
100121 1
100125 3
100129 5



Primary Key
The purpose of a primary key is to uniquely identify each record in a table. In general, a primary
key is defined on a single column. If a primary key is defined on more than one column then they
are generally called as Composite key. Basic rules to be followed while defining primary keys are
Every record must have a value in the primary key. It cannot be null
Primary key values must be unique.
Primary key values should not be reused. If a record is deleted, its primary key should
not be reassigned to another record, as this can create errors and confusion.
Foreign Key
A foreign key is a field from a table that refers to (or targets) a specific key, usually the primary
key, in another table. This is a convenient way of logically linking information from related tables.
Note that the foreign key is not unique, but the referenced field
Page 7
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Views
Views are used to provide a different way of looking at the data stored in one or more base tables.
Essentially, a view is a named specification of a result table that is populated whenever the view is
referenced in an SQL statement. Like base tables, can be thought of as having columns and rows.
And in most cases, data can be retrieved from a view the same way it can be retrieved from a
table. However whether or not a view can be used in insert, update, and delete operations
depends upon how it was defined views can be defined as being insertable, updatable,
deletable, and read-only.

Although views look similar to base tables, they do not contain real data. Instead, views refer to
data stored in other base tables. Only the view definition itself is actually stored in the database.
(In fact, when changes are made to the data presented in a view, the changes are actually made
to the data stored in the base tables(s) the view references.)
Aliases
An alias is an alternate name for a table or view. (Aliases can also be created for nicknames that
refer to data tables or views located on federated systems.) Aliases can be used to reference any
table or view that can be referenced by its primary name. However, an alias cannot be used in
every context that a primary table or view name can. For example, an alias cannot be used in the
check condition of a check constraint, nor can it be used to reference a user defined temporary
table.

Like tables and views, an alias can be created, dropped and have comments associated with it.
How ever, unlike tables (but similar to views), aliases can refer to other aliases, using a process
known as chaining.

Aliases are publicly referenced names, so no special authority or privilege is required to use them.
However, access to the table or view that is referred to by an alias still has the authorization
requirements associated with these types of objects.
Schemas
Schemas are objects that are used to logically classify and group other objects in the database.
Because schemas are objects themselves, they have privileges associated with them that allow
the schema owner to control which users can create, alter, and drop objects within them. Most
objects in a database are named using a tow-part naming convention. The first (leftmost) part of
the name is called the schema name or qualifier, and the second (rightmost) part is called the
object name. Syntactically, these two parts are concatenated and delimited with a period. Each
time an object that can be qualified by a schema name is created, it is assigned to the schema that
is provided with its name. If no schema name is provided, the object is assigned to the default
schema, which is usually the user ID of the individual that created the object.
Triggers
A trigger is used to define a set of actions that are to be executed whenever an insert, update, or
delete operation is performed on a specified table. Triggers can be used, along with referential
constraints and check constraints, to enforce data integrity rules and business rules. (A data
integrity rule might be that whenever the record for an employee is deleted from the table that
holds employee information, the corresponding record will be deleted from the table that holds
Page 8
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
payroll information. A business rule might be that an employees salary cannot be increased by
more than 10 percent). Triggers can also be used to update other tables, automatically generate
or transform values for inserted and / or update rows, or invoke functions to perform special tasks.

By using triggers, the logic needed to enforce such business rules can be placed directly in the
database, and applications that work with the database can concentrate solely on data storage,
data management, and data retrieval. And by storing the logic needed to enforce data integrity
rules and business rules directly in the database, it can be modified as data integrity rules and
business rules change without requiring applications to be recoded and recompiled.

Here are some important aspects of Triggers.
Subject table: The table that the trigger is to interact with
Trigger Event: An SQL operation that causes the trigger to be activated whenever it
is performed against the subject table. This operation can be an insert operation, an
update operation, or a delete operation.
Trigger Activation Time: Indicates whether the trigger should be activated before or
after the trigger event occurs. A before trigger will be activated before that trigger
event occurs; therefore, it will be able to see new data values before they are inserted
into the subject table. An after trigger will be activated after the trigger even occurs;
therefore, it can only see data values that have already been inserted into the subject
table.
Set of Affected Rows: The rows of the subject table that are being inserted, updated
or deleted.
Trigger Granularity: Specifies whether the actions the trigger will perform are to be
performed once for the entire insert, update or delete operation or once for every row
affected by the insert, update, or delete operation.
Triggered Action: An optional search condition and a set of SQL statements that are
to be executed whenever the trigger is activated. If a search condition is specified, the
SQL statements will only be executed when the search condition evaluates to true. If
the trigger is a Before Trigger, the triggered action can include statements that
retrieve data, set transition variables, or signal SQL states. If the trigger is an After
Trigger, the triggered action can include statements that retrieve data, insert records,
update records, delete records or signal SQ: states.
User Defined Data Types
User-defined data types (UDTs) are data types that are created (and named) by a database user.
A user-defined data type can be a distinct data type that shares a common representation with on
of the built-in data types provided with the Database or it can be a structured type that consists of
a sequence of named attributes, each of which has its own data type. Structured data types can
also be created as subtypes of other structured types, thereby defining a type hierarchy.

User defined data types support strong data typing, which means that even though they may share
the same representation as other built-in or user-defined data types, the value of one user-defined
data type is only compatible with values of that same type or of other user-defined data types
within the same data type hierarchy. As a result, user-defined data types cannot be used as
arguments for most of the built-in functions available. Instead, user defined functions (or methods)
that provide similar functionality must be developed whenever that kind of capability is needed.
Page 9
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
User Defined Functions
User-defined functions are special objects used to extend and enhance the support provided by
the built-in functions available with the database. Like user defined data types, user-defined
functions (or methods) are created and named by a database user. A user-defined function can
be an external function written in a high-level programming language, or a sourced function whose
implementation is inherited from some other function that already exists.
Sequence
A sequence is an object that is used to automatically generate data values. Unlike an identity
column, which is used to generate data values for a specific column in a table, a sequence is not
tied to any specific column or any specific table. Instead, a sequence behaves like a unique
counter that resides outside the database, with the exception that it does not present the same
concurrency and performance problems that can occur when external counters are used.
Summary:
When ever a table is created or enhanced the above mentioned attributes need to be tested. The
number of indexes created may affect the performance of the system. Similarly the triggers need
to be tested according by using or without using tools. Testing does not mean to test an
application which is developed incorrectly or incompletely is working fine or not. Testing need to
be done on the design of the tables, allocation of fields and its corresponding attributes. This
chapter is an introduction to such attributes which are very critical for a table.
Test Your Understanding
1. What is the main repository to save data in a database?
a) Table space
b) Table
c) Index

2. Which of the following events will NOT cause a trigger to be activated?
a) A select operation
b) An insert operation
c) An update operation
d) A delete operation

3. Primary keys and Unique Indexes are same. State True or False.

4. Jamal is designing an oracle table for an application that store the seats reserved in a
hotel. Select the valid option which Jamal must follow
a) Create more indexes to increase the performance of data retrieval process
b) Minimize the number of indexes to increase the overall performance of action
queries
c) Create more indexes to increase the overall performance of action queries
d) Minimize the number of indexes to increase the performance of data retrieval
process
Page 10
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
5. Ajay needs to update all the employee related tables when ever a data is inserted or
updated or deleted from the EMPLOYEE table. Ajay must use a
a) Foreign Key
b) Index
c) Schema
d) Trigger

Answers:
1. (b) Tables
2. (a) Select operation
3. (b) False
4. (b) Minimize the number of indexes to increase the overall performance of action queries
5. (d) Trigger
Page 11
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Chapter 2: SQL Queries

Learning Objectives
After completing this chapter, you will be able to:
Write SELECT Queries
Write SELECT DISTINCT Queries
Work with WHERE Clause
Work with LIKE Condition
Differentiate AND, OR, and BETWEEN Operations
Work with GROUP BY and ORDER BY conditions
Write SELECT INTO Statements
Perform INNER JOIN
Perform LEFT JOIN
Perform RIGHT JOIN
Perform Aggregate functions
Overview
This chapter introduces basic SQL Queries to the reader. This chapter will concentrate on testing
related Data Manipulation Language (DML) Statements rather than the development related Data
Control Language (DCL) & Data Definition Language (DDL) Statements.
Query
A query is a question that is asked of the database server. Database queries can
be one of two types:
Select queries: They retrieve data from tables. For instance, getting a list of
all products manufactured by a Company that cost more than $100.
Action queries: They manipulate data in some way (e.g. insert records, update or
delete existing records).For instance, adding a new product to the catalogue or
changing the address of the Company.

The language used to query a database is called query language. The most well-known is the
Structured Query Language (SQL). SQL is syntax for executing queries. But the SQL language
also includes syntax to update, insert, and delete records. These following queries together form
the Data Manipulation Language (DML) part of SQL:
SELECT: Extracts data from a database table
UPDATE: Updates data in a database table
DELETE: Deletes data from a database table
INSERT INTO: Inserts new data into a database table

Note: SQL Statements are not case sensitive, SELECT is same as select.
Page 12
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 13
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Semicolon is the standard way to separate each SQL statement in database systems that allow
more than one SQL statement to be executed in the same call to the server. Some SQL tutorials
end each SQL statement with a semicolon. Is this necessary? We are using MS Access and SQL
Server 2000 and we do not have to put a semicolon after each SQL statement, but some database
programs force you to use it.
Select Queries
The SELECT statement is used to select data from a table. The tabular result is stored in a result
table (called the result-set).

Example: Consider the following database table EMPLOYEE



To get the last name and first name of the employees we need to execute the query

Syntax: SELECT <Field Names> FROM <Table Name>

Example: SELECT LAST NAME, FIRST NAME FROM EMPLOYEE

The result will be as follows


To select all the fields from the table we need to use * symbol as mentioned below

Syntax: SELECT * FROM <Table Name>

Example: SELECT * FROM EMPLOYEE

The result will be as follows

To select distinct elements from a table we need to use the DISTINCT key word to the select
statement as mentioned below
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 14
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

Syntax: SELECT DISTINCT <Column(s) Name > FROM <Table Name>
Example: SELECT CITY FROM EMPLOYEE

For this query the result will be as follows


Example: SELECT DISTINCT CITY FROM EMPLOYEE

For this query the result will be as follows

Where Clause
To conditionally select data from a table (or) to specify a selection criterion a WHERE clause can
be added to the SELECT statement.

Syntax: SELECT <Column(s) Name > FROM <Table Name> WHERE <Column Name> <Operator> <Value>

The following are the operators which can be used in a WHERE clause Query.


Example: SELECT FIRST NAME FROM EMPLOYEE WHERE CITY = CORK

Note: The values entered inside the quotes are case sensitive.

For this query the result will be as follows


For Text values:
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Valid Query - SELECT * FROM EMPLOYEE WHERE FIRST NAME='JOHN'
Wrong Query - SELECT * FROM EMPLOYEE WHERE FIRST NAME=JOHN
Like Condition
The LIKE condition is used to specify a search for a pattern in a column.

Syntax: SELECT <Column Name> FROM <Table Name> WHERE <Column Name> LIKE <Pattern>
% - Sign is used for used to define wildcards (missing letters in the pattern) both before and after
the pattern
-- Sign is used for used to define single card (missing letters in the pattern) both before and after
the pattern

Example (1):
The following SQL statement will return persons with first names that start with an 'O'
SELECT * FROM EMPLOYEE WHERE FIRST NAME LIKE 'J%'

Example (2):
The following SQL statement will return persons with first names that end with an 'a'
SELECT * FROM EMPLOYEE WHERE FIRST NAME LIKE '%a'

Example (3):
The following SQL statement will return persons with first names that contain the pattern 'la':
SELECT * FROM EMPLOYEE WHERE FIRST NAME LIKE '%LE%'
Order by Statement
The ORDER BY keyword is used to sort the retrieved rows base on particular key(s).
Consider the example of the following PRODUCT table


Example (1):
To display the company names in alphabetical order we need to execute the following query
SELECT COMPANY, PRODUCT NUMBER FROM PRODUCT ORDER BY COMPANY
The result will be displayed as follows:


Example (2):
To display the company names in alphabetical order AND the Product Number in numerical order:
Page 15
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 16
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
SELECT COMPANY, PRODUCT NUMBER FROM PRODUCT ORDER BY COMPANY, PRODUCT
NUMBER

The result will be displayed as follows:


Example (3):
To display the company names in reverse alphabetical order the query will be
SELECT COMPANY, PRODUCT NUMBER FROM PRODUCT ORDER BY COMPANY DESC

The result will be displayed as follows:


Example (4):
To display the company names in reverse alphabetical order AND the Product Number in
numerical order we need to execute the query
SELECT COMPANY, PRODUCT NUMBER FROM PRODUCT ORDER BY COMPANY DESC,
ORDER NUMBER ASC

The result will be displayed as follows:

AND & OR Operators
AND operators and OR operators are used to combine two or more conditions in a where clause

The AND operator displays a row if ALL conditions listed are true. The OR operator displays a row
if ANY of the conditions listed are true.

Consider the example of the following EMPLOYEE table

Example (1):
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 17
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
To fetch records with first name equal to "Tove" and the last name equal to "Svendson" we need to
execute the following query
SELECT * FROM EMPLOYEE WHERE FRIST NAME='JOHN' AND LAST NAME='STEWART'
The result will be displayed as follows:




Example (2):
To fetch records with first name equal to "Tove" or the last name like S% we need to execute the
following query

SELECT * FROM EMPLOYEE WHERE FRIST NAME='JOHN' OR LAST NAME LIKE 'S%'

The result will be displayed as follows:

Example (3):
We can also combine AND and OR operation to form complex expressions as below

SELECT * FROM EMPLOYEE WHERE (FIRST NAME='john' OR FIRST NAME='Alex')
AND LAST NAME LIKE 'S%'

The result will be displayed as follows:
SQL IN
The IN operator may be used when we know the exact value we want to return for at least one of
the columns.

Syntax: SELECT <Column Name> FROM <Table Name> WHERE <Column Name> IN (Value1, Value2,..)
Consider the following EMPLOYEE table


Example:
To display the persons with Last Name equal to "Moody" or "staurt" the SQL statement is

SELECT * FROM EMPLOYEE WHERE LAST NAME IN ('Moody', 'staurt)
The result will be displayed as follows:
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 18
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected

SQL BETWEEN AND Operator
The BETWEEN ... AND operator selects a range of data between two values. These values can be
numbers, text, or dates.

Syntax: SELECT <Column name> FROM <Table Name> WHERE <Column Name> BETWEEN <Value1>
AND <Value2>
Consider the following EMPLOYEE table




Example (1):
To display the records alphabetically between (and including) "Cork" and exclusive "Naigara", use
the following SQL

SELECT * FROM EMPLOYEE WHERE CITY BETWEEN 'CORK' AND 'NAIAGRA'

The result will be displayed as follows:


IMPORTANT: The BETWEEN...AND operator is treated differently in different databases. With
some databases a person with the LAST NAME of "Hansen" or "Pettersen" will not be listed
(BETWEEN..AND only selects fields that are between and excluding the test values). With some
databases a person with the last name of "Hansen" or "Pettersen" will be listed (BETWEEN..AND
selects fields that are between and including the test values). With other databases a person with
the last name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND selects
fields between the test values, including the first test value and excluding the last test value).
Therefore: Check how your database treats the BETWEEN....AND operator!

Example (2):
To display the city outside the range used in the previous example, use the NOT operator

SELECT * FROM EMPLOYEE WHERE CITY NOT BETWEEN 'CORK' AND 'NAIAGRA'

The result will be displayed as follows:
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 19
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
SQL JOIN
One of the more powerful features of the SELECT statement and the element that makes data
normalization possible is the ability to retrieve data from two or more tables by performing what is
known as a join operation.


In its simple form the syntax for a SELECT statement that performs a join operation is

Syntax: SELECT <*/Expression> AS <New Column Name> FROM <Table Name1> AS <Correlation
Name> JOIN <Table Name2> AS <Correlation Name> ON <Join Condition>

Consider the below two tables






We can select data from two tables by referring to two tables as follows

Example (1):
Who has ordered a product, and what did they order?

SELECT EMPLOYEES.NAME, ORDERS.PRODUCT FROM EMPLOYEES, ORDERS WHERE
EMPLOYEES.EMPLOYEE_ID=ORDERS.EMPLOYEE_ID
The results will be as follows:

Example (2):
Who ordered a printer?

SELECT EMPLOYEES.NAME FROM EMPLOYEES, ORDERS
WHERE EMPLOYEES.EMPLOYEE_ID = ORDERS.EMPLOYEE_ID AND ORDERS.PRODUCT='Printer'

The results will be as follows
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 20
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
INNER JOIN
One of the more powerful features of the SELECT statement and the element that makes data
normalization possible is the ability to retrieve data from two or more tables by performing what is
known as a join operation.


In its simple form the syntax for a SELECT statement that performs a join operation is

Syntax: SELECT <tield1>, <Field2>, <Field3>
FROM <First Table> INNER JOIN <Second Table>
ON <First Table.Keyfield> = <Second Table.Foreign_keyfield>

Example (2):
Who has ordered a product, and what did they order?

SELECT EMPLOYEES.NAME, ORDERS.PRODUCT
FROM EMPLOYEES INNER JOIN ORDERS
ON EMPLOYEES.EMPLOYEE_ID = ORDERS.EMPLOYEE_ID

This INNER JOIN returns all rows from both tables where there is a match. If there are rows in
Employees that do not have matches in Orders, those rows will not be listed.

The results will be as follows

Left Join
The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches
in the second table (Orders).

Example:
Who has ordered a product and what are their orders?

SELECT EMPLOYEE.NAME,ORDERS.PRODUCT
FROM EMPLOYEES LEFT JOIN ORDERS
ON EMPLOYEES.EMPLOYEE_ID = ORDERS.EMPLOYEE_ID

The Result will be as follows:

A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 21
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Right Join
The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches
in the first table (Employees). If there had been any rows in Orders that did not have matches in
Employees, those rows also would have been listed.
Example:
What are the products are ordered and who has ordered?
SELECT Employees.Name, Orders.Product
FROM Employees RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

The result will be as follows:

Aggregate Functions
Aggregate functions operate against a collection of values, but return a single value.

Note: If used among many other expressions in the item list of a SELECT statement, the SELECT
must have a GROUP BY clause!!

Some examples of Aggregate Functions used in MS Access and SQL Server is given below:
Aggregate Functions:
Function Description
AVG(column)
Returns the average value of a column
COUNT(column)
Returns the number of rows (without a
NULL value) of a column
COUNT(*)
Returns the number of selected rows
FIRST(column)
Returns the value of the first record in a
specified field
LAST(column)
Returns the value of the last record in a
specified field
MAX(column)
Returns the highest value of a column
MIN(column)
Returns the lowest value of a column
SUM(column)
Returns the total sum of a column

Scalar Functions
Scalar functions operate against a single value, and return a single value based on the input value.
Some examples of Scalar Functions used in MS Access is given below:
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing

Summary:
To perform an effective testing on a database table basic knowledge on SQL queries is
indispensable. This chapter is an introduction to such query building requirement. Though in real
time projects Insert and update queries are also used to test tables, here we have considered only
select statements since similar syntax can be used for insert and update queries also. More over
query building skills can be increased by case studies or by practically building queries to test
complicated applications.
Test Your Understanding
1) When we have a fixed set of values for which we need to extract data from a database we
use which type of query?
a) IN BETWEEN
b) IN
c) LIKE
d) RIGHT or LEFT
2) When we are not sure about the string for which we need to extract we search for a pattern
using
a) IN
b) LIKE
c) MATCH
d) SEARCH <string> *
3) The wild card use to search for a string is
a) *
b) -
c) _
d) %

Answers:
(1) (b) IN (2) (b) LIKE (3) (d) %
Page 22
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Chapter 3: Database Testing Concepts

Learning Objectives
After completing this chapter, you will be able to:
Explain Basic Database connectivity
Explain Backend test Requirements
Record counts testing in between tables
Perform Field attributes testing of tables
Perform Textual conversion testing
Perform Field shifting testing in between tables
Work with Tables Design testing
Explain Triggers and referential constraints testing
Basic Database Connectivity Concepts
To connect with any database we need the following details
TNS names (I.P, Port & other related details)
Database name
User ID
Corresponding Password

TNS names Transparent Network Substrate, allows peer-to-peer connectivity where no machine-
level connectivity can occur. It provides a user-transparent layer that enables a heterogeneous
network consisting of different protocols to function as a homogeneous network. TNS forms a
transparent layer to which different network protocols can connect. It provides a network of
applications above the existing networks of computers. Oracle Corporation typically relies on TNS
to provide generic network connectivity to and between Oracle databases, regardless of underlying
protocols. (I.P., port and other related details)

TNS names are the details about the server I.P and its port along with the other details like names
and other authentication related information. This need to be added to the TNS names file present
in the Database installation folders. Without this information establishing database connection
becomes impossible. Apart from this we also need the Database name, User ID and Password to
establish the database connection and successfully interact with its objects.
Backend Test Requirements
Backend testing means ensuring data is properly stored as expected. Backend testing can occur
in between any of the type of applications such as it may occur in between Online applications &
Backend applications or Among backend applications.
Page 23
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Direct Data Validation in Between Tables
Some of the Backend testing in between tables may require a direct data validation. In such cases
the data flow in between the tables need to be tested where the field attributes are same in
between the source and the target. We call such type of testing as direct data validations.

In case of database testing we execute JOIN queries to handle these types of requirements.
Though we use the INNER JOIN queries mostly we also use RIGHT or LEFT joins as per the data
flow and the requirement.

Data Requirements Testing in between Tables
Some of the real time Backend Testing projects may require in between tables. Data requirement
testing means, testing data residing in two different tables in a single/multi database where the
field attributes may be modified in between them. For example fields may be split or concatenated
before they are actually transferred to the destination tables. In such cases testing process must
implement such split or concatenation criteria before validating the data residing in such tables.
Testing in such cases SELECT queries should be executed along with the appropriate selection or
omission criteria with AS statements. Based on the requirement appropriate modification in the
queries need to be done in these cases.
Business Rule implementation testing In between Tables
Backend applications are usually maintained by implementing lots of business rules in between
them. Some of the Business rules are implemented for the business requirements while some of
them are implemented for performance and data integrity requirements also. In such cases testing
also need to implement those business rules and tests whether they are properly implemented in
between tables. Queries need to be built according the business rules and the fields involved in
them. In some cases this type of testing can also be done using ETL tools also
Record Count Testing In between tables
Whenever there is a data flow from one table to another table without any data cleansing or
filtration criteria then the number of records in between the tables need to be verified. This could
be done using SELECT COUNT queries. But the ideal approach will be to execute join queries for
all the common fields existing in between the tables where data flows (on receiving the appropriate
primary or composite key). This type of JOIN queries will not only ensure the data count but also
the actual data migrated or copied in between such tables.
Field Attribute Testing In Tables
When ever a table is created or modified the field attributes need to be tested as a smoke test for
that backend testing. This testing is done to ensure the descriptions of tables are present as
expected. Testers need to test the field definitions of tables to ensure these requirements.
Executing a DESC query for an ORACLE table can do this. Similarly for each and every database
we have commands to obtain the field attributes of created tables. Care should be taken to test
the attribute along with constrains defined for each and every field like NOT NULL, NULL, other
defaulted values, decimal precisions and date formats. If the field definition is wrong ultimate the
expected behaviour of the table may also go wrong. So usually we include Field attribute testing
as a part of smoke testing itself.
Page 24
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Textual Conversion Testing
When a source table does not contain characters that are not handled properly these characters
may be moved inappropriately to the subsequent tables. Visually scanning the import fields often
illustrates where data is incorrect. Common causes of this error involve commas, single or double
quotes and other unusual characters.
Field Shifting Testing in Tables
A common error in data conversion using fixed width files is the importing of the wrong data to a
column by a shift in the field assignments. This is especially true for common data types where a
type check will not identify the error. Cross-referencing a sample set of records to the source
system can identify this systematic error.
Trim Functions Testing
In some cases data may be loaded into tables with preceding or proceeding spaces. In such
cases the actual data may not appear to contain them actually. By executing queries to fetch
records based on some user provided values for such fields may uncover such errors. So in every
database testing process must test whether preceding or proceeding spaces are present in the
actual data stored in the table.
Tables Design Testing
Risks are increasing in Backend Testing projects now a day. The Complications in the data
management process has increased these risks. In such cases testing needs do have a wide
definition. Testing is not just to ensure whether an incompletely developed or incorrectly
developed application is working fine or not. So Design testing is critical for a backend application.
Design testing can be classified into two. This may be from Domain perspective and from
Application perspective.

From Domain perspective the completeness of the design need to be verified. For example a
prescription table can exist without the Medicine and Concentration fields. So the completeness of
the tables needs to be tested from domain perspective. Inculcating efficient business analysts to
verify the completeness could do this testing.

From Application perspective the referential integrity in between tables need to be tested. For
example the association and the functionality in between the foreign and parent keys needs to be
verified. Having a good understanding on the application at a higher level could do this testing.
Triggers and Referential Constraints Testing
Triggers are implemented in backend applications to implement business critical rules at the
database level. Implementation of such rules at the application level may affect the performance
of applications. Such triggers are also need to be checked. This type of testing can be performed
by inserting, updating or deleting data from the source tables and observing their appropriate
reactions in the target tables. Similar type of testing also needs to be implemented for referential
constraints too.
Page 25
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Summary:
To perform an effective and efficient database testing it is mandatory to include the entire above
mentioned test scenarios in the form of test cases. These testing can be performed manually by
preparing test data specific to the test scenarios and can so be performed by implementing some
tools to test large volume of data. Apart from this there are security level testing which also needs
to be done on the newly created, altered and enhanced tables. Since security requirements are
usually varying in between projects we have not included in this presentation.
Test Your Understanding
1. When ever a table is altered or newly created, we should perform these testing at the
initial stage before data population (select multiple ones)
(a) Design level testing
(b) Data load testing
(c) Business rules testing
(d) Field Attributes testing

2. Business rules implemented in tables cannot be tested by building SQL queries. State
True or False.

3. Tester need not update or insert records in tables to test. State True or False.

Answers:

1. (a) Design Level Testing
(b) Field Attributes Testing
2. False
3. False

Page 26
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Glossary

Database - An application that manages data and allows fast storage and retrieval of that data

Tables - A logical database object that acts as the main repository in a database

Record - The storage representation of a row in a table is called a record.

Field - The storage representation of a column in a table is called a field.

Value - Each intersection of a row and column in a table is called a value.

Index - An object that contains an ordered set of pointers that refer to rows in a base table

Primary key Set of fields used to provide unique identity to each and every record in a table

Foreign Key - A field in table that refers a specific key, usually the primary key, in another table

Triggers - set of pre defined actions that are to be executed whenever an insert, update, or delete
operation is performed on a specified table

SQL Structured Query Language

TNS - Transparent Network Substrate that allows peer-to-peer connectivity where no machine-
level connectivity can occur.






Page 27
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
References

Websites
http://en.wikipedia.org
Books:
SQL in a Nutshell - Publisher: Oreilly & Associates Inc
SQL Bible - John Wiley & Sons Inc













Page 28
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
A
s
s
o
c
i
a
t
e
I
D
:
2
4
5
2
1
7
Handout - SQL and Database Testing
Page 29
Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
STUDENT NOTES:

You might also like