You are on page 1of 63

DATABASE TESTING

DATABASE MANAGEMENT SYSTEM


Data Base Management System is defined as collection of Software Programs
used to store the data, manage the data, and retrieve the data. Data retrieval is
based on three points
Accuracy Data Free from Errors.
Timelines With in a time
Relevancy Related Data
Maintaining of the data can be done in two ways.
File System
Data Base
Why Database Management System and why not flat files to maintain the data.
Flat Files has many disadvantages they are
No Security
Difficulty in accessing the data
Redundancy
Data Inconsistency
Sequential Search Technique (Time Consuming Process)
Indexing is not present in file system
No Identifier (Related Information)

What is database?
It is defined as Logical Container which contains related
objects, Objects Includes Tables, Views, Synonyms, Stored
Procedures, Functions, Triggers Etc.
What is DBMS?
DBMS:-Database management system is a software
package designed to store and manage database.
Ex: Dbase, FoxPro, PostgreSQL
DBMS is for smaller organizations with small amount of
data, where security of the data is not of major concern
What is RDBMS?
Relational Data Base Management Systems (RDBMS) are
database management systems that maintain data records and
indices in tables. Relationships may be created and maintained
across and among the data and tables.
SQL SERVER:
It was introduced in the year 1989 by MICROSOFT as SQL
SERVER 1.0
It is GUI based RDBMS.
It is CLIENT/ SERVER technology.
It is associated with DATABASE ENGINE (set of compilers)
It can be installed on specific Operating System (WINDOWS)

What are the system databases? And the basic functions for master, msdb, model, tempdb and
resource databases?
When you first load SQL Server, you will start with four system databases:
> Master
> Model
> Msdb
> Tempdb
> Resource
> Distributed
Master: Every SQL server regardless of version, has the master database and it contains server-wide
information about SQL Server system. This server-wide information includes logins, linked server
information, configuration information for the server and information about user databases created in the
SQL Server instance.
Resource: The resource database contains all the system objects deployed with SQL Server 2008. These
system objects include the system stored procedures and system views that logically appears in the each
database but are physically stored in the resource database. Microsoft has moved all the system objects
to the resource database to simplify the upgrade process.
The msdb database stores information regarding database backups, SQL Agent information, DTS (Data
transmission services) packages, SQL Server jobs, and some replication information such as for log
shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in
the instance.

Client server environment


This environment contains 2 tiers. One is for client and other one is for servers. The
presentation layer and the business layer will be present in the clients and the database layer will be
present in the servers.
If at all the application need to be used in a single building or a single place or in a single city by
multiple users, application need to be accessed very fast and if there is no problem with security then
the best environment suggested is client server environment.

UI
Database

UI

UI

Server

Clients (PL/BL)
Client Server environment or 2-tier architecture

BANK
Account, Loans, Mutual, Insure

Capture Information:
-- Customer
-- Saving, Account
-- Insurance

Front End Applications


-- Java, . Net

Database

Views
Tables

Views
Tables
INSERT/UPDATE/DELE
TE

Tables

Views

Tables
Transaction by Transaction

OLTP- Online Transactional Processing or Transactional


Systems or Operational Systems

ETL Architecture

S
O
U
R
C
E
S
Y
S
T
E
M
S

E
T
L

S
T
A
G
I
N
G
A
R
E
A

DATA
WAREHOUSE

E
T
L
DATA
MARTS

O
L
A
P
S
E
R
V
E
R
(S)

OLAP
REPORTS

OLAP
REPORTS

What are the files created when database created?

When Database is created, it creates 2 files. They are Primary data file and
Secondary data files.

Primary data file:


The primary data file is the data file that keeps track of all the other data files
used by the database. It is an operating system file that typically has the
extension .MDF

The primary data file is the first file created for a database. Each database must
have only one primary file.
Secondary data file:
You can create 1 or more secondary data files in a database. These files, by
default, are identified with the .NDF extension.
Secondary data files provide an opportunity to spread the data that SQL Server
stores over more than one physical file. This capability can be particularly useful
for larger databases and can help with performance and management of
database files.
Transaction log file:
A transaction is a mechanism for grouping a series of database changes into one
logical operation. SQL Server keeps track of each transaction in a file called the
transaction log. This log file usually has the extension .LDF.

Database Objects and Key constraints:


The Most basic database objects:

TABLE: It is made up of what is called domain data (columns) and entity data (rows). The actual data
for the database is stored in the tables.
Indexes: An index is an object that exists only within the framework of a
particular table or View. An index works muck like the index in the book.
Constraints: A constraint is yet another object that exists only within a table. Constraints confine the
data in your table to meet certain conditions.
Views: A view is something of a virtual table. A view, for the most part, is used just like a table, except
that it doesnt contain any data of its own. Instead, a view is merely a preplanned mapping and
representation of the data stored in tables. The plan is stored in the database in the form of a
query.

Database Objects and Key constraints:


Stored Procedures:
A Stored procedures are generally an ordered series of Transact-SQL (the language used to query
Microsoft SQL Server) statements bundled up into a single logical unit. They allow for variables and
parameters as well as selection and looping constructs.
Triggers:
A trigger is an object that exists only within the framework of a table. Triggers are pieces of logical
code that are automatically executed when certain things, such as inserts, updates, or deletes
happen to your table.

SQL Statements
SQL Commands:
SQL commands are instructions used to communicate with the database to perform
specific task that work with data. SQL commands can be used not only for searching the
database but also to perform various other functions like, for example, you can create
tables, add data to tables, or modify data, drop the table, set permissions for users. SQL
commands are grouped into four major categories depending on their functionality:
Data Definition Language (DDL) - These SQL commands are used for creating,
modifying, and dropping the structure of database objects. The commands are CREATE,
ALTER, DROP, RENAME, and TRUNCATE.
Data Manipulation Language (DML) - These SQL commands are used for storing,
retrieving, modifying, and deleting data. These commands are SELECT, INSERT, UPDATE,
and DELETE.
Transaction Control Language (TCL) - These SQL commands are used for managing
changes affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
Data Control Language (DCL) - These SQL commands are used for providing security
to database objects. These commands are GRANT and REVOKE.

SQL STATEMENTS

Most of the actions that we need to perform are on a database with SQL
statements.
SQL statements are not case sensitive and the following SQL statements
are equivalent:
SELECT * FROM SALESLT.CUSTOMER;
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.

DISTINCT, TOP, ORDER BY, WHERE, INSERT INTO, SELECT *


INTO, LIKE, IN, IS NULL, BETWEEN, EXISTS
Wild Char/Operators: Like, IN, BETWEEN, AND, OR
Functions: Len, Substring, Replace, Ltrim, Rtrim, Ascii, char.
Agg Function: count, sum, avg, min, max
ADVANCED SQL

GROUP BY, HAVING


Alias
UNION, UNION ALL

SQL Statements
The SQL SELECT Statement: is used to select the data from a database.

SELECT * FROM S_Customer


--- how to select specific columns --
The SQL DISTINCT Statement: The DISTINCT key word can be used to return
only distinct (different) values.
CREATE TABLE TEST(ID INTEGER,VNAME VARCHAR(20));
INSERT INTO TEST VALUES(2,'TEJAS');
SELECT * FROM TEST;
SQL WHERE Clause: The WHERE clause is used to extract only those records
that fulfill a specified criterion.

Syntax: SELECT * FROM S_CUSTOMER WHERE CustomerID = 10

Sql uses single quotes around text values, for numeric values should not be
enclosed.

SQL Statements
Operators allowed in the WHERE Clause
The AND & OR Operators:
The AND operator displays a record if both the first condition and the second condition
is true.
The OR operator displays a record if either the first conditions or the second condition is
true.

Show Examples;
The ORDER BY keyword: The order by key word is used to sort the result-set by a
specified column. It does in ascending and descending order.

Show Examples:
The INSERT INTO Statement: it is used to insert a new row in a table.

Show Example:

The UPDATE Statement: The UPDATE statement is used to update existing records in
a table.

Show Example:
---- show it with where cluase --!Warning of WHERE clause to update the records in DB.

SQL Statements
The DELETE Statement: the DELETE statemetn is used to delete rows in a table.

--- Show with where clause, all , specific records

Note: Be very careful when deleting records with DELETE statement, you cannot undo
this statement.
SQL TOP clause: The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of records.
Returning a large number of records can impact on performance.

SELECT TOP 10 * FROM S_CUSTOMER


Examples with different data.
---- how do you show third highest salaried emp ---The LIKE Operator: the LIKE operator is used to search for specified pattern in a
column.

SELECT * FROM S_Customer WHERE Suffix LIKE 'Jr.'

SQL Statements
SQL IN Operator: The IN Operator allows you to specify multiple values in
Where Clause.
SQL BETWEEN Operator: The BETWEEN operator selects range of data
between two values. The values can be numbers, text or dates.

SELECT * FROM EMP WHERE SAL NOT BETWEEN 1000 AND 10000
SQL Alias: You can give a table or a column another name by using an alias. This
can be a good thing to do If you have very long or complex table names or
column names.

Example:
------ Alias --SELECT * FROM DEPT
SELECT DEPT_ID, DEPT_NAME AS DEPARTMENT_NAME FROM DEPT
SELECT * FROM EMP_DETAILS
SELECT E.EMP_ID, E.FIRST_NAME, E.SALARY, D.DEPT_NAME FROM EMP_DETAILS E

SQL DDL Statements


SQL DROP:
The SQL DROP command is used to remove an object from the database. If you
drop a table, all the rows in the table is deleted and the table structure is
removed from the database. Once a table is dropped we cannot get it back, so
be careful while using DROP command. When a table is dropped all the
references to the table will not be valid.
The DROP TABLE Statement
The DROP TABLE statement is used to delete a table.
DROP TABLE table_name
SELECT * FROM SYS.OBJECTS WHERE TYPE = U
The DROP DATABASE Statement
The DROP DATABASE statement is used to delete a database.
DROP DATABASE database_name
The TRUNCATE TABLE Statement
What if we only want to delete the data inside the table, and not the table itself?
Then, use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name

SQL DDL/DML Statements


What is the differences between DELETE and TRUNCATE?
If a table is dropped, all the relationships with other tables will no longer be valid, the
integrity constraints will be dropped, grant or access privileges on the table will also be
dropped, if want use the table again it has to be recreated with the integrity constraints,
access privileges and the relationships with other tables should be established again. But,
if a table is truncated, the table structure remains the same, therefore any of the above
problems will not exist.
In case of TRUNCATE ,Trigger doesn't get fired. But in DML commands like
DELETE .Trigger get fired.
TRUNCATE is DDL statement where as DELETE is DML statement.
SQL NULL Values:
If a column in a table is optional, we can insert a new record or update an existing record
without adding a value to this column. This means that the field will be saved with a NULL
value.
NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.
Note: It is not possible to compare NULL and 0; they are not equivalent.

SQL FUNCTIONS
SQL DATE function:
SELECT

SELECT
SELECT
SELECT
SELECT
SELECT

SELECT
SELECT
SELECT

GETDATE() it returns system date.

SELECT
SELECT
SELECT
SELECT

DATEADD(MONTH, 1, '2006-08-30') -- month is added to the given date.


DATEADD(YEAR, 1, '2006-08-30') -- year is added to the given date.
DATEADD(DAY, 1, '2006-08-30') - day is added to the given date.
DATEADD(WEEK, 1, '2006-08-30') week days added to the given date.

DATEDIFF(YEAR,'2010-04-02','2011-02-04') -- shows No of years diff


DATEDIFF(MONTH,'2010-04-02','2011-02-04') -- shows No of months diff
DATEDIFF(day,'2010-04-02','2011-02-04') -- shows no of days diff
DATEDIFF(WEEK,'2010-04-02','2011-02-04') -- shows no of WEEKS diff
DATEDIFF(HOUR,'2010-04-02','2011-02-04') -- shows no of HOWRS diff
MONTH('2011-10-02') shows the month from the given date
DAY('2011-10-02') -- shows the day from the given date
YEAR('2011-10-02') -- shows the year from the given date

SQL FUNCTIONS
SQL Aggregate functions:
SQL Aggregate functions: SQL has many built-in functions for performing
calculations on data.
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:

AVG() - Returns the average value


COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum

Show Examples for every function

Use full string functions.


ASCII()
Returns the ASCII code value of the leftmost character of a character expression.
Syntax : ASCII(String expression)
Ex: select ASCII('A') It returns 65.
CHAR()
Converts an int ASCII code to a character.
Syntax
CHAR(Integer)
Ex: select CHAR(65) It returns A
LEFT()
Returns the left most characters of a string.
Syntax LEFT(string, length) string
Specifies the string from which to obtain the left-most characters.
length Specifies the number of characters to obtain.
Example : SELECT LEFT('Marufuzzaman',5) OutPut Maruf
RIGHT()
Returns the right most characters of a string.
Syntax RIGHT(string, length) string
Specifies the string from which to obtain the left-most characters.
length
Specifies the number of characters to obtain.
Example :
SELECT RIGHT('Md. Marufuzzaman',12) OutPut Marufuzzaman

Use full string functions.


LTRIM() - Returns a character expression after it removes leading blanks.
Example : SELECT LTRIM(' Md. Marufuzzaman') OutPut Md. Marufuzzaman
RTRIM() - Returns a character string after truncating all trailing blanks.
Example : SELECT RTRIM('Md. Marufuzzaman ') OutPut Md. Marufuzzaman
REPLACE()
Returns a string with all the instances of a substring replaced by another substring.
Syntax REPLACE(find, replace, string)
Find Specifies the string that contains the substring to replace all instances of with another.
Replace Specifies the substring to locate.
String Specifies the substring with which to replace the located substring.
Example : SELECT REPLACE('The codeProject is ?.','?', 'your development resource')
LET() -Len is a function which returns the length of a string.
Syntax
LEN(String)
Example: SELECT LEN('Hi to everyone')
SUBSTRING - Substring returns the part of the string from a given characterexpression. The general
syntax of Substring is as follows :
SUBSTRING(expression, start, length)

SQL Group By clause


The GROUP BY Statement:
The GROUP BY statement is used in conjunction with the aggregate functions to
group the result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
SQL GROUP BY Example
EXISTS: Specifies a subquery to test for the existence of rows.
It returns Boolean value 0/1
SELECT * FROM EMP WHERE EXISTS(SELECT DEPTNO FROM EMP WHERE DEPTNO
IS NULL)
Comparing queries by using EXISTS
SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP AS E
WHERE EXISTS (SELECT * FROM DEPT AS D WHERE E.DEPTNO = D.DEPTNO)

SQL HAVING Clause


Having clause is used to filter data based on the group functions. This is similar to
WHERE condition but is used with group functions. Group functions cannot be used in
WHERE Clause but can be used in HAVING clause.
For Example: If you want to select the department that has total salary paid for its
employees more than 25000, the sql query would be like;
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000
The output would be like:
Dept Salary
Electronics
55000
Aeronautics 35000
InfoTech
30000
When WHERE, GROUP BY and HAVING clauses are used together in a SELECT
statement, the WHERE clause is processed first, then the rows that are returned after
the WHERE clause is executed are grouped based on the GROUP BY clause. Finally,
any conditions on the group functions in the HAVING clause are applied to the
grouped rows before the final output is displayed.

INSERT INTO SELECT/SELECT INTO


SELECT INTO: This method is used when table is not created earlier and needs to be created
when data from one table is to be inserted into newly created table from another table. New
table is created with same data types as selected columns. This is specifically used when we
need to create back up tables.
SELECT INTO EMPLOYEE_DETAILS FROM EMPLOYEES
INSERT INTO SELECT: This method is used when table is already created in the database
earlier and data is to be inserted into this table from another table. If columns listed in insert
clause and select clause are same, they are not required to list them.
Example #1:
USE TestDB;

CREATE TABLE EMP1 (EMP_ID INT, Company varchar(20), Last_Name Varchar(20), Job_Title
varchar(30),
Home_Phone varchar(20));
SELECT * FROM Employees;
INSERT INTO EMP1 SELECT ID, Company, [Last Name], [Job Title], [Home Phone] from
Employees;

INSERT INTO SELECT


Example #2:
USE TestDB;

SELECT * FROM [Order Details]; SELECT * FROM Employees; SELECT *


FROM ORDERS
SELECT * FROM Products; SELECT * FROM Customers
CREATE TABLE ORDERS_PROD_DETAILS(ORDER_ID INT, EMP_NAME VARCHAR(20), CUST_NAME
VARCHAR(25), PROD_NAME VARCHAR(60), ORDER_DATE DATE, QUANTITY DECIMAL (10,4), UNIT_PRICE DECIMAL
(6,2))
INSERT INTO ORDERS_PROD_DETAILS SELECT ORS.[Order ID],EM.[First Name] AS EMP_NAME,
CU.[First Name] CUST_NAME, PR.[Product Name], ORS.[Order Date], ORD.Quantity, ORD.[Unit Price]
FROM Orders ORS
INNER JOIN EMPLOYEES EM
ON ORS.[Employee ID]= EM.ID
INNER JOIN Customers CU
ON ORS.[Customer ID] = CU.ID
INNER JOIN [Order Details] ORD
ON ORS.[Order ID] = ORD.[Order ID]
INNER JOIN Products PR
ON ORD.[Product ID] = PR.ID

SQL Indexes
Indexes: indexes in SQL server are similar to index in a book. SQL Server has
two main types of indexes: clustered and nonclustered. They both help the
query engine get at data faster, but they have different effects on the storage of
the underlying data. Indexes are used to improve the performance of quires.

Indexes are generally created for following columns.


Primary key column
Foreign key column: Frequently used in join conditions
Column which are frequently used in where clause
Columns which are used to retrieve the data in sorting order

Indexes are cannot be created for following columns


The columns which are not frequently used in where clause.
Columns containing the duplicate and NULL values.
Columns containing images, binary information, and text information.
Type of Indexes:
Cluster Index.
Non-Cluster Index.

SQL Indexes
Clustered Indexes: Clustered indexes sort and store the data rows for a table, based
on the columns defined in the index. An important characteristic of the clustered index
is that the indexed values are sorted in either ascending or descending order. As a
result, there can be only one clustered index on a table or view. In addition, data in a
table is sorted only if a clustered index has been defined on a table.
Ex: CREATE CLUSTERED INDEX CI ON EMP(EMPNO)
DROP INDEX EMP.CI
Non-clustered indexes:
Nonclustered indexes cannot be sorted like clustered indexes; however, you can
create more than one nonclustered index per table or view. SQL Server 2005 supports
up to 249 nonclustered indexes, and SQL Server 2008 support up to 999. This certainly
doesnt mean you should create that many indexes. Indexes can both help and hinder
performance.

Key constraints
Integrity:
Enforcing data integrity ensures the quality of the data in the database. For example, if an
employee is entered with an employee_id value of 123, the database should not allow
another employee to have an ID with the same value. If you have an employee_rating
column intended to have values ranging from 1 to 5, the database should not accept a
value of 6. If the table has a dept_id column that stores the department number for the
employee, the database should allow only values that are valid for the department numbers in the
company.
Types of Integrity:
How integrity is enforced depends on the type of integrity being enforced. The types of data integrity
are domain, entity and referential integrity.
Domain Integrity: Domain integrity controls the validation of values for a column. You can use domain
integrity to enforce the type, format, and possible values of data stored in a column. SQL Server
provides several mechanisms to enforce domain integrity:
You can control the type of data stored in a column by assigning a data type
to the column.
You can use CHECK constraints and rules to control the format of the data.
You can control the range of values stored in a column by using FOREIGN
KEY constraints, CHECK constraints, DEFAULT definitions, NOT NULL
definitions, and rules.

Database Objects and Key constraints:


Entity Integrity:
Entity integrity requires that all rows in a table be unique. You can enforce entity integrity in SQL Server
by using PRIMARY KEY constraints, UNIQUE constraints, and IDENTITY properties.
Referential Integrity:
Referential integrity preserves the defined relationships between tables. You can define such a
relationship in SQL Server by relating foreign key columns on one table to the primary key or
unique key of another table. When it is defined, referential integrity ensures that values inserted in
the foreign key columns have corresponding values in the primary table. It also controls changes to
the primary key table and ensures that related foreign key rows are not left orphaned.
KEY CONSTRINTS
Key constraints are: PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULTare the
primary method used to enforce data integrity.

Database Objects and Key constraints:


PRIMARY KEY: A Primary Key constraint is a unique identifier for a row within a database.
Every table should have a primary key constraint to uniquely identify each
row in a table.
Only one primary key constraint can be created for each table.
A Primary key constraint column must be defined as NOT NULL.
The primary key constraints are used to enforce the entity integrity.
By default on primary key column Cluster index is crated.
SP_HELP S_Customer
UNIQUE KEY: The UNIQUE constraint is functionally similar to PRIMARY KEY. But unlike PRIMARY
KEY, it allows nulls in the columns that participate in the UNIQUE constraint.
The value of NULL is considered a unique value, so only one row can be with NULL under UNIQUE
column. By default on UNIQUE KEY column Non-Clustored index is created.
Differences between Primary Key and Unique Key:
1)

By default Primary Key will generate Clustured Index whereas Unique Key will Generate NonClustured Index.
2) Primary Key is a combination of Unique and NOT NULL Constraints so it cant have duplicate values
or any Null Whereas for Oracle UNIQUE Key can have any number of NULL whereas for SQL
Server It can have only one NULL
3) A table can have only one PK but It can have any number of UNIQUE Key.

Database Objects and Key constraints:

FOREIGN KEY (Referential Integrity Constraint): Relationships are maintained and enforce via referential
integrity. FOREIGN KEY constraints are the declarative means for enforcing referential integrity in SQL
Server.
You implement FOREIGN KEY constraint by relating one or more columns in a table to the columns in a
primary key or unique index. The columns in the referencing table can be referred to as foreign key
column.
Values in the foreign key columns must have a corresponding value in the
primary table. If the new values in the foreign key columns do not exist in
the primary table, the insert or update operation fails.
Values in the primary key or unique index that are referenced by the foreign
key table cannot be deleted. If an attempt is made to delete a referenced
value in the primary table, the delete fails.
Values in the primary key that are referenced by the foreign
key table cannot be modified. If an attempt is made to change a referenced
value in the primary table, the update fails.
Ex: Draw a table and show.

Database Objects and Key constraints:


DEFAULT: A Default provides a value for a column when a value is not supplied in INSERT statement. Default
can be anything constant.
A column can have only one DEFAULT definition.
A DEFAULT definition can contain constant values, functions. A DEFAULT
cannot refer to another column in the table, or to other tables,
views, or stored procedures.
DEFAULT definitions cannot be created on columns with a timestamp data
type or columns with an IDENTITY property.

definition

CREATE TABLE ABC(


PNAME VARCHAR (20),
EMP_TYPE VARCHAR(1) CONSTRAINT EMPTYPE DEFAULT 'F')
ALTER TABLE ABC ADD CONSTRAINT EMPTYPE DEFAULT GETDATE() FOR EMP_TYPE
INSERT ABC VALUES('RAJESH','F')
INSERT ABC VALUES('RAJESH1',DEFAULT)
SELECT * FROM ABC
DROP TABLE ABC
Composite Primary Key:
Multiple Columns set with One Primary key refers to Composite Primary Key.
Behaviour of Composite Primary Key that it will allow One column Store Duplicates only
when the corresponding column contains Unique Data.
Composite Primary Key can be created Minimum of 2 and Maximum of 16 Columns
CREATE TABLE track( album CHAR(10) NOT NULL, dsk INTEGER NOT NULL, posn INTEGER NOT
NULL, song VARCHAR(255), PRIMARY KEY (album, dsk, posn))

Database Objects and Key constraints:


IDENTITY: Identity is an auto increment value, this is assigned only to the integer fields.
CREATE TABLE TEST_DEFAULT
(ID INT IDENTITY NOT NULL,
PASSWORD CHAR(13) NOT NULL DEFAULT 'DEFAULTPW'
)
INSERT TEST_DEFAULT VALUES(DEFAULT,DEFAULT)
INSERT TEST_DEFAULT VALUES(DEFAULT)
SELECT * FROM TEST_DEFAULT
DROP TABLE TEST_DEFAULT
Show the difference of DELETE and TRUNCATE ON IDENTITY column

Database Objects and Key constraints:


CHECK:
NOT NULL:This constraint ensures all rows in the table contain a definite value for the column which is
specified as not null. Which means a null value is not allowed.
Syntax to define a Not Null constraint:
[CONSTRAINT constraint name] NOT NULL
For Example: To create a employee table with Null value, the query would be like
CREATE TABLE employee
( id number(5),
name char(20) CONSTRAINT nm_nn NOT NULL,
dept char(10), age number(2), salary number(10), location char(10) );
SQL NULL Values:
If a column in a table is optional, we can insert a new record or update an existing record without
adding a value to this column. This means that the field will be saved with a NULL value.
NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.
Note: It is not possible to compare NULL and 0; they are not equivalent.

Database Objects and Key constraints:


SQL Check Constraint :
This constraint defines a business rule on a column. All the rows must satisfy this rule. The constraint
can be applied for a single column or a group of columns.
Syntax to define a Check constraint:
[CONSTRAINT constraint_name] CHECK (condition)
For Example: In the employee table to select the gender of a person, the query would be like
Check Constraint at column level:
CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
gender char(1) CHECK (gender in ('M','F')),
salary number(10),
location char(10) );

Transactions
TCL: Transaction Control
BEGIN TRANSACTION
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can
later roll back
ROLLBACK - restore database to original since the last COMMIT

SQL JOINS
JOINS: Joins are used to retrieve data from tow or more tables into one
result set by using the various forms of the JOIN clause. These will include
1) INNER JOIN
2) OUTER JOIN
LEFT OUTER JOIN
RIGHT OUT JOIN
3) CROSS JOIN.
4) SELF JOIN

How exactly does a JOIN put the information from two tables into a single
result set? Well, that depends on how you tell it to put the data together
thats why there are four different kinds of JOINs. (draw pic)
INNER JOINs: INNER JOINs are the most common kind of JOIN. They match
records together based on one or more common fields, as do most JOINs,
but an INNER returns only the records where there are matches for
whatever fields you have said are to be used for the JOIN.
SYNTAX:
SELECT <select list> FROM <first_table> <join_type>
<second_table>
[ON <join_condition>]

SQL JOINS
USE NORTHWIND DB
SELECT * FROM Products
INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID
The SupplierID column appears twice, but theres nothing to say which one is
from which table.
All columns were returned from both tables.
The first columns listed were from the first table listed.
As for all columns being returned from both tables, that is as expected as we
used the * operator.
You can specify from which table we need all the columns like
SELECT Products.*, Suppliers.CompanyName FROM Products
INNER JOIN Suppliers
ON Products.SupplierID = Suppliers.SupplierID
When we run the below query we get an error:
SELECT Products.*, CompanyName FROM Products
INNER JOIN Suppliers

SQL JOINS
When we want to refer to a column where the column name exists more than
once in our JOIN result, we must fully qualify the column name. We can do this
in one of two ways:
Provide the name of the table that the desired column is from, followed by a
period and the column name (Table.ColumnName)
Alias the tables, and provide that alias, followed by a period and the column
name (Alias.ColumnName)

SELECT p.*, s.SupplierID FROM Products p


INNER JOIN Suppliers s
ON p.SupplierID = s.SupplierID
SELECT p.ProductID, s.SupplierID, p.ProductName, s.CompanyName
FROM Products p
INNER JOIN Suppliers s
ON p.SupplierID = s.SupplierID
WHERE p.ProductID < 4

SQL JOINS
---- Can you show me all the customers who have placed
orders with us? ---
SELECT DISTINCT c.CustomerID, c.CompanyName
FROM Customers c
INNER JOIN Orders o
ON c.CustomerID = o.CustomerID

Run the below query and show the diff because of DISTINT

SELECT COUNT(*) AS No. Of Records FROM Customers

SQL JOINS
The Simple OUTER JOIN
Syntax:

SELECT <SELECT list>


FROM <the table you want to be the LEFT table>
<LEFT|RIGHT> [OUTER] JOIN <table you want to be the RIGHT table>
ON <join condition>
the table that comes before the JOIN keyword is considered to be the LEFT table, and
the table that comes after the JOIN keyword is considered to be the RIGHT table.
A LEFT OUTER JOIN includes all the information from the table on the left, and a RIGHT
OUTER JOIN includes all the information from the table on the right.

LEFT JOIN:
SELECT CUS.ID, CUS.Company, CUS.[JOB TITLE],CUS.[Business Phone], CUE.[Contact
Name]
FROM Customers CUS
LEFT OUTER JOIN [Customers Extended] CUE ON CUS.ID = CUE.ID
RIGHT JOIN:
SELECT CUS.ID, CUS.Company, CUS.[JOB TITLE],CUS.[Business Phone], CUE.[Contact
Name]
FROM Customers CUS
RIGHT OUTER JOIN [Customers Extended] CUE ON CUS.ID = CUE.ID

SQL JOINS
CROSS JOINs are very strange critters indeed. A CROSS JOIN differs from other JOINs in
that there is no ON operator, and that it joins every record on one side of the JOIN with
every record on the other side of the JOIN. In short, you wind up with a Cartesian
product of all the records on both sides of the JOIN.

The syntax is the same as any other JOIN except that it uses the keyword CROSS
(instead of INNER, OUTER), and that it has no ON operator. Heres a quick example:
SELECT v.VendorName, a.Address
FROM Vendors v
CROSS JOIN Address a

SELF JOIN: A Self Join is a type of sql join which is used to join a table to itself,
particularly when the table has a FOREIGN KEY that references its own PRIMARY KEY. It is
necessary to ensure that the join statement defines an alias for both copies of the table
to avoid column ambiguity

SQL UNION & UNION ALL


UNION:
A UNION isnt really a JOIN, like the previous options weve been looking atinstead its
more of an appending of the data from one query right onto the end of another query.
Where a JOIN combined information horizontally (adding more columns), a UNION
combines data vertically (adding more rows).
SELECT * FROM Customers
UNION
SELECT * FROM Customers
UNION ALL:
SQL UNION ALL is combine the results of two queries together without filter out the
same value(no distinct behavior).
The difference between UNION ALL and UNION is UNION only selects distinct values and
UNION ALL selects all values.
Syntax - (SQL Statement 1)
UNION ALL
(SQL Statement 2)
SELECT * FROM Customers
UNION ALL
SELECT * FROM Customers

SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or
more tables can be seen. Views do not contain data of their own. They are used to restrict
access to the database or to hide data complexity. A view is stored as a SELECT statement in
the database. DML operations on a view like INSERT, UPDATE, DELETE affects the data in the
original table upon which the view is based.
Syntax: CREATE VIEW <view_name> AS
SELECT column_list FROM table_name [WHERE condition];
The SELECT statement is used to define the columns and rows that you want to
display in the view.
Restrict a user to specific rows in a table. For example, allow an employee to see only
the rows recording his or her work in a labor-tracking table.
Restrict a user to specific columns. For example, allow employees who do not work in
payroll to see the name, office, work phone, and department columns in an employee table,
but do not allow them to see any columns with salary information or personal information.
Join columns from multiple tables so that they look like a single table.
Aggregate information instead of supplying details. For example, present the sum of a
column, or the maximum or minimum value from a column.

SQL Procedure
A stored procedure is one or more SQL commands stored in a database as an executable object. Stored procedures can be called interactively, from within client application code, from
within other stored procedures, and from within triggers.
Parameters can be passed to and returned from stored procedures to increase their usefulness and flexibility.
What is the difference between Function and Stored Procedures?
1.
2.
3.
4.
5.
6.

Function is mainly used in the case where it must return a value. Where as a procedure may or may not return a value or may return more than one value using the OUT parameter.
Function can be called from SQL statements where as procedure can not be called from the sql statements .
Functions are normally used for computations where as procedures are normally used for executing business logic.
Function returns 1 value only. Procedure can return multiple values (max 1024).
Stored procedure returns always integer value by default zero. where as function return type could be any output value or table values.
Stored procedure is precompiled execution plan where as functions are not.

--QUERY TO SELECT COUNT OF ALL OBJECTS (TABLES,VIEW ETC )IN SQLSERVER DB

SYSOBJECT TYPES

SELECT XTYPE, COUNT(XTYPE) NOOFOBJECTS FROM SYSOBJECTS GROUP BY XTYPE

Object type:

AF = Aggregate function (CLR)


D = DEFAULT (constraint or stand-alone)
FN = SQL scalar function
FT = Assembly (CLR) table-valued function
IT = Internal table
PK = PRIMARY KEY constraint
S = System base table
TR = SQL DML trigger
U = Table (user-defined)
V = View
QUERY: SELECT * FROM SYSOBJECTS WHERE TYPE = V

C = CHECK constraint
F = FOREIGN KEY constraint
FS = Assembly (CLR) scalar-function
IF = SQL inline table-valued function
P = SQL Stored Procedure
R = Rule (old-style, stand-alone)
SQ = Service queue
TT = Table type
UQ = UNIQUE constraint

--FIND OUT ROWS COUNT IN ALL TABLES OF SQLSERVER DB


SELECT * FROM SYSINDEXES
SELECT T.NAME AS TABLE_NAME, R.ROWCNT AS ROW_COUNT
FROM SYSOBJECTS T, SYSINDEXES R
WHERE T.ID = R.ID
AND INDID IN(0,1)
AND T.XTYPE='U'
ORDER BY T.NAME
-- FRAME QUERIES FOR MULTIPLE TABLES
SELECT 'SELECT * INOT ' + NAME + '_BKUP' FROM SYSOBJECTS WHERE TYPE = 'U'

SYSOBJECT TYPES

SYSOBJECT TYPES

--QUERY TO RETURN ALL THE TABLES CONTAINING SPECIFIC COLUMN ALONG WITH THEIR SCHEMA NAME
SELECT T.NAME AS TABLE_NAME,
SCHEMA_NAME(SCHEMA_ID) AS SCHEMA_NAME,
C.NAME AS COLUMN_NAME
FROM SYS.TABLES AS T
INNER JOIN SYS.COLUMNS C ON T.OBJECT_ID = C.OBJECT_ID
WHERE C.NAME LIKE '%_ID'
ORDER BY SCHEMA_NAME, TABLE_NAME;
--QUERY TO LIST THE COLUMNS WHICH ARE HAVING PRIMARY KEY CONSTRAINT FOR ALL THE TABLES IN A DB
SELECT I.NAME AS INDEXNAME,
OBJECT_NAME(IC.OBJECT_ID) AS TABLENAME,
COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID) AS COLUMNNAME
FROM SYS.INDEXES AS I
INNER JOIN SYS.INDEX_COLUMNS AS IC
ON I.OBJECT_ID = IC.OBJECT_ID
AND I.INDEX_ID = IC.INDEX_ID
WHERE I.IS_PRIMARY_KEY = 1
--QUERY TO LIST THE COLUMNS WHICH ARE HAVING FORIEGN KEY CONSTRAINT FOR ALL THE TABLES IN A DB
SELECT F.NAME AS FOREIGNKEY,
OBJECT_NAME(F.PARENT_OBJECT_ID) AS TABLENAME,
COL_NAME(FC.PARENT_OBJECT_ID,
FC.PARENT_COLUMN_ID) AS COLUMNNAME,
OBJECT_NAME (F.REFERENCED_OBJECT_ID) AS REFERENCETABLENAME,
COL_NAME(FC.REFERENCED_OBJECT_ID,
FC.REFERENCED_COLUMN_ID) AS REFERENCECOLUMNNAME
FROM SYS.FOREIGN_KEYS AS F
INNER JOIN SYS.FOREIGN_KEY_COLUMNS AS FC
ON F.OBJECT_ID = FC.CONSTRAINT_OBJECT_ID

--QUERY TO DELETE DUPLICATE RECORDS FROM A TABLE. Only works on Oracle not on SQL and to do in SQL use SELF join.
DELETE FROM <TABLE_NAME> WHERE ROWID<(SELECT MAX(ROWID) FROM <TABLENAME>)
--QUERY TO GET LIST OF VIEWS WITH VIEW DEFINITION QUERY
SELECT * FROM INFORMATION_SCHEMA.VIEWS
-- QUERY TO GET LIST OF SYSTEM TABLES
SELECT * FROM SYS.OBJECTS WHERE TYPE='S
--QUERY TO GET LIST OF USER TABLES
SELECT * FROM SYS.OBJECTS WHERE TYPE='U'
QUERY TO GET LIST OF STORE PROCEDURES
SELECT * FROM SYS.OBJECTS WHERE TYPE='P'
--TO DISPLAY THE STRUCTURE OF TABLE
SP_HELP <TABLE NAME>
--TO DISPLAY THE STRUCTURE OF VIEW
SP_HELP <VIEW NAME>
--TO DISPLAY THE VIEW DEFINITION QUERY
SP_HELPTEXT <VIEW NAME>
--TO DISPLAY THE CODE OF STORED PROCEDURE
SP_HELPTEXT <STORED PROCEDERE NAME>
--TO EXECUTE THE STOREPROCEDURE FROM SQL SERVER QUERY WINDOW
EXEC <SP NAME> <PARAMETERS>

RENAME THE OBJECTS


How do you rename a database?
SP_RENAMEDB <OLDNAME>, <NEW NAME>
How do you rename a table?
SP_RENAME <OLD NAME>, <NEW NAME>
How do you rename a table column?
SP_RENAME <TABLENAME.COLUMOLDNNAME>, <TABLE NAME.NEW NAME>
How do you find string in deployed database objects?
SELECT * FROM SYSCOMMENTS WHERE TEXT LIKE '%LOG%'
SELECT NAME, TYPE_DESC FROM SYS.OBJECTS WHERE OBJECT_ID IN(SELECT ID
FROM SYSCOMMENTS WHERE TEXT LIKE '%LOG%')
Where the Database user logins and passwords and principals are stored.
select * FROM sys.server_principals
select * from sys.sql_logins

BCP & SP_UPDATESTATS


When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a
large amount of deletions any modification or Bulk Copy into the tables has
occurred, it has to update the indexes to take these changes into account.
UPDATE_STATISTICS updates the indexes on these tables accordingly.
EXEC SP_UPDATESTATS
BCP (BULK COPY): BCP utility is used to insert the data into a table or extract the
data into a .txt file from a database table.
BCP IN:
BCP TESTDB.DBO.ORDERS1 IN C:\TEMP\ORDERS.TXT -c -m1 1 -e
C:\TEMP\BCP_ERR.TXT -o C:\BCPOUT.TXT -SSYS\DIVIJA -T
BCP TESTDB.DBO.ORDERS1 IN C:\TEMP\ORDERS.TXT -c -m1 -SSYS\DIVIJA T
BCP OUT:
BCP TESTDB.DBO.ORDERS1 OUT C:\TEMP\ORDERS.TXT -c -m1 -SSYS\DIVIJA T

UTILITIES

SQL Logins
You can create sql USERs and maintain passwords and resolve lockout problems.
SQL Server Logs
View the SQL Server error log by using SQL Server Management Studio or any text
editor. By default, the error log is located at
Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files.
Linked Server Objects
A linked server configuration enables SQL Server to execute commands against OLE
DB data sources on remote servers. Linked servers offer the following advantages:
Remote server access.
The ability to issue distributed queries, updates, commands, and transactions on
heterogeneous data sources across the enterprise.
SQL Profiler:
Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for
monitoring an instance of the Database Engine or Analysis Services. You can capture and
save data about each event to a file or table to analyze later. For example, you can monitor
a production environment to see which stored procedures are affecting performance by
executing too slowly.
To run SQL Server Profiler, on the Start menu, point toAll Programs, Microsoft SQL
Server 2008, Performance Tools, and then click SQL Server Profiler.

SQL SERVER LOCKS

SQL Server locks resources using different lock modes that determine how
the resources can be accessed by concurrent transactions.
SQL Server uses these resource lock modes.
Shared (S):
Used for operations that do not change or update data (read-only
operations), such as a SELECT statement.
Update (U)
Used on resources that can be updated. Prevents a common form of deadlock
that occurs when multiple sessions are reading, locking, and potentially updating
resources later.
Exclusive (X)
Used for data-modification operations, such as INSERT, UPDATE, or DELETE.
Ensures that multiple updates cannot be made to the same resource at the same
time.
Schema
Used when an operation dependent on the schema of a table is executing.
The types of schema locks are: schema modification (Sch-M) and schema stability
(Sch-S).
Bulk Update (BU)
Used when bulk-copying data into a table and the TABLOCK hint is specified.

SQL SERVER LOCKS

What is Dead lock?


is a situation when two processes, each having a lock on
one piece of data, attempt to acquire a lock on the others piece.
Each process would wait indefinitely for the other to release the
lock, unless one of the user processes is terminated.
SQL Server detects deadlocks and terminates one users process.

Database Testing
Testing Life Cycle:
Documents acquiring
Functional specification document.
Overall system design document
Database design specification document and Data Model Diagrams.
All reviews are done and frozen.
Prepare Test Plan
Prepare Test cases for Front end and Back end testing.
Get this reviewed and final approvals.
Prepare the test environment.
Prepare the Test data.
Deployment in QA & deployment validation
DB Validations as said in the doc:
Database validation
Database Objects verification with check list
Columns and Names
Data Type and Size Test
Data Integrity Test
Indexes creation
Do a Sanity round of testing.
Functional testing, If components are there, do it as component wise.

Database Testing
Testing Life Cycle:
Queries Validation (querying database tables, views)
Procedures Validation (individual- Test Coverage)
Performance Testing.
Regression Testing.
Validate if any scheduled jobs.
Integration/End to End testing.
QA Signoff
Test summary Reports
Bugs Status Report.
Database scripts with deployment scripts
Source locations
If QA notes, that should be mentioned.

Database Testing
Functional Testing:
Table level validations: Verify the following points and find out the differences
between specification and actual tables in database.
all table names
Column names for each table.
Column types for each table.
Whether a column allows NULL or not.
Default definitions.
Rule definitions.
Keys and Indexes: Verify the following points and compare with design
specification.
primary Key for each table (Every table should have primary key).
Foreign keys.
Column data types between Primary key and foreign key column and
that are present different tables.
Indexes, clustered or non-clustered

Every Stored Procedure is to be tested separately for its functionality (Based on separate functions it performs).
Stored procedures need to be broken up into action items based on functions and then each action needs to be tested separately as the results of complete Stored Procedure
Execution may differ from the results obtained by partial execution. This also helps in validating the modularity
In the case of stored procedures, to come up with test cases one can consider the following things:
The
The
The
The

Number of arguments being passed.


data type of each of the argument being passed.
order of the arguments being passed.
return type

Based on these, you can write both negative and positive test cases

STORED PROCEDURE TEST

SQL PROCEDURE TEST


Test Coverage Criterion: Each and every procedure must be tested at least
once.
Individual Procedures test: Verify the following things and compare them with
design specification document.
Whether a stored procedure is installed in database
Stored Procedure name
Parameter names, parameter types and the number of parameters.
Check is that appropriate comments has been used in the procedure.
Outputs:
When output is zero (o rows affected)
Output contains many records.
Write simple queries to see if a stored procedure populates right data.
Parameters:
Check the parameters if they are required.
Call stored procedure with valid data.
Make each parameter invalid a time and run a procedure and see is that
giving appropriate user informative message or not.
Return Values:
When a stored procedure returns a 0, it is successful execution.

SQL PROCEDURE Test


Logging:
Check is that procedure execution is having log and information is
adequate.
Check is that procedure is capturing correct error message when fails.
Check is that error handling is present or not (checking out any
exception that
doesnt have a predefined error message)
Debug:
How to run a procedure in debug mode.
Look into a procedure code and make sure major branches are test
covered.

THANK YOU!

You might also like