leading software technologies chennai

226
Leading Software Technologies Chennai

Upload: gudrun

Post on 24-Jan-2016

43 views

Category:

Documents


3 download

DESCRIPTION

Leading Software Technologies Chennai. CONTENTS. Introduction SQL Server Introduction Data Definition Language Data Manipulation Language Data Control Language Constraints Functions Joins Sub Queries Views & Indexes Stored Procedures Triggers - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Leading Software Technologies Chennai

Leading Software Technologies

Chennai

Page 2: Leading Software Technologies Chennai

CONTENTS

Introduction SQL Server Introduction Data Definition Language Data Manipulation Language Data Control Language Constraints Functions Joins Sub Queries Views & Indexes Stored Procedures Triggers Cursors  User-defined Data types

Page 3: Leading Software Technologies Chennai

INTRODUCTION

Page 4: Leading Software Technologies Chennai

INTRODUCTION

What is Database?

Introduction to DBMS.

Data Model.

Introduction to RDBMS.

DBMS Vs RDBMS

Basic Database Concepts

Page 5: Leading Software Technologies Chennai

What is a Database?

• A structured collection of related data • An filing cabinet, an address book, a telephone

directory, a timetable, etc.• In Access, your Database is your collection of

related tables

Page 6: Leading Software Technologies Chennai

Data vs. Information

• Data – a collection of facts made up of text, numbers and dates:

Menaka 50000 5/22/82

• Information - the meaning given to data in the way it is interpreted:

Menaka is a Programmer whose annual salary is $50,000 and whose date of birth is May 22, 1982.

What is a Database?

Page 7: Leading Software Technologies Chennai

Basic Database Concepts

Table– A set of related records

Name: Rahul College: SSNA Tel: 9942131251

Name: Rahul College: SSNATel: 9942131251

Name: Rahul

Field

Record

– A collection of data about an individual item

– A single item of data common to all records

Page 8: Leading Software Technologies Chennai

Example of Table :

Records

Fields

Name Qualification Phone College

Rahul MSC 9942131251 SSNA

Harris MCA 9840945849 SRM

Priya BE 9834756906 MIT

Basic Database Concepts

Page 9: Leading Software Technologies Chennai

A set of generalized system software for creating and manipulating large databases, whose interfaces provide a broad range of languages to aid all users

Data Base Management System (DBMS)

Application

DBMS

Database

Page 10: Leading Software Technologies Chennai

• Database model is the process of organizing the data into related record types.

• Types of Data models:

Hierarchical

Network

Relational

object oriented model

Data Model

Page 11: Leading Software Technologies Chennai

Hierarchical Database Data is organized into a tree-like structure, implying

a single upward link in each record to describe the nesting. A record type can be owned by only one owner.

Network Database In network databases, a record type can have

multiple owners.

Data Model

Page 12: Leading Software Technologies Chennai

Relational Database models

Relational databases do not link records together physically, but the design of the records must provide a common field to allow for matching.

Often, the fields used for matching are indexed in

order to speed up the process

Data Model

Page 13: Leading Software Technologies Chennai

Object Oriented Database

An "object oriented database" can be employed when hierarchical, network and relational structures are too restrictive.

Object oriented databases can easily handle many-to-many relationships.

Data Model

Page 14: Leading Software Technologies Chennai

Introduction to RDBMS

• RDBMS is a Relational Data Base Management System Relational DBMS.

• This adds the additional condition that the system

supports a tabular structure for the data, with enforced relationships between the tables.

DBMS are for smaller organizations with small amount of data, where security of the data is not of major concern and RDBMS are designed to take care of large amounts of data and also the security of this data.

Page 15: Leading Software Technologies Chennai

DBMS Vs. RDBMS

DBMS RDBMS

1.Set of data and tools to manage those data. - Will not support RELATION SHIP between data. - Ex : - Foxpro data files and earlier Ms Access.  

1.Same as DBMS - Will Support RELATION SHIP between Tables. - Ex : - ORACLE,SQL 2000,DB 2 ...  

2.In DBMS only one user can access the same database, at the same time 

2.In RDBMS many users simultaneously access the same database  

3.No relationship between tables 3. The main advantage of an RDBMS is that it checks for referential integrity (relationship between related records using Foreign Keys). You can set the constraints in an RDMBS such that when a paricular record is changed, related records are updated/deleted automatically.  

Page 16: Leading Software Technologies Chennai

SQL SERVER BASICS

Page 17: Leading Software Technologies Chennai

SQL SEVER BASICS

Introduction

SQL Components

Data Type

Working with Query Analyzer

Page 18: Leading Software Technologies Chennai

• SQL stands for Structured Query Language

• SQL allows to access a database

• SQL is an ANSI standard computer language

• SQL can execute queries against a database

• SQL can retrieve data from a database

SQL

Page 19: Leading Software Technologies Chennai

Sql used for…..

• SQL can insert new records in a database

• SQL can delete records from a database

• SQL can update records in a database

• SQL is easy to learn

• SQL is a standard computer language for accessing and manipulating databases.

SQL

Page 20: Leading Software Technologies Chennai

• SQL is a Standard - BUT....

• SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems.

• SQL statements are used to retrieve and update data in a database.

• SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, etc.

SQL

Page 21: Leading Software Technologies Chennai

Binary data types

Character data types

Date and Time data types

Numeric data types

Integer data types

Monetary data types

Special data types Text and image data types

Unicode Character data types

User-Defined data types

Data Types

Page 22: Leading Software Technologies Chennai

Character data types are used to store any combination of letters, symbols, and numbers. Enclose character data with quotation marks, when enter it.There are two character data types:

1) CHAR(N) 2) VARCHAR(N) // n Specifies the Length

Char(n) data type• Store up to 8000 bytes of fixed-length character data.

Varchar(n) data type

• Store up to 8000 bytes of variable-length character data.• Variable-length means that character data can contain less than n bytes, and the storage size will be the actual length of the data entered.• Use varchar data type instead of char data type, when you expect null values or a variation in data size.

Data Types

CHARACTER DATA TYPES

Page 23: Leading Software Technologies Chennai

There are two datetime data types:

DATETIME

SMALLDATETIME

Datetime It is stored in 8 bytes of two 4-byte integers: 4 bytes for the

number of days before or after the base date of January 1, 1900, and 4 bytes for the number of milliseconds after midnight.

Data Types

DATE AND TIME DATA TYPES

Smalldatetime

It is stored in 4 bytes of two 2-byte integers: 2 bytes for the number of days after the base date of January 1, 1900, and 2 bytes for the number of minutes after midnight.

Page 24: Leading Software Technologies Chennai

•DECIMAL[(P[, S])] // Storage Size10^38 - 1 through - 10^38 - 1. ]

•NUMERIC[(P[, S])]

Data Types

NUMERIC DATATYPES

S - is a scale, that specify the maximum number of decimal digits that can be stored to the right of the decimal point, and it must be less than or equal to the precision.

P - is a precision, that specify the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The maximum precision is 28 digits.

Page 25: Leading Software Technologies Chennai

•FLOAT(N) •REAL

Float[(n)] datatype

It is stored in 8 bytes and is used to hold positive or negative floating-point numbers.It can store positive values from 2.23E-308 to 1.79E308 and negative values from -2.23E-308 to -1.79E308.

Real datatype

It is stored in 4 bytes and is used as float datatype to hold positive or negative floating-point numbers. It can store positive values from 1.18E-38 to 3.40E38 and negative values from -1.18E-38 to -3.40E38.

NUMERIC DATATYPES (Cont.)

Data Types

Page 26: Leading Software Technologies Chennai

There are four integer data types:

•TINYINT •SMALLINT •INT•BIGINT

TINYINT : It is stored in 1 byte and is used to hold integer values from 0 through 255.

SMALLINT : It is stored in 2 bytes and is used to hold integer values from -32768 through 32,767.

INT : It is stored in 4 bytes and is used to hold integer values from -2147483648 through 2147483647.

BIGINT : It is stored in 8 bytes and is used to hold integer values from -9223372036854775808 through 9223372036854775807

Data Types

INTEGER DATATYPES

Page 27: Leading Software Technologies Chennai

Monetary datatypes are usually used to store monetary values.There are two monetary datatypes:

•MONEY •SMALLMONEY

MONEY It is stored in 8 bytes and is used to hold monetary values from -922337203685477.5808 through 922337203685477.5807.

SMALLMONEY It is stored in 4 bytes and is used to hold monetary values from - 214748.3648 through 214748.3647

MONETARY DATATYPES

Data Types

Page 28: Leading Software Technologies Chennai

•BIT •SQL_VARIANT •TIMESTAMP •UNIQUEIDENTIFIER

Data Types

SPECIAL DATATYPES

BIT : It is usually used for true/false or yes/no types of data, because it holds either 1 or 0. All integer values other than 1 or 0 are always interpreted as 1.

One bit column stores in 1 byte, but multiple bit types in a table can be collected into bytes. Bit columns cannot be NULL and cannot have indexes on them.

SQL_VARIANT : It is used to store values of various SQL Server supported data types, except text,ntext,timestamp, and sql_variant. The maximum length of sql_variant datatype is 8016 bytes.

Store in one column of type sql_variant the rows of different data types, for example int, char, and varchar values.

Page 29: Leading Software Technologies Chennai

TIMESTAMP : It is stored in 8 bytes as binary(8) datatype. The timestamp value is automatically updated every time a row containing a timestamp column is inserted or updated.

Timestamp value is a monotonically increasing counter whose values will always be unique within a database and can be selected by queried global variable @@DBTS.

UNIQUEIDENTIFIER : It is a GUID (globally unique identifier). A GUID is a 16-byte binary number that is guaranteed to be unique in the world.This datatype is usually used in replication or as primary key to unique identify rows in a table. Get the new uniqueidentifier value by calling the NEWID function.

Note You should use IDENTITY property instead of uniqueidentifier, if global uniqueness is not necessary, because the uniqueidentifier values are long and more slowly generated.

Data Types

SPECIAL DATATYPES (Cont.)

Page 30: Leading Software Technologies Chennai

Text and image data are stored on the Text/Image pages. There are three datatypes in this category:

• TEXT • NTEXT • IMAGE

TEXT : It is a variable-length datatype that can hold up to 2147483647 characters. This datatype is used when you want to store the character values with the total length more than 8000 bytes.

NTEXT : It is a variable-length unicode datatype that can hold up to 1073741823 characters. This datatype is used when you want to store the variable-length unicode data with the total length more than 4000 bytes.

Data Types

TEXT AND IMAGE DATATYPES

IMAGE : It is a variable-length datatype that can hold up to 2147483647 bytes of binary data.This datatype is used when you want to store the binary values with the total length more than 8000 bytes. It is also used to store pictures.

Page 31: Leading Software Technologies Chennai

A column with unicode character datatype can store all of the characters that are defined in the various character sets, not only the characters from the particular character set, which was chosen during SQL Server Setup.

Unicode datatypes take twice as much storage space as non-Unicode datatypes.

The unicode character data, as well as character data, can be used to store any combination of letters, symbols, and numbers. Enclose unicode character data with quotation marks, when enter it.

Data Types

UNICODE CHARACTER DATATYPES

NCHAR[(N)]

NVARCHAR[(N)]

There are two unicode character datatypes:

Page 32: Leading Software Technologies Chennai

Binary data is similar to hexadecimal data and consists of the characters 0 through 9 and A through F, in groups of two characters each.Specify 0x before binary value when input it.

There are two binary datatypes:

•BINARY[(N)] //Specify the maximum byte length with n.

•VARBINARY[(N)]

BINARY[(N)] Store up to 8000 bytes of fixed-length binary data.

VARBINARY[(N)]• Store up to 8000 bytes of variable-length binary data.• Variable-length means that binary data can contain less than n bytes, and the storage size will be the actual length of the data entered.• Use varbinary datatype instead of binary datatype, when you expect null values or a variation in data size.

BINARY DATA TYPES

Data Types

Page 33: Leading Software Technologies Chennai

Enterprise Manager

To start SQL SERVER

Start

Programs

MicrosoftSQLSERVER

Query Analyzer

Query analyzer

Working with Query Analyzer

Page 34: Leading Software Technologies Chennai

Query Analyzer

Working with Query Analyzer

Page 35: Leading Software Technologies Chennai

To log

Server name

Working with Query Analyzer

Page 36: Leading Software Technologies Chennai

Create a new database named as Ebidding

Working with Query Analyzer

Page 37: Leading Software Technologies Chennai

Select the Query and Press F5 to run the query

Working with Query Analyzer

Page 38: Leading Software Technologies Chennai

Use command

• The USE command selects a database to use for future processing.

Syntax

Use <databasename>

Working with Query Analyzer

Page 39: Leading Software Technologies Chennai

SQL Components

SQL

DDL DML

RDBMS Structure

Create/Delete DBs

Create/Delete TablesAlter Tables

Data I/O

Create Record

Read Record

Update Record

Delete Record

DCL

DBA Activities

Create UsersDelete UsersGrant privilegesImplement AccessSecurity

Page 40: Leading Software Technologies Chennai

DATA DEFINITION LANGUAGE

Page 41: Leading Software Technologies Chennai

DATA DEFINITION LANGUAGE

CREATE

ALETR

DROP

Page 42: Leading Software Technologies Chennai

The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted.

• The most important DDL statements in SQL are: 

CREATE TABLE - creates a new database table

ALTER TABLE - alters (changes) a database table

DROP TABLE - deletes a database table

Data Definition Language (DDL)

Page 43: Leading Software Technologies Chennai

Syntax :

Create table <table name >(

column name1 data type ,

column name2 data type

…….

)

DDL - CREATE

Example :

Create table Employee (

Eno varchar(10),

Empname varchar(100),

Dateofbirth varchar(100),

Salary Numeric )

 Table 1: Employee Eno varchar(10)Ename varchar(100)Dateofbirth varchar(100)Salary int

CREATE Table using Constraints

Page 44: Leading Software Technologies Chennai

Eno EmpName Dateofbirth Salary

Table 1 : EmployeeSyntax 1: Alter a table to add a new column

ALTER TABLE <table name >

ADD column name1 data type

DDL - ALTER

Example : Add “Age” column to Employee table

ALTER TABLE Employee

ADD age INT

Table 1 : Altered table Employee

Table 1: Employee Eno varchar(10)Ename varchar(100)Dateofbirth varchar(100)Salary intAge int

Eno EmpName Dateofbirth

Salary Age

Modifies a table definition by altering, adding, or dropping columns and constraints.

Page 45: Leading Software Technologies Chennai

Table 1 : EmployeeSyntax 1: Modify Existing Column

ALTER TABLE <table name >

ALTER column name1 data type

DDL - ALTER

Example : Modify “DateofBirth” data type to DATETIME

ALTER TABLE Employee

ALTER COLUMN DateofBirth DateTime

Table 1 : Altered table Employee

Table 1: Employee Eno varchar(10)Ename varchar(100)

Table 1: Employee Eno varchar(10)Ename varchar(100)

Salary int

Dateofbirth DateTime

Salary int

Dateofbirth varchar(100)

Page 46: Leading Software Technologies Chennai

Syntax : Alter table to drop column

Example: Remove “Age” from Employee Table

ALTER TABLE Employee

DROP COLUMN Age

DDL - ALTER

Eno EmpName Dateofbirth Salary

Table 1 : Employee

Table 1 : Altered table Employee

Eno EmpName Dateofbirth

Salary AgeALTER TABLE <Table Name>

DROP COLUMN <Columnname>

Page 47: Leading Software Technologies Chennai

Syntax :

DROP TABLE <table name >

DDL - DROP

Example :

DROP TABLE Employee

Drop should destroy the values and structure of the table

Removes a table definition and all data, indexes, triggers, constraints, and permission specifications for that table.

Page 48: Leading Software Technologies Chennai

DATA MANIPULATION LANGUAGE

Page 49: Leading Software Technologies Chennai

DATA MANIPULATION LANGUAGE

INSERT

UPDATE

DELETE

SELECT

Page 50: Leading Software Technologies Chennai

DML - Data Manipulation Language

• Data manipulation language (DML) statements

access and manipulate data in existing schema objects.

DML Statements includes :

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

Page 51: Leading Software Technologies Chennai

Syntax : Simple Insert

INSERT INTO TableName

VALUES(Fieldvalue1,Field Value2 …)

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

Example :

INSERT INTO Employee VALUES (‘LST/1001’,’Menaga’,’05/22/1982’,12000)

DML – INSERT

INSERT Statement is used to insert data into Database table

Note :

Varchar,Char and DateTime values should be given with single quotes. (Eg) ‘Menaga’

 Table 1: Employee Eno varchar(10)Ename varchar(100)Dateofbirth DatetimeSalary int

Page 52: Leading Software Technologies Chennai

Syntax :

INSERT INTO TableName(Field1,Field2…)

VALUES(Fieldvalue1,Field Value2 …)

Eno EmpName Dateofbirth Salary

LST/1001 Menaga

Example :

INSERT INTO Employee(Eno,Ename)

VALUES(‘LST/1001’,’Menaga’)

DML – INSERT

Note : Insert All not null values.

 Table 1: Employee Eno varchar(10)Ename varchar(100)Dateofbirth DatetimeSalary int

Insert data with fewer values than columns

Page 53: Leading Software Technologies Chennai

Syntax :

INSERT INTO TableName(Field1,Field2…)

SELECT(Fieldvalue1,Field Value2 …)

Eno EmpName Dateofbirth Salary

LST/1001 Menaga

Example :

INSERT INTO Employee(Eno,Ename)

SELECT Eno,Ename FROM OldEmp

DML – INSERT

Note : Insert All not null values.

 Table 1: Employee Eno varchar(10)Ename varchar(100)Dateofbirth DatetimeSalary int

Insert data from Other table

Page 54: Leading Software Technologies Chennai

Syntax :

BULK INSERT database_name.dbo.table_name FROM 'data_file'      WITH    (   FIELDTERMINATOR ='field_terminator‘,

ROWTERMINATOR = 'row_terminator' )

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 05/22/1982 10000

LST/1002 Kavitha 07/10/1982 12000

Example :

BULK INSERT Master.dbo.Employee

FROM ‘C://empdetails.txt’' WITH  (  FIELDTERMINATOR=‘*‘,

ROWTERMINATOR = ‘ > ' )

DML – INSERT

Example File Format is :

LST/1001 * Menaga * 05/22/1982 * 10000> LST/1002 * Kavitha * 07/10/1982 * 12000>

Insert data from Some otherFile System(Eg. Notepad,XML)

Page 55: Leading Software Technologies Chennai

UPDATE Employee Set salary=20000

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Shakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Table 1 : Employee

1) Simple Update

DML - UPDATE

Syntax :

UPDATE <tablename> SET columname=value WHERE conditon

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 20000

LST/1002 Kavitha 10/07/1982 20000

LST/1003 Shakthi 12/05/1985 20000

LST/1004 Karthik 15/09/1980 20000

2).More than 2 values with Condition

UPDATE employee SET salary=50000,Empname=‘Preetha’

WHERE Eno=‘LST/1003’

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 20000

LST/1002 Kavitha 10/07/1982 20000

LST/1003 Preetha 12/05/1985 50000

LST/1004 Meena 15/09/1980 20000

UPDATE Statement is used to update data into Database table

Page 56: Leading Software Technologies Chennai

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Shakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Table 1 : Employee

1) Delete the Employee with employeeno‘LST/1004’

DML - DELETE

Syntax :

DELETE FROM <tablename>

WHERE conditon

DELETE FROM Employee

2.) Delete all records in Employee

DELETE FROM Employee

WHERE eno=‘LST/1004’

Delete values only not structure of the table

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Shakthi 12/05/1985 12000

DELETE Statement is used to delete data from Database table

Page 57: Leading Software Technologies Chennai

SELECT * FROM Employee

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Shakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Table 1 : Employee

SELECT * FROM Employee WHERE Eno=‘LST/10001’

1) Display Employee details

2) Display all the details of Employee no ‘LST/1001’

DML - SELECT

Syntax:

SELECT * From <tablename>

WHERE Condition

SELECT Field1,Field2.. FROM TableName

WHERE Condition

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

SELECT is Used to retrieve the data from the database Table

Page 58: Leading Software Technologies Chennai

Table 1 : Employee

Syntax :

SELECT * FROM tablename

ORDER BY Fieldname ASC/DESC

* By default is is Ascending

DML - SELECT

Arrange the Rows by Ascending or Descending

SELECT USING ORDER BY

Example :

SELECT * FROM Employee

ORDER BY Empname

SELECT * FROM Employee

ORDER BY Empname DESC

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Sakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

ORDER BY ASC

Eno EmpName Dateofbirth Salary

LST/1004 Karthik 15/09/1980 20000

LST/1002 Kavitha 10/07/1982 15000

LST/1001 Menaga 22/05/1982 12000

LST/1003 Sakthi 12/05/1985 12000

Eno EmpName Dateofbirth Salary

LST/1003 Sakthi 12/05/1985 12000

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1004 Karthik 15/09/1980 20000

ORDER BY DESC

Page 59: Leading Software Technologies Chennai

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Karthik 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Table 1 : Employee

DML - SELECT

The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. If DISTINCT is not specified, all rows are returned, including duplicates.

SELECT DISTINCT

Example :

SELECT Empname FROM Employee

SELECT DISTINCT( Empname) FROM Employee

Syntax :

SELECT DISTINCT( Field Name) FROM TableNameEmpName

Menaga

Kavitha

Karthik

Karthik

EmpName

Menaga

Kavitha

Karthik

With out Distinct

Using Distinct

Page 60: Leading Software Technologies Chennai

DML - SELECT

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Karthik 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Table 1 : Employee

The Where Conditions may includes the following logical operatos: AND , OR , NOT

AND - Both Conditions should be True.OR - Both or Any one of the Condition should be True NOT – If Condition is True then return False If Condition is False then return True

SELECT USING LOGICAL OPERATORS

Example :

SELECT * FROM Employee

WHERE Eno=‘LST/1001’ AND Salary=12000

SELECT * FROM TableName

WHERE Eno=‘LST/1001’ OR Salary=12000

SELECT * FROM TableName

WHERE NOT (Salary=12000)

AND

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1003 Karthik 12/05/1985 12000

OR

NotEno EmpName Dateofbirth Salary

LST/1002 Kavitha 10/07/1982 15000

LST/1004 Karthik 15/09/1980 20000

Page 61: Leading Software Technologies Chennai

Table 1 : Employee

Syntax :

SELECT * FROM tablename

WHERE Fieldname BETWEEN value1 AND value2

Eno EmpName Dateofbirth Salary

LST/1002 Kavitha 10/07/1982 15000

LST/1004 Karthik 15/09/1980 20000

BETWEEN Specifies a range to test.

SELECT USING BETWEEN

Example :

SELECT * FROM Employee

WHERE Salary BETWEEN 15000 AND 20000

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Sakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

BETWEEN

DML - SELECT

Page 62: Leading Software Technologies Chennai

Table 1 : Employee

Syntax :

SELECT * FROM tablename

WHERE Fieldname LIKE ‘%Characterstring%’

% - Indicated any string before and after

Eno EmpName Dateofbirth Salary

LST/1002 Kavitha 10/07/1982 15000

LST/1004 Karthik 15/09/1980 20000

Determines whether or not a given character string matches a specified pattern.

SELECT USING LIKE

Example : Select Employee details whose name starts with ‘K’

SELECT * FROM Employee

WHERE EmpName LIKE ‘ K %’

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Sakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

LIKE

DML - SELECT

Page 63: Leading Software Technologies Chennai

Table 1 : Employee

Syntax :

SELECT [ALL | DISTINCT] columnname1 [,columnname2] FROM tablename1 [,tablename2] [WHERE condition] [ and|or condition...] [GROUP BY column-list] [HAVING "conditions] [ORDER BY "column-list" [ASC | DESC] ]

•The GROUP BY clause is used to group the output of the WHERE clause.

SELECT USING GROUP BY

Example :

SELECT SUM(salary) FROM Employee where salary >12000 GROUP BY Eno

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Sakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Using WHERE

Using Having

15000

20000

Example :

SELECT EmpName FROM EMPLOYEE

GROUP BY SALARY HAVING EMPNAME LIKE ‘k%'

Kavitha

Karthik

DML - SELECT

Page 64: Leading Software Technologies Chennai

•The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type.

•With UNION, only distinct values are selected.

Syntax:

SQL SELECT Statement 1 UNION SQL SELECT Statement 2

UNION

DML - SELECT

Page 65: Leading Software Technologies Chennai

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees_Chennai

Table 2 :Employees_Banglore

1)Combining Two Tables

UNION

Employee_Id Name

100 Saachin

101 Kumble

102 Prasad

103 Agarkar

Name

Sachin

Dravid

Ganguly

Kumble

Prasad

Agarkar

SELECT E_Name FROM Employees_Chennai UNION SELECT E_Name FROM Employees_Banglore

This command cannot be used to list all employees in Chennai and Banglore. In the example above we have two employees with equal names, and only one of them is listed. The UNION command only selects distinct values.

Page 66: Leading Software Technologies Chennai

The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values

Syntax

SQL Statement 1 UNION ALL SQL Statement 2

UNION ALL

DML - SELECT

Page 67: Leading Software Technologies Chennai

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees_Chennai

Table 2 :Employees_Banglore

1)Combining Two Tables

UNION ALL

Employee_Id Name

100 Sachin

101 Kumble

102 Prasad

103 Agarkar

Name

Sachin

Sachin

Dravid

Kumble

Prasad

Agarkar

SELECT E_Name FROM Employees_Chennai UNION ALL SELECT E_Name FROM mployees_Banglore

This command can be used to list all employees in Chennai and Banglore. In the example above we have two employees with equal names, and all of them is listed.

Page 68: Leading Software Technologies Chennai

DATA CONTROL LANGUAGE

Page 69: Leading Software Technologies Chennai

Data Control Language

• Data Control Language is the segment of the SQL language that allows you to work with user privileges for objects in the database.

• DCL uses the following two SQL commands to work with objects in the database:

GRANT: Gives authority for a user or group to access or update a table, view, or procedure.

REVOKE: Removes authority that has been previously granted to a user or a group.

DENY : Deny Permission for a user or group to access or update a table, view, or procedure.

Page 70: Leading Software Technologies Chennai

CONSTRAINTS

Page 71: Leading Software Technologies Chennai

PRIMARY KEY

FOREIGN KEY

CHECK

CONSTRAINTS

DEFAULT

NULL

Page 72: Leading Software Technologies Chennai

CONSTRAINTS

• Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity.Using constraints is preferred to using triggers, rules, and defaults.

Classes of Constraints

1.Primary Key

2.Foreign Key

3.Unique

4.Check

5.Default

6.Not null

Page 73: Leading Software Technologies Chennai

1 ) PRIMARY KEY

It is a constraint that identify the column or set of columns whose values uniquely identify a row in a table.

No two rows in a table can have the same primary key value.

You cannot enter a NULL for any column in a primary key.

NULL is a special value in databases that represents an unknown value, which is distinct from a blank or 0 value.

2 ) FOREIGN KEY

It is a constraint that identify the relationships between tables.A foreign key in one table points to a candidate key in another table.

CONSTRAINTS

3 ) CHECK

It is a constraint that enforce domain integrity by limiting the values that can be placed in a column. range are entered for the key.

Page 74: Leading Software Technologies Chennai

UNIQUE It is a constraint that enforce the uniqueness of the

values in a set of columns. No two rows in the table are allowed to have the same values for the columns in a UNIQUE constraint. It accepts one null value

CONSTRAINTS

4 ) DEFAULT

It is a Constraint that sets the default value which is allowed for the column if value is not given

5 ) NOT NULL

It specifies that the column does not accept NULL values.

Page 75: Leading Software Technologies Chennai

Table 1 : Product

1.PRIMARY KEY CONSTRAINT

create table product (pcode int primary key ,pname varchar(100))

Pcode Pname

100 Rin

101 Surf

102 Ariel

103 Power

2.FOREIGN KEY CONSTRAINT

create table orders (pcode int foreignkey references product(pcode),orderid varchar(100))

Pcode Pname

100 Rin

101 Surf

102 Ariel

103 Power

Pcode Orderid

100 Ord100

101 Ord101

101 Ord102

102 Ord103

Table 2 : Order

Pcode Orderid

100 Ord100

101 Ord101

101 Ord102

102 Ord103

.

INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK__orders__pcode__76A18A26'. The conflict occurred in database 'master', table 'product', column 'pcode'.

The statement has been terminated.insert into orders values(104,'ord105')

Note:Pcode 104 is not belongs to product

Create table tablename (Column name data type foreign key references primarykey tablename(columnname)

Create table table name (column name data type prmary key

Page 76: Leading Software Technologies Chennai

Table 1 : Product

3.CHECK CONSTRAINT

Alter table product add price numeric check(price >250)

4.NOT NULL CONSTRAINT

create table ord (pcode int not null,prodname varchar(100) not null)

Pcode Pname

100 Rin

101 Surf

102 Ariel

103 Power

Table 2 : Ord

Pcode Pname Price

100 Rin 300

101 Surf null

102 Ariel null

103 Power null

Pcode Productname

100 Pears

101 Hamam

101 Liril

102 Cinthol

Product  Pcode intPname varchar(100)Price numeric check (price >250)

Ord  Pcode int not nullPname varchar(100) not null

Page 77: Leading Software Technologies Chennai

Table 1 : Orde

UNIQUE CONSTRAINT

create table orde (pcode int unique,prodname varchar(100) )

Pcode Productname

Pcode Productname

100 Rin

101 Surf

102 Ariel

103 Power

Orde Pcode int uniquePname varchar(100)

Create table <tblname>(columnname unique)

5.DEFAULT CONSTRAINT

create table ord1 (pcode int unique,prodname varchar(100) default ‘surf’)

Pcode Productname

100 Rin

101 Surf

102 Ariel

105 Surf

insert into ord1(pcode) values(105)

Create table <tblname>(column name data type default value)

Table 1 : Orde1

Page 78: Leading Software Technologies Chennai

Sample Constraints contain all classes

Create table empnew(eno int PRIMARY KEY,ename varchar(100) unique,salary numeric CHECK(salary >10000),designation varchar(30) DEFAULT 'programmer', dob datetime NOT NULL)

eno ename salary designaton dob

100 Meena 25000 Designer 1982/05/02

101 Geetha 30000 programmer 1982/04/05

102 Kavitha 50000 Teamleader 1982/06/07

Table :Empnew Eno intEname varchar(100)Salary numericDesignation varchar(30)Dob datetime 

Page 79: Leading Software Technologies Chennai

Table 1 : Order

IDENTITY

create table order (pcode int identity(1000,1),prodname varchar(100) )

Pcode Prodname

Order Pcode int identity(1000,1)Prodname varchar(100)

Create table <tblname>(columnname data type identity)

Pcode Prodname

1000 pears

1001 Margo

Table 1 : Orderinsert into order(prodname) values('pears')

insert into order(prodname) values('Margo')

Select * from order

Page 80: Leading Software Technologies Chennai

FUNCTIONS

Page 81: Leading Software Technologies Chennai

FUNCTIONS

AGGREGATE FUNCTIONS

STRING FUNCTIONS

MATHEMATICAL FUNCTIONS

DATE FUNCTIONS

Page 82: Leading Software Technologies Chennai

• Its used produce the result set of the select statements in an effective way as like calculating and manipulating the values.

Types

1. Count

2. Sum

3. Avg

4. Max

5. Min

AGGREGATE FUNCTIONS

FUNCTIONS

Page 83: Leading Software Technologies Chennai

COUNT

Its used to count the total number of records in the table

Table 1:Employees

Eno Ename Salary

100 Praveen 50000

101 Preetha 30000

102 Aravinth 25000

103 Priya 30000Ex:SELECT COUNT(eno) FROM employees

Output:

• 4In the employees table its display the total number of employees

FUNCTIONS

AGGREGATE FUNCTIONS

Page 84: Leading Software Technologies Chennai

SUM

Its used to sum the total number of records in the table

Table 1:Employees

Eno Ename Salary

100 Praveen 50000

101 Preetha 30000

102 Aravinth 25000

103 Priya 30000Ex:SELECT SUM(salary)FROM employees

Output:

• 135000In the employees table its display the sum of employee salary employees

FUNCTIONS

AGGREGATE FUNCTIONS

Page 85: Leading Software Technologies Chennai

Avg

Its used to calculate the average value for the given records in the table

Table 1:Employees

Eno Ename Salary

100 Praveen 50000

101 Preetha 30000

102 Aravinth 25000

103 Priya 30000Ex:SELECT AVG(salary)FROM employees

Output:

• 33750In the employees table its display the average salary of the employees

FUNCTIONS

AGGREGATE FUNCTIONS

Page 86: Leading Software Technologies Chennai

MAX

Its used display the maximum values of records in the table

Table 1:Employees

Eno Ename Salary

100 Praveen 50000

101 Preetha 30000

102 Aravinth 25000

103 Priya 30000Ex:SELECT MAX(salary)FROM employees

Output:

• 50000In the employees table its display maximum salary of the employee

FUNCTIONS

AGGREGATE FUNCTIONS

Page 87: Leading Software Technologies Chennai

MIN

Its used display the minimum values of records in the table

Table 1:Employees

Eno Ename Salary

100 Praveen 50000

101 Preetha 30000

102 Aravinth 25000

103 Priya 30000Ex:SELECT MIN(salary)FROM employees

Output:

• 25000In the employees table its display minimum salary of the employee

FUNCTIONS

AGGREGATE FUNCTIONS

Page 88: Leading Software Technologies Chennai

These scalar functions perform an operation on a string input value and return a string or numeric value

FUNCTIONS

STRING FUNCTIONS

ASCII

Returns the ASCII code value of the leftmost character of a character expression.

Syntax

ASCII ( character_expression )

Arguments

character_expression

Is an expression of the type char or varchar.

Return Types : int

Ex:

Select ASCII(‘A’)

Output:

65

Page 89: Leading Software Technologies Chennai

CHARA string function that converts an int ASCII code to a character.

SyntaxCHAR ( integer_expression )

Arguments

integer_expressionIs an integer from 0 through 255. NULL is returned if the integer expression is not in this range.

Return Typeschar(1)

Ex:

select CHAR(65)

Output:

A

FUNCTIONS

STRING FUNCTIONS

Page 90: Leading Software Technologies Chennai

LEN

Returns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks.

SyntaxLEN ( string_expression )

Argumentsstring_expressionIs the string expression to be evaluated.

Return Types : int

Ex:select len('praveen')

Output:

7

FUNCTIONS

STRING FUNCTIONS

Page 91: Leading Software Technologies Chennai

SUBSTRINGReturns part of a character, binary, text, or image expression

SyntaxSUBSTRING ( expression , start , length )

ArgumentsexpressionIs a character string, binary string, text, image, a column, or an expression that includes a column. Do not use expressions that include aggregate functions.startIs an integer that specifies where the substring begins.lengthIs an integer that specifies the length of the substring (the number of characters or bytes to return).

Ex:select SUBSTRING('preetha',1,3)

Output:

pre

FUNCTIONS

STRING FUNCTIONS

Page 92: Leading Software Technologies Chennai

REPLACEReplaces all occurrences of the second given string expression in the first string expression with a third expression.

Syntax

REPLACE ( 'string_expression1' , 'string_expression2' , 'string_expression3' )

Arguments'string_expression1‘ : Is the string expression to be searched. string_expression1 can be of character or binary data.'string_expression2‘ : Is the string expression to try to find. string_expression2 can be of character or binary data.'string_expression3‘ : Is the replacement string expression string_expression3 can be of character or binary data.

Ex:

SELECT REPLACE('abcdefghicde','cde','xxx')

Output:

abxxxfghixxx

This example replaces the string cde in abcdefghi with xxx.

FUNCTIONS

STRING FUNCTIONS

Page 93: Leading Software Technologies Chennai

UPPERReturns a character expression with lowercase character data converted to uppercase.

SyntaxUPPER ( character_expression )

Argumentscharacter_expressionIs an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

Return Typesvarchar

Ex:

Select UPPER(‘priya’)

Output:

PRIYA

FUNCTIONS

STRING FUNCTIONS

Page 94: Leading Software Technologies Chennai

LOWERReturns a character expression after converting uppercase character data to lowercase.

SyntaxLOWER ( character_expression )

Argumentscharacter_expressionIs an expression of character or binary data. character_expression can be a constant, variable, or column. character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use CAST to explicitly convert character_expression.

Return Typesvarchar

Ex:

Select LOWER(‘PRIYA’)

Output:

priya

FUNCTIONS

STRING FUNCTIONS

Page 95: Leading Software Technologies Chennai

These scalar functions perform a calculation, usually based on input values provided as arguments, and return a numeric value.

Arithmetic functions, such as ABS, CEILING, DEGREES, FLOOR, POWER, RADIANS, and SIGN, return a value having the same data type as the input value. Trigonometric and other functions, including EXP, LOG, LOG10, SQUARE, and SQRT, cast their input values to float and return a float value.

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 96: Leading Software Technologies Chennai

ABS

Returns the absolute, positive value of the given numeric expression.

SyntaxABS ( numeric_expression )

Argumentsnumeric_expressionIs an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Return TypesReturns the same type as numeric_expression

Examples

This example shows the effect of the ABS function on three different numbers.

SELECT ABS(-1.0), ABS(0.0), ABS(1.0)

Output:

1.0, .0 ,1.0

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 97: Leading Software Technologies Chennai

CEILINGReturns the smallest integer greater than, or equal to, the given numeric expression.

SyntaxCEILING ( numeric_expression )

Argumentsnumeric_expressionIs an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Return TypesReturns the same type as numeric_expression.

Examples

This example shows positive numeric, negative, and zero values with the CEILING function.

SELECT CEILING(123.45), CEILING(-123.45), CEILING(0.0)

Output

124.00, -123.00, 0.00

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 98: Leading Software Technologies Chennai

FLOORReturns the largest integer less than or equal to the given numeric expression.

SyntaxFLOOR ( numeric_expression )

Argumentsnumeric_expressionIs an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Return TypesReturns the same type as numeric_expression.

Examples:

This example shows positive numeric, negative numeric values with the FLOOR function.

SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR(123.45)

Output:

123 ,-124 ,123.0000

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 99: Leading Software Technologies Chennai

POWER

Returns the value of the given expression to the specified power.

SyntaxPOWER ( numeric_expression , y )

Argumentsnumeric_expressionIs an expression of the exact numeric or approximate numeric data type category, except for the bit data type.yIs the power to which to raise numeric_expression. y can be an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Return TypesSame as numeric_expression.

Ex:

select POWER(2,2)

Output:

4

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 100: Leading Software Technologies Chennai

ROUND

Returns a numeric expression, rounded to the specified length or precision.Syntax

ROUND ( numeric_expression , length [ , function ] )

Arguments

numeric_expressionIs an expression of the exact numeric or approximate numeric data type category, except for the bit data type.lengthIs the precision to which numeric_expression is to be rounded.

Examples

This example shows two expressions illustrating that with the ROUND function the last digit is always an estimate

SELECT ROUND(123.9994, 3), ROUND(123.9995, 3)

Output:

123.9990, 124.0000

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 101: Leading Software Technologies Chennai

SQUARE : Returns the square of the given expression.

Syntax : SQUARE ( float_expression )

Argumentsfloat_expression : Is an expression of type float.

Return Types : float

Ex:

select square(4)

Output:

16.0

SQRTReturns the square root of the given expression.

Syntax : SQRT ( float_expression )

Argumentsfloat_expression : Is an expression of type float.

Return Types : float

Ex:

select sqrt(4)

Output:

2.0

FUNCTIONS

MATHEMATICAL FUNCTIONS

Page 102: Leading Software Technologies Chennai

These scalar functions perform an operation on a date and time input value and return a string, numeric, or date and time value.

FUNCTIONS

DATE AND TIME FUNCTIONS

GETDATE

DAY

MONTH

YEAR

DATEADD

DATEDIFF

Page 103: Leading Software Technologies Chennai

GETDATE

Returns the current system date and time in the SQL Server standard internal format for datetime values.

Syntax : GETDATE ( )

Return Types : datetime

RemarksDate functions can be used in the SELECT statement select list or in the WHERE clause of a query.

Ex:

Select GETDATE( )

Output:

2007-05-26 18:00:56.153

FUNCTIONS

DATE AND TIME FUNCTIONS

Page 104: Leading Software Technologies Chennai

DAY

Returns an integer representing the day datepart of the specified date.

Syntax : DAY ( date )

Arguments :

Date : Is an expression of type datetime or smalldatetime.

Return Type : int

Example:

Select DAY(’05/12/2007’)

Output:

12

FUNCTIONS

DATE AND TIME FUNCTIONS

Page 105: Leading Software Technologies Chennai

MONTH

Returns an integer that represents the month part of a specified date.

Syntax : MONTH ( date )

Arguments

Date : Is an expression returning a datetime or smalldatetime value, or a character string in a date format. Use the datetime data type only for dates after January 1, 1753.

Return Types : int

Example:

Select MONTH(’05/12/2007’)

Output:

5

FUNCTIONS

DATE AND TIME FUNCTIONS

Page 106: Leading Software Technologies Chennai

YEAR

Returns an integer that represents the year part of a specified date.

Syntax : YEAR ( date )

Arguments

Date : An expression of type datetime or smalldatetime.

Return Types : int

Example:

Select YEAR(’05/12/2007’)

Output:

2007

FUNCTIONS

DATE AND TIME FUNCTIONS

Page 107: Leading Software Technologies Chennai

DATEADD

Returns a new datetime value based on adding an interval to the specified date.

Syntax : DATEADD ( datepart , number, date )

numberIs the value used to increment datepart. If you specify a value that is not an integer, the fractional part of the value is discarded. For example, if you specify day for datepart and1.75 for number, date is incremented by 1.

Select DATEADD(DAY,10,’03/12/2007’)

Output:

2007/05/22

Select DATEADD(MONTH,04,’03/12/2007’)

Select DATEADD(YEAR,02,’03/12/2007’)

Output:

2007/07/22

Output:

2009/05/22

FUNCTIONS

DATE AND TIME FUNCTIONS

Page 108: Leading Software Technologies Chennai

Select DATEDIFF(DAY,'07/05/1979','11/08/1983')

Output:

1587

Select DATEDIFF(MONTH,'07/05/1979','11/08/1983')

Select DATEDIFF(YEAR,'07/05/1979','11/08/1983')

Output:

52

Output:

4

DATEDIFF

Returns the number of date and time boundaries crossed between two specified dates.

SyntaxDATEDIFF ( datepart , startdate , enddate )

Arguments

datepartIs the parameter that specifies on which part of the date to calculate the differencestartdateIs the beginning date for the calculation. startdate is an expression that returns a datetime or smalldatetime value, or a character string in a date format. enddateIs the ending date for the calculation. enddate is an expression that returns a datetime or smalldatetime value, or a character string in a date format.

FUNCTIONS

DATE AND TIME FUNCTIONS

Page 109: Leading Software Technologies Chennai

JOINS

Page 110: Leading Software Technologies Chennai

JOINS

OUTER JOIN

INNER JOIN

CROSS JOIN

Page 111: Leading Software Technologies Chennai

JOINS

Sometimes we have to select data from two or more tables to make the result complete. Here we have to perform a join.

Joins can be categorized as:

INNER JOINS

OUTER JOINS

CROSS JOINS

Page 112: Leading Software Technologies Chennai

DeptNo DeptName Shortname

100 Human Resourse HR

101 Accounts AC

102 Reaserch and Development RD

DeptNo ENO

100 LST/1003

101 LST/1001

101 LST/1004

102 LST/1002

Table 3 : EmpDept

SELECT E.Eno,E.Ename,E.DateofBirth,D. DeptName,E.Salary FROM Employee E,Department D,EMpDept ED

WHERE E.Eno=ED.Eno AND ED.Deptno=D.Deptno AND AND E.Eno=‘LST/10001’

Eno EmpName Dateofbirth DeptName Salary

LST/1001 Menaga 22/05/1982 Accounts 12000

Display all the details of Employee no ‘LST/1001’Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

LST/1002 Kavitha 10/07/1982 15000

LST/1003 Shakthi 12/05/1985 12000

LST/1004 Karthik 15/09/1980 20000

Table 1 : Employee

Table 2 : Department

JOINS

Page 113: Leading Software Technologies Chennai

select *from Employees,Orders

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Table 2 :Orders

1)Joining Two Tables

Simple Join

Prod_Id Product Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Employee_ID Name Prod_ID Product Employee_ID

100 Sachin 1000 Bat 100

101 Dravid 1000 Bat 100

102 Ganguly 1000 Bat 100

100 Sachin 1003 Ball 100

101 Dravid 1003 Ball 100

102 Ganguly 1003 Ball 100

100 Sachin 1005 Glouse 101

101 Darvid 1005 Glouse 101

102 Ganguly 1005 Glouse 101

Page 114: Leading Software Technologies Chennai

INNER JOINS

An inner join is a join in which the values in the columns being joined are compared using a comparison operator.

Inner joins (the typical join operation, which uses some comparison operator like = or <>).

These include equi- joins and natural joins.

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table.

Inner joins return rows only when there is at least one row from both tables that matches the join condition. Inner joins eliminate the rows that do not match with a row from the other table

JOINS

Page 115: Leading Software Technologies Chennai

SELECT Employees.Name, Orders.Product FROM Employees INNER JOIN Orders ON Employees.Employee_ID=Orders.Employee_ID

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Table 2 :Orders

1)Joining Two Tables with specified condition

Prod_Id Product Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Name Product

Sachin Bat

Sachin Ball

Dravid Glouse

The 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.

INNER JOINS

JOINS

Page 116: Leading Software Technologies Chennai

Outer joins can be a left, a right, or full outer join. Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

LEFT JOIN or LEFT OUTER JOIN

The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match.

When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

OUTER JOINS

JOINS

Page 117: Leading Software Technologies Chennai

SELECT Employees.Name, Orders.Product

FROM Employees

LEFT JOIN Orders

ON Employees.Employee_ID=Orders.Employee_ID

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Table 2 :Orders

1)Joining Two Tables with specified condition

LEFT OUTER JOIN

Prod_Id Product Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Name Product

Sachin Bat

Sachin Ball

Dravid Glouse

Ganguly Null

The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.

Page 118: Leading Software Technologies Chennai

RIGHT OUTER JOIN OR RIGHT JOIN

A right outer join is the reverse of a left outer join.

All rows from the right table are returned.

Null values are returned for the left table any time a right table row has no matching row in the left table.

OUTER JOINS

JOINS

Page 119: Leading Software Technologies Chennai

SELECT Employees.Name, Orders.Product FROM Employees RIGHT JOIN Orders ON Employees.Employee_ID=Orders.Employee_ID

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Table 2 :Orders

1)Joining Two Tables

RIGHT OUTER JOIN

Prod_Id Product Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Name Product

Sachin Bat

Sachin Ball

Dravid Glouse

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.

Page 120: Leading Software Technologies Chennai

FULL OUTER JOIN

A full outer join returns all rows in both the left and right tables.

Any time a row has no match in the other table, the select list columns from the other table contain null values.

When there is a match between the tables, the entire result set row contains data values from the base tables.

OUTER JOINS

JOINS

Page 121: Leading Software Technologies Chennai

SELECT Employees.Name, Orders.Product

FROM Employees

FULL Outer JOIN Orders

ON Employees.Employee_ID=Orders.Employee_ID

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Table 2 :Orders

1)Joining Two Tables

FULL OUTER JOIN

Prod_Id Product Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Name Product

Sachin Bat

Sachin Ball

Dravid Glouse

Ganguly Null

Page 122: Leading Software Technologies Chennai

Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table.

Cross joins are also called Cartesian products.

CROSS JOINS

JOINS

Page 123: Leading Software Technologies Chennai

select *from Employees cross join Orders

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Table 2 :Orders

1)Joining Two Tables with Cross Join

CROSS JOIN

Prod_Id Product Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Employee_ID Name Prod_ID Product Employee_ID

100 Sachin 1000 Bat 100

101 Dravid 1000 Bat 100

102 Ganguly 1000 Bat 100

100 Sachin 1003 Ball 100

101 Dravid 1003 Ball 100

102 Ganguly 1003 Ball 100

100 Sachin 1005 Glouse 101

101 Darvid 1005 Glouse 101

102 Ganguly 1005 Glouse 101

Page 124: Leading Software Technologies Chennai

SUB QUERIES

Page 125: Leading Software Technologies Chennai

A SELECT statement nested inside another SELECT statement is commonly referred to as a SUBQUERY

It is also known as a nested query.

A sub Query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

Sub Queries are used with the SELECT, INSERT, UPDATE, and DELETE statements.

A sub query can be used in some cases in place of a join operation by indirectly linking data between the tables based on one or more conditions.

SUB QUERIES

Page 126: Leading Software Technologies Chennai

Syntax

Select * from <tblname> where condition( select * from <tblname>)

Example

select * from stud where sno in(select sno from payment)

Sno Sname

100 preetha

101 praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

ResultSno

100

101

102

103

SUB QUERIES

Page 127: Leading Software Technologies Chennai

Two types of sub queries:

1.Simple sub query 2.Correlated Sub query

1.Simple sub query

The results of one query as the input for another is called as simple sub query

 2.Correlated Sub query

It depends upon the outer table.Each time the inner query evaluated whenever the system finds the new row in outer query.

SUB QUERIES

Page 128: Leading Software Technologies Chennai

Operations involved in sub query

Basic comparisons:Sub Queries can be introduced with one of the comparison operators (=, < >, >, > =, <, ! >, ! <, or < =).

Quantified Comparisons(ANY,ALL and SOME)

IN,NOT IN Keyword

EXISTS ,NOT EXISTS Keyword

SUB QUERIES

Page 129: Leading Software Technologies Chennai

select * from stud where sno =(select sno from payment where balance=0)

1.Sub Queries using operators

Sno Sname

100 preetha

101 praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

Sno Sname

101 praveenkumar

Result

SUB QUERIES

Page 130: Leading Software Technologies Chennai

select * from stud where sno in(select sno from payment where balance>1000)

2.Sub Queries using IN Sno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

Sno Sname

100 preetha

103 Reethu

Using IN the inner query execute and return value.Based on the inner query the outer query return values

Select stmt IN  ( subquery |

expression [ ,...n ] )

syntax

Result

SUB QUERIES

Page 131: Leading Software Technologies Chennai

select * from stud where sno NOT IN (select sno from payment where balance>1000)

3.Sub Queries using NOT INSno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

Using NOT IN the inner query execute and return value.The outer query return values which is not belong to Sub query

Sno Sname

101 Praveenkumar

102 Ramkumar

Select stmt NOT IN  ( subquery | expression [ ,...n ] )

syntax

Result

SUB QUERIES

Page 132: Leading Software Technologies Chennai

4.Sub Queries using EXISTS

Sno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

Exists function check’s inner query if it contains at least one row. It returns a value of TRUE or FALSE.

Sno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

Select stmt where EXSTS  ( subquery | expression [ ,...n ] )

syntax

select * from stud where exists (select * from payment where stud.sno=payment.sno)

SUB QUERIES

Page 133: Leading Software Technologies Chennai

5.Sub Queries using NOT EXISTS

Sno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

It works just opposite to EXISTS

Sno Sname

104 Sathyakar

105 Sus

Select stmt where NOT EXSTS  (

subquery | expression [ ,...n ]     )

syntax

select * from stud where not exists (select * from payment where stud.sno=payment.sno)

SUB QUERIES

Page 134: Leading Software Technologies Chennai

5.Sub Queries using ANYSno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 0

103 7000 3000

Table:Stud

Table:Payment

Select stmt where ANY  (

subquery | expression [ ,...n ]     )

syntax

SELECT sname FROM stud WHERE sno = any(SELECT sno FROM payment where balance=0)

Sno Sname

101 Praveenkumar

102 Ramkumar

SUB QUERIES

Page 135: Leading Software Technologies Chennai

7.Sub Queries using ALL

Sno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

Select stmt where ALL (subquery | expression [ ,...n ]     )

syntax

SELECT * FROM stud WHERE sno <> ALL (SELECT sno FROM payment)

Sno Sname

104 Sathyakar

105 Susi

SUB QUERIES

Page 136: Leading Software Technologies Chennai

8.UPDATE statement in Sub Queries

Sno Sname

100 Preetha

101 Praveenkumar

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 1000

103 7000 3000

Table:Stud

Table:Payment

update stud set sno =sno+1 where sno IN(select sno from payment where balance>1000)

Sno Sname

101 Preetha

101 Praveenkumar

102 Ramkumar

104 Reethu

104 Sathyakar

105 Susi

Result

SUB QUERIES

Page 137: Leading Software Technologies Chennai

9.DELETE statement in Sub Queries

Sno Sname

100 Preetha

101 Praveen

102 Ramkumar

103 Reethu

104 Sathyakar

105 Susi

Sno Amount Balance

100 7000 2000

101 7000 0

102 7000 0

103 7000 3000

Table:Stud

Table:Payment

DELETE stud WHERE sno IN (SELECT sno from payment where balance=0)

Sno Sname

100 Preetha

103 Reethu

104 Sathyakar

105 Susi

Result

SUB QUERIES

Page 138: Leading Software Technologies Chennai

VIEWS AND INDEXES

Page 139: Leading Software Technologies Chennai

VIEWS

A view is a virtual table based on the result-set of a SELECT statement

What is View?

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database

We can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from a single table.

The database design and structure will NOT be affected by the functions, where, or join statements in a view

Page 140: Leading Software Technologies Chennai

The database does not store the view data! The database engine recreates the data, using the view's SELECT statement, every time a user queries a view

Using Views

•A view could be used from inside a query, a stored procedure, or from inside another view. By adding functions, joins, etc., to a view, it allows you to present exactly the data you want to the user

VIEWS

Syntax :

CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition

Page 141: Leading Software Technologies Chennai

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

1)Creating Temporary table using view

Create view v1 as select *from employees

Select *from v1

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Now the employee information should be temporarily stored to view v1

VIEWS

Page 142: Leading Software Technologies Chennai

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees1)Update The view

Employee_Id Name

100 Sachin

101 Dravid

102 Sourvav

update v1 set Name=Sourvav where Employee_id=102

While creating view for single table it should be update but creating view from more than one table shouldn’t updated

VIEWS

Page 143: Leading Software Technologies Chennai

Employee_Id Name

100 Sachin

101 Dravid

102 Ganguly

Table 1 : Employees

Creating view from more than one table

Create view v2 as select Employees.Employee_Id,Employees.Name,Product.Products from employees

Select *from v2

Table 2 : Product

Prod_Id Products Employee_Id

1000 Bat 100

1003 Ball 100

1005 Glouse 101

Employee_Id Name Products

100 Sachin Bat

101 Dravid Ball

102 Ganguly Glouse

VIEWS

Page 144: Leading Software Technologies Chennai

• Indexes help us retrieve data from tables quicker.

• Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes.

INDEXES

Page 145: Leading Software Technologies Chennai

CREATE INDEX

• We can creates an index for table or view.

• Only the table or view owner can create indexes on that table.

• The owner of a table or view can create an index at any time, whether or not there is data in the table. Indexes can be created on tables or views in another database by specifying a qualified database name.

INDEXES

Page 146: Leading Software Technologies Chennai

• CREATE INDEX "INDEX_NAME" ON "TABLE_NAME" (COLUMN_NAME)

• Let's assume that we have the following table,

• TABLE Customer

(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date date)

• and we want to create an index on the column Last_Name, we would type in,

INDEXES

Page 147: Leading Software Technologies Chennai

• CREATE INDEX IDX_CUSTOMER_LAST_NAMEon CUSTOMER (Last_Name)

• If we want to create an index on both City and Country, we would type in,

• CREATE INDEX IDX_CUSTOMER_LOCATIONon CUSTOMER (City, Country)

INDEXES

Page 148: Leading Software Technologies Chennai

STORED PROCEDURES

Page 149: Leading Software Technologies Chennai

A Stored Procedures is a group of Transact-SQL statements compiled into a single execution plan

A precompiled collection of Transact-SQL statements stored under a name and processed as a unit.

SQL Server supplies stored procedures for managing SQL Server and displaying information about databases and users.

SQL Server-supplied stored procedures are called system stored procedures.

STORED PROCEDURES

Page 150: Leading Software Technologies Chennai

Procedures return data in four ways:

Output parameters, which can return either data (such as an integer or character value) or a cursor variable (cursors are result sets that can be retrieved one row at a time).

Return codes, which are always an integer value.

A result set for each SELECT statement contained in the stored procedure or any other stored procedures called by the stored procedure.

A global cursor that can be referenced outside the stored procedure.

STORED PROCEDURES

Page 151: Leading Software Technologies Chennai

CharacteristicsA Precompiled transact Sql statements that stored under a single name.

Compiled once and executed more times

Stored batch of Sql statements

Advantages:

It allows modular programmingSecurity Reduce Network TrafficCompilation speed is much faster than statements

STORED PROCEDURES

Page 152: Leading Software Technologies Chennai

CREATE PROCEDURE

Creates a stored procedure, which is a saved collection of Transact-SQL statements that can take and return user-supplied parameters.

Syntax

Create Procedure Procedure_name(@parameter data_type,…)

As

Begin

--------------------------

SQL Statements

--------------------------

End

STORED PROCEDURES

Page 153: Leading Software Technologies Chennai

Arguments

procedure_name

The name of the new stored procedure. Procedure names must conform to the rules for identifiers and must be unique within the database and its owner.

Rules for Regular Identifiers:

•The first character must be one of the following:

A letter ( a - z or A – Z) The underscore (_),

•Subsequent characters can be:

Letters Decimal numbers

•The identifier must not be a Transact-SQL reserved word. SQL Server reserves both the uppercase and lowercase versions of reserved words.

•Embedded spaces or special characters are not allowed.

STORED PROCEDURES

Page 154: Leading Software Technologies Chennai

@parameter

One or more parameters can be declared in a CREATE PROCEDURE statement.

The value of each declared parameter must be supplied by the user when the procedure is executed (unless a default for the parameter is defined).

A stored procedure can have a maximum of 2,100 parameters.

Specify a parameter name using an at sign (@) as the first character.

The parameter name must conform to the rules for identifiers.

Parameters are local to the procedure; the same parameter names can be used in other procedures.

data_type

It is an attribute that specifies the type of data (integer, character, money, and so on) that the parameter can hold.

The cursor data type can be used only on OUTPUT parameters.

There is no limit on the maximum number of output parameters that can be of cursor data type.

STORED PROCEDURES

Page 155: Leading Software Technologies Chennai

OUTPUT

Indicates that the parameter is a return parameter.

The value of this option can be returned to EXEC[UTE].

Use OUTPUT parameters to return information to the calling procedure.

Text, ntext, and image parameters can be used as OUTPUT parameters.

STORED PROCEDURES

Page 156: Leading Software Technologies Chennai

EXECUTE

Executes a scalar-valued, user-defined function, a system procedure, a user-defined stored procedures, or an extended stored procedure.

Also supports the execution of a character string within a Transact-SQL batch. St

Syntax

EXEC Procedure_name <values>

STORED PROCEDURES

Page 157: Leading Software Technologies Chennai

Create Procedure

INSERT:

Create Procedure emp_insert(

@eno int,

@ename Varchar(10)) As

Begin

Insert into emp values(@eno,@ename)

End

Eno Ename

Table 1:Emp

Exec emp_insert 104,’Praveen’ Eno Ename

104 Praveen

STORED PROCEDURES

Page 158: Leading Software Technologies Chennai

Update Procedure

Update:

Create Procedure emp_Update(

@eno int,

@ename Varchar(10)) As

Begin

Update emp set ename=@ename where eno=@eno

End

Eno Ename

104 Praveen

105 Kumar

Table 1:Emp

Exec emp_Update 105,’Naveen’

Eno Ename

104 Praveen

105 Naveen

STORED PROCEDURES

Page 159: Leading Software Technologies Chennai

Delete Procedure

Update:

Create Procedure emp_Delete(@eno int)

As

Begin

Delete from emp where eno=@eno

End

Eno Ename

104 Praveen

105 Naveen

106 Kumar

Table 1:Emp

Exec emp_Delete 106

Eno Ename

104 Praveen

105 Naveen

STORED PROCEDURES

Page 160: Leading Software Technologies Chennai

Select Procedure

Select:

Create Procedure emp_Select(@eno int)

As

Begin

Select * from emp where eno=@eno

End

Eno Ename

104 Praveen

105 Kumar

Table 1:Emp

Exec emp_Selects 104 Eno Ename

104 PraveenSelect:

Create Procedure emp_Select

As

Begin

Select * from emp

End

Eno Ename

104 Praveen

105 Kumar

Exec emp_Selects

STORED PROCEDURES

Page 161: Leading Software Technologies Chennai

ALTER PROCEDURE

Alters a previously created procedure, created by executing the CREATE PROCEDURE statement, without changing permissions and without affecting any dependent stored procedures or triggers.

ALTER PROCEDURE is used to redefine the stored procedure.

Syntax:

Alter procedure <procedure name>

As

-----

Sql Statements

----

STORED PROCEDURES

Page 162: Leading Software Technologies Chennai

Parameters

Parameters are used to exchange data between stored procedures and the application or tool that called the stored procedure:

Input Parameters

Output Parameters

Input parameters allow the caller to pass a data value to the stored procedure.

Output parameters allow the stored procedure to pass a data value or a cursor variable back to the caller.

Every stored procedure returns an integer return code to the caller. If the stored procedure does not explicitly set a value for the return code, the return code is 0.

STORED PROCEDURES

Page 163: Leading Software Technologies Chennai

ExampleThe following stored procedure shows the use of an input parameters, an output parameters, and a return code:

-- Create a procedure that takes one input

-- and returns one output parameters and a return code.

CREATE PROCEDURE SampleProcedure @EmployeeIDParm INT, @MaxQuantity INT OUTPUT

AS

SELECT FirstName, LastName, Title FROM Employees WHERE EmployeeID = @EmployeeIDParm

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

STORED PROCEDURES

Page 164: Leading Software Technologies Chennai

Find ‘n’th maximum salary using Output parameter

Eno Salary

100 4000

101 7000

102 8000

103 6000

create procedure nmax(@n int,@max numeric output)

as

select @max=max(salary) from emp

while(@n>1)

begin

select @max=max(salary) from emp where salary<@max

set @n=@n-1

end

Return @max

Table 1:Emp

Output : (Second Maximum)

Maximum Value Is:7000

STORED PROCEDURES

Execution Part:

declare @m numeric

exec nmax 2,@max=@m output

print ‘Maximum Value Is:’+@m

Page 165: Leading Software Technologies Chennai

DROP PROCEDURE

Removes one or more stored procedures or groups from the current database.

Syntax:

DROP PROCEDURE procedure_name

STORED PROCEDURES

Page 166: Leading Software Technologies Chennai

TRIGGERS

Page 167: Leading Software Technologies Chennai

A trigger is a special type of stored procedure that is not called directly by a user.

When the trigger is created, it is defined to execute when a specific type of data modification is made against a specific table or column.

TRIGGERS

A trigger is a database object that is attached to a table. In many aspects it is similar to a stored procedure.

As a matter of fact, triggers are often referred to as a "special kind of stored procedure."

The main difference between a trigger and a stored procedure is that the former is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs. You specify the modification action(s) that fire the trigger when it is created.

Page 168: Leading Software Technologies Chennai

Syntax:

Create trigger <trigger name> on <table name>

For insert/update/delete

As

Begin

---------------------

--Sql statements--

----------------------

End

TRIGGERS

Page 169: Leading Software Technologies Chennai

Checking salary condition using Insert Trigger

Create Trigger

create trigger sa on sals

for insert as

begin

declare @salary numeric

select @salary=salary from inserted

if(@salary<1000)

begin

rollback transaction

print 'Salary should be >1000'

End

endInserting values

insert into sals values(100,5000)

Eno Salary

100 5000

Inserting salary as <1000

insert into sals values(100,5000)

1.Table : Sals

Salary should be >1000

Output

TRIGGERS

Page 170: Leading Software Technologies Chennai

Create table

create table sample(eno int,m1 int,m2 int,tot int)

Eno M1 M2 tot

Create trigger

create trigger s on sample

for insert

as

update sample set tot=m1+m2

1.The Trigger is used to insert the values in table then the total should be automatically updated

1.Table:sample

TRIGGERS

Page 171: Leading Software Technologies Chennai

Eno M1 M2 tot

101 90 90 180

102 80 80 160

Inserting values in table

insert into sample(eno,m1,m2)values(101,90,90)

Eno M1 M2 totInserting another value

insert into sample(eno,m1,m2)values(102,80,80)

Select the values from the table

Select *from sample

Here the total should be automatically updated using trigger

1.Table : Sample

2.Table : Sample

TRIGGERS

Page 172: Leading Software Technologies Chennai

Checking salary condition using Update Trigger

Create Trigger

create trigger sa on sals

for update as

begin

declare @salary numeric

select @salary=salary from inserted

if(@salary<1000)

begin

rollback transaction

print ‘ Cannot Update Salary should be >1000'

End

end

Eno Salary

100 5000

Updating salary as <1000

Update sals set salary=500 where eno=100

1.Table : Sals

Cannot Update Salary should be >1000'

Output

TRIGGERS

Page 173: Leading Software Technologies Chennai

Delete Trigger

Transferring one table value to other table using trigger

Eno Salary

100 5000

101 6000

102 8000create trigger ds on employees

for delete as

begin

insert into oldemp select * from deleted

end

1.Table:Employees

2.Table: OldEmp

Eno Salary

Eno Salary

100 5000

101 6000

102 8000

3.Table :OldEmp

TRIGGERS

Page 174: Leading Software Technologies Chennai

CURSORS

Page 175: Leading Software Technologies Chennai

A select statement returns a complete result set which contains all the rows that are qualified in the select statement .

Some applications needs one row or a block of

row at a time.At that time we need cursor Cursor is a logical extension to result set that

fetches single row at a time

Definition: A data type for variables or stored

procedure OUTPUT parameters that contain a reference to a cursor. Any variables created with the cursor data type are null able.

CURSORS

Page 176: Leading Software Technologies Chennai

Allow positioning of a specific row

It retrieves one row or a block of row at current position

Supporting data modification to rows at current position

Used in script,stored procedures and triggers

CURSORS

Page 177: Leading Software Technologies Chennai

Steps in Cursors

The steps followed in cursor

1.DECLARE

2.OPEN

3.FETCH

4.CLOSE

5.DEALLOCATE

CURSORS

Page 178: Leading Software Technologies Chennai

1.DECLARE

Is used to declare the cursor

• Syntax

DECLARE cursor_name CURSOR FOR select_statement

• cursor may be declared as

LOCAL | GLOBAL FORWARD_ONLY | SCROLL STATIC | KEYSET | DYNAMIC

| FAST_FORWARD

2.OPEN

Used to open the cursor

•Syntax

OPEN cursor_name

CURSORS

Page 179: Leading Software Technologies Chennai

• The operation to retrieve a row from a cursor is called a fetch. These are the fetch options:

• FETCH FIRST Fetches the first row in the cursor.

• FETCH NEXT Fetches the row after the last row fetched.

• FETCH PRIOR Fetches the row before the last row fetched.

• FETCH LAST Fetches the last row in the cursor.

• FETCH ABSOLUTE n Fetches the nth row from the first row in the cursor if n is a positive integer. If n is a negative integer, the row n rows before the end of the cursor is fetched. If n is 0, no rows are fetched.

• FETCH RELATIVE n Fetches the row n rows from the last row fetched. If n is positive, the row n rows after the last row fetched is fetched.

3.Fetching and Scrolling

CURSORS

Page 180: Leading Software Technologies Chennai

Fetch Status

Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.

Return value

Description

0 FETCH statement was successful.

-1 FETCH statement failed or the row was beyond the result set.

-2 Row fetched is missing.

CURSORS

Page 181: Leading Software Technologies Chennai

4.CLOSE

Closes an open cursor by releasing the current result set and freeing any cursor locks held on the rows on which the cursor is positioned. Syntax

CLOSE cursor_name

5.DEALLOCATE

Removes a cursor reference.

Syntax

DEALLOCATE cursor_name

CURSORS

Page 182: Leading Software Technologies Chennai

Example for Cursor

DECLARE c1 CURSOR FORSELECT ename FROM empOPEN c1FETCH NEXT FROM c1 WHILE @@FETCH_STATUS = 0BEGINFETCH NEXT FROM c1ENDCLOSE c1DEALLOCATE c1

// -- Check @@FETCH_STATUS to see if there are any more rows to fetch.

Result

Note: cursor fetch single row at a time

Table:Emp

CURSORS

Page 183: Leading Software Technologies Chennai

TYPES OF FETCHING

1.Use FETCH in a simple cursor

2.Use FETCH to store values in variables

3.Declare a SCROLL cursor and use the other FETCH options

CURSORS

Page 184: Leading Software Technologies Chennai

TYPES OF FETCHING

1. Use FETCH in a simple cursorThis example declares a simpleCursor for the rows in employee table  DECLARE c1 CURSOR FOR SELECT * FROM Emp OPEN c1 FETCH NEXT FROM c1 WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM c1 END CLOSE c1 DEALLOCATE c1

RESULT

CURSORS

Page 185: Leading Software Technologies Chennai

2.Use FETCH to store values in variables

• Here the output of the FETCH statements is stored in local variables. The PRINT statement combines the variables into a single string and returns .

  DECLARE @e varchar(40) DECLARE c CURSOR FOR SELECT ename FROM emp WHERE ename LIKE 'p%' OPEN c FETCH NEXT FROM c into @e WHILE @@FETCH_STATUS = 0 BEGIN PRINT @e FETCH NEXT FROM c into @e END CLOSE c DEALLOCATE c

RESULT

pinky

praveenkumar

preetha

Table:Emp

CURSORS

Page 186: Leading Software Technologies Chennai

3. Declare a SCROLL cursor and use the other FETCH options

• This example creates a SCROLL cursor to allow full scrolling capabilities through the LAST, PRIOR, RELATIVE, and ABSOLUTE options.

DECLARE c SCROLL CURSOR FORSELECT ename FROM emp Orderby enameFETCH LAST FROM cFETCH PRIOR FROM cFETCH FIRST FROM cFETCH NEXT FROM cFETCH ABSOLUTE 2 FROM cFETCH RELATIVE 3 FROM cFETCH RELATIVE -2 FROM cCLOSE cDEALLOCATE c 

RESULT

CURSORS

Page 187: Leading Software Technologies Chennai

Cursor used in update

DECLARE c1 CURSOR FORSelect * from empOPEN c1FETCH NEXT FROM c1WHILE @@FETCH_STATUS = 0BEGIN FETCH c1update emp set eno=eno+1 wherecurrent of c1ENDCLOSE c1DEALLOCATE c1

RESULT

Table :Emp

CURSORS

Page 188: Leading Software Technologies Chennai

Cursor used in delete

DECLARE c1 cursor forSelect * from emp where eno=101OPENc1FETCH c1While (@@fetch_status=0)Begin FETCH c1Delete from emp where current ofc1EndCLOSE c1DEALLOCATE c1

Table:Emp

Duplicate record deleted

CURSORS

Page 189: Leading Software Technologies Chennai

Cursor for delete duplicate records

Create procedure noduplicate asDECLARE @e intDECLARE c1 cursor forSelect * from emp where

eno=@eOPEN c1FETCH c1While (@@fetch_status=0)Begin FETCH c1Delete from emp where current

of c1EndCLOSE c1FETCH next from c1 into @eDEALLOCATE c1

Duplicate records deleted

Table:Emp

Note:Duplicate records are not mentioned cursor fetches each row and delete duplicate wherever it occurred

CURSORS

Page 190: Leading Software Technologies Chennai

USER DEFINED DATA TYPES

Page 191: Leading Software Technologies Chennai

RULE

A database object that is bound to columns or user-defined data types, and specifies which data values are acceptable in a column. CHECK constraints provide the same functionality and are preferred because they are in the SQL-92 standard.

A column or user-defined data type can have only one rule bound to it. However, a column can have both a rule and one or more check constraints associated with it. When this is true, all restrictions are evaluated.

USER DEFINED DATA TYPES

Page 192: Leading Software Technologies Chennai

Syntax

CREATE RULE rule AS condition_expression

ArgumentsruleIs the name of the new rule. Rule names must conform to the rules for identifiers. Specifying the rule owner name is optional.condition_expressionIs the condition(s) defining the rule. A rule can be any expression valid in a WHERE clause and can include such elements as arithmetic operators, relational operators, and predicates (for example, IN, LIKE, BETWEEN). A rule can be created only in the current database. After creating a rule, execute sp_bindrule to bind the rule to a column or to a user-defined data type.

Examples

CREATE RULE range_rule AS @range >= $1000 AND @range < $20000

USER DEFINED DATA TYPES

Page 193: Leading Software Technologies Chennai

User-defined data types are based on the system data types in SQL Server. User-defined data types can be used when several tables must store the same type of data in a column and you must ensure that these columns have exactly the same data type, length, and null ability. For example, a user-defined data type called postal_code could be created based on the char data type.

When a user-defined data type is created, you must supply these parameters:

NameSystem data type upon which the new data type is based

Syntax

sp_addtype [ @typename = ] type,[ , [ @nulltype = ] 'null_type' ]

USER DEFINED DATA TYPES

Page 194: Leading Software Technologies Chennai

Arguments

[@typename =] typeIs the name of the user-defined data type. Data type names must follow the rules for identifiers and must be unique in each database.

[@nulltype =] 'null_type‘Indicates the way the user-defined data type handles null values. null_type is varchar(8), with a default of NULL, and must be enclosed in single quotation marks ('NULL', 'NOT NULL', or 'NONULL'). If null_type is not explicitly defined by sp_addtype, it is set to the current default nullability.   

Examples with Not Null

EXEC sp_addtype gend, 'VARCHAR(6)', 'NOT NULL'

Used in tables

Create table emp(sno int,gender gend)

Examples With Null

EXEC sp_addtype birthday, datetime, 'NULL'

Used in Tables

Create table emp(sno int,dob birthday)

USER DEFINED DATA TYPES

Page 195: Leading Software Technologies Chennai

Drop user-Defined Type

Syntax:

sp_droptype [ @typename = ] 'type'

Arguments

[@typename =] 'type'

Is the name of a user-defined data type that you own. type is sysname, with no default.

Examples

This example drops the user-defined data type birthday.

Note  This user-defined data type must already exist or this example returns an error message.

EXEC sp_droptype 'birthday'

USER DEFINED DATA TYPES

Page 196: Leading Software Technologies Chennai

Normalization

Page 197: Leading Software Technologies Chennai

Normalization

• The purpose of normailization

• Functional Dependencies

• The Process of Normalization

• First Normal Form (1NF)

• Second Normal Form (2NF)

• Third Normal Form (3NF)

• Boyce-Codd Normal Form (BCNF)

• Fourth Normal Form (4NF)

• Fifth Normal Form (5NF)

Page 198: Leading Software Technologies Chennai

The Purpose of Normalization

Normalization is a technique for producing a set of relations with desirable properties, given the data requirements of an enterprise.

The process of normalization is a formal method that identifies relations based on their primary or candidatekeys and the functional dependencies among their attributes.

Page 199: Leading Software Technologies Chennai

Functional Dependencies

Functional dependency describes the relationship betweenattributes in a relation.For example, if A and B are attributes of relation R, and B is functionally dependent on A ( denoted A B), if each value ofA is associated with exactly one value of B. ( A and B may eachconsist of one or more attributes.)

A BB is functionally

dependent on A

Determinant Refers to the attribute or group of attributes on the left-hand side of the arrow of a functional dependency

Page 200: Leading Software Technologies Chennai

Trival functional dependency means that the right-handside is a subset ( not necessarily a proper subset) of the left-hand side.

Functional Dependencies (2)

For example: (See Figure 1)staffNo, sName sNamestaffNo, sName staffNo

They do not provide any additional information about possible integrity constraints on the values held by these attributes.

We are normally more interested in nontrivial dependencies because they represent integrity constraints for the relation.

Page 201: Leading Software Technologies Chennai

Functional Dependencies

Main characteristics of functional dependencies in normalization

• Have a one-to-one relationship between attribute(s) on the left- and right- hand side of a dependency;

• hold for all time;

• are nontrivial.

Page 202: Leading Software Technologies Chennai

Identifying the primary key

Functional dependency is a property of the meaning or semantics of the attributes in a relation. When a functional dependency is present, the dependency is specified as a constraint between the attributes.

An important integrity constraint to consider first is the

identification of candidate keys, one of which is selected to

be the primary key for the relation using functional dependency.

Functional Dependencies

Page 203: Leading Software Technologies Chennai

Functional Dependencies

Inference RulesA set of all functional dependencies that are implied by a givenset of functional dependencies X is called closure of X, writtenX+. A set of inference rule is needed to compute X+ from X.Armstrong’s axioms

1. Relfexivity: If B is a subset of A, them A B2. Augmentation: If A B, then A, C B3. Transitivity: If A B and B C, then A C4. Self-determination: A A5. Decomposition: If A B,C then A B and A

C6. Union: If A B and A C, then A B,C7. Composition: If A B and C D, then A,C B,

Page 204: Leading Software Technologies Chennai

Minial Sets of Functional Dependencies

A set of functional dependencies X is minimal if it satisfies the following condition:

• Every dependency in X has a single attribute on its right-hand side

• We cannot replace any dependency A B in X withdependency C B, where C is a proper subset of A, andstill have a set of dependencies that is equivalent to X.

• We cannot remove any dependency from X and still have a set of dependencies that is equivalent to X.

Functional Dependencies

Page 205: Leading Software Technologies Chennai

Example of A Minial Sets of Functional Dependencies

A set of functional dependencies for the StaffBranch relation satisfies the three conditions for producing a minimal set.

staffNo sNamestaffNo positionstaffNo salarystaffNo branchNostaffNo bAddressbranchNo bAddressbranchNo, position salarybAddress, position salary

Functional Dependencies

Page 206: Leading Software Technologies Chennai

The Process of Normalization

• Normalization is often executed as a series of steps. Each step corresponds to a specific normal form that has known properties.

• As normalization proceeds, the relations become progressively more restricted in format, and also less vulnerable to update anomalies.

• For the relational data model, it is important to recognize thatit is only first normal form (1NF) that is critical in creatingrelations. All the subsequent normal forms are optional.

Page 207: Leading Software Technologies Chennai

First Normal Form (1NF)

Unnormalized form (UNF)A table that contains one or more repeating groups.

ClientNo cName propertyNo pAddress rentStart rentFinish rent ownerNo oName

CR76John

kay

PG4

PG16

6 lawrence

St,Glasgow

5 Novar Dr,

Glasgow

1-Jul-00

1-Sep-02

31-Aug-01

1-Sep-02

350

450

CO40

CO93

Tina Murphy

Tony Shaw

CR56Aline

Stewart

PG4

PG36

PG16

6 lawrence

St,Glasgow

2 Manor Rd,

Glasgow

5 Novar Dr,

Glasgow

1-Sep-99

10-Oct-00

1-Nov-02

10-Jun-00

1-Dec-01

1-Aug-03

350

370

450

CO40

CO93

CO93

Tina Murphy

Tony Shaw

Tony Shaw

Figure 3 ClientRental unnormalized table

Repeating group = (propertyNo, pAddress, rentStart, rentFinish, rent, ownerNo, oName)

Page 208: Leading Software Technologies Chennai

Definition of 1NF

First Normal Form is a relation in which the intersection of eachrow and column contains one and only one value.

There are two approaches to removing repeating groups from unnormalized tables:

1. Removes the repeating groups by entering appropriate data in the empty columns of rows containing the repeating data.

2. Removes the repeating group by placing the repeating data, along with a copy of the original key attribute(s), in a separate relation. A primary key is identified for the new relation.

Page 209: Leading Software Technologies Chennai

1NF ClientRental relation with the first approach

ClientNo propertyNo cName pAddress rentStart rentFinish rent ownerNo oName

CR76 PG4John

Kay

6 lawrence

St,Glasgow1-Jul-00 31-Aug-01 350 CO40

Tina Murphy

CR76 PG16John

Kay

5 Novar Dr,

Glasgow1-Sep-02 1-Sep-02 450 CO93

Tony Shaw

CR56 PG4Aline

Stewart

6 lawrence

St,Glasgow1-Sep-99 10-Jun-00 350 CO40

Tina Murphy

CR56 PG36Aline

Stewart

2 Manor Rd,

Glasgow10-Oct-00 1-Dec-01 370 CO93

Tony Shaw

CR56 PG16Aline

Stewart

5 Novar Dr,

Glasgow1-Nov-02 1-Aug-03 450 CO93

Tony Shaw

Figure 4 1NF ClientRental relation with the first approach

The ClientRental relation is defined as follows,ClientRental ( clientNo, propertyNo, cName, pAddress, rentStart, rentFinish, rent,

ownerNo, oName)

With the first approach, we remove the repeating group(property rented details) by entering the appropriate client data into each row.

Page 210: Leading Software Technologies Chennai

1NF ClientRental relation with the second approach

With the second approach, we remove the repeating group (property rented details) by placing the repeating data along with a copy of the original key attribute (clientNo) in a separte relation.

Client (clientNo, cName)PropertyRentalOwner (clientNo, propertyNo, pAddress, rentStart,

rentFinish, rent, ownerNo, oName)ClientNo cName

CR76 John Kay

CR56 Aline Stewart

ClientNo propertyNo pAddress rentStart rentFinish rent ownerNo oName

CR76 PG46 lawrence

St,Glasgow1-Jul-00 31-Aug-01 350 CO40

Tina Murphy

CR76 PG165 Novar Dr,

Glasgow1-Sep-02 1-Sep-02 450 CO93

Tony Shaw

CR56 PG46 lawrence

St,Glasgow1-Sep-99 10-Jun-00 350 CO40

Tina Murphy

CR56 PG362 Manor Rd,

Glasgow10-Oct-00 1-Dec-01 370 CO93

Tony Shaw

CR56 PG165 Novar Dr,

Glasgow1-Nov-02 1-Aug-03 450 CO93

Tony Shaw

Figure 5 1NF ClientRental relation with the second approach

Page 211: Leading Software Technologies Chennai

Full functional dependency

Full functional dependency indicates that if A and B are attributes of a relation, B is fully functionally dependent on A if B is functionally dependent on A, but not on any proper subset of A.

A functional dependency AB is partially dependent if there is some attributes that can be removed from A and the dependency still holds.

Page 212: Leading Software Technologies Chennai

Second Normal Form (2NF)

Second normal form (2NF) is a relation that is in first normal form and every non-primary-key attribute is fully functionally dependent on the primary key.

The normalization of 1NF relations to 2NF involves theremoval of partial dependencies. If a partial dependency exists, we remove the function dependent attributes fromthe relation by placing them in a new relation along witha copy of their determinant.

Page 213: Leading Software Technologies Chennai

2NF ClientRental relation

The ClientRental relation has the following functional dependencies:

fd1 clientNo, propertyNo rentStart, rentFinish (Primary Key)fd2 clientNo cName (Partial dependency)fd3 propertyNo pAddress, rent, ownerNo, oName (Partial dependency)fd4 ownerNo oName (Transitive Dependency)fd5 clientNo, rentStart propertyNo, pAddress,

rentFinish, rent, ownerNo, oName (Candidate key)fd6 propertyNo, rentStart clientNo, cName, rentFinish (Candidate key)

Page 214: Leading Software Technologies Chennai

2NF ClientRental relationAfter removing the partial dependencies, the creation of the three new relations called Client, Rental, and PropertyOwner

ClientNo cNameCR76 John Kay

CR56 Aline Stewart

Client

ClientNo propertyNo rentStart rentFinishCR76 PG4 1-Jul-00 31-Aug-01

CR76 PG16 1-Sep-02 1-Sep-02

CR56 PG4 1-Sep-99 10-Jun-00

CR56 PG36 10-Oct-00 1-Dec-01

CR56 PG16 1-Nov-02 1-Aug-03

Rental

propertyNo pAddress rent ownerNo oName

PG4 6 lawrence St,Glasgow 350 CO40 Tina Murphy

PG16 5 Novar Dr, Glasgow 450 CO93 Tony Shaw

PG36 2 Manor Rd, Glasgow 370 CO93 Tony Shaw

PropertyOwner

Client (clientNo, cName)Rental (clientNo, propertyNo, rentStart, rentFinish)PropertyOwner (propertyNo, pAddress, rent, ownerNo, oName)

Figure 6 2NF ClientRental relation

Page 215: Leading Software Technologies Chennai

Third Normal Form (3NF)Transitive dependency A condition where A, B, and C are attributes of a relation such thatif A B and B C, then C is transitively dependent on A via B(provided that A is not functionally dependent on B or C).

Third normal form (3NF)A relation that is in first and second normal form, and in which no non-primary-key attribute is transitively dependent on the primary key.

The normalization of 2NF relations to 3NF involves the removal of transitive dependencies by placing the attribute(s) in a new relation along with a copy of the determinant.

Page 216: Leading Software Technologies Chennai

3NF ClientRental relation

The functional dependencies for the Client, Rental and PropertyOwner relations are as follows:

Clientfd2 clientNo cName (Primary Key)

Rentalfd1 clientNo, propertyNo rentStart, rentFinish (Primary Key)fd5 clientNo, rentStart propertyNo, rentFinish (Candidate key)fd6 propertyNo, rentStart clientNo, rentFinish (Candidate key)

PropertyOwnerfd3 propertyNo pAddress, rent, ownerNo, oName (Primary Key)fd4 ownerNo oName (Transitive Dependency)

Page 217: Leading Software Technologies Chennai

3NF ClientRental relation

The resulting 3NF relations have the forms:

Client (clientNo, cName)Rental (clientNo, propertyNo, rentStart, rentFinish)PropertyOwner (propertyNo, pAddress, rent, ownerNo)Owner (ownerNo, oName)

Page 218: Leading Software Technologies Chennai

ClientNo cNameCR76 John Kay

CR56 Aline Stewart

ClientClientNo propertyNo rentStart rentFinishCR76 PG4 1-Jul-00 31-Aug-01

CR76 PG16 1-Sep-02 1-Sep-02

CR56 PG4 1-Sep-99 10-Jun-00

CR56 PG36 10-Oct-00 1-Dec-01

CR56 PG16 1-Nov-02 1-Aug-03

Rental

propertyNo pAddress rent ownerNo

PG4 6 lawrence St,Glasgow 350 CO40

PG16 5 Novar Dr, Glasgow 450 CO93

PG36 2 Manor Rd, Glasgow 370 CO93

PropertyOwner

3NF ClientRental relation

ownerNo oName

CO40 Tina Murphy

CO93 Tony Shaw

Owner

Figure 7 2NF ClientRental relation

Page 219: Leading Software Technologies Chennai

Boyce-Codd Normal Form (BCNF)

Boyce-Codd normal form (BCNF)A relation is in BCNF, if and only if, every determinant is a candidate key.

The difference between 3NF and BCNF is that for a functionaldependency A B, 3NF allows this dependency in a relation if B is a primary-key attribute and A is not a candidate key, whereas BCNF insists that for this dependency to remain in arelation, A must be a candidate key.

Page 220: Leading Software Technologies Chennai

Example of BCNF

fd1 clientNo, interviewDate interviewTime, staffNo, roomNo (Primary Key)fd2 staffNo, interviewDate, interviewTime clientNo (Candidate key)fd3 roomNo, interviewDate, interviewTime clientNo, staffNo (Candidate key)fd4 staffNo, interviewDate roomNo (not a candidate key)

As a consequece the ClientInterview relation may suffer from update anmalies.For example, two tuples have to be updated if the roomNo need be changed for staffNo SG5 on the 13-May-02.

ClientNo interviewDate interviewTime staffNo roomNoCR76 13-May-02 10.30 SG5 G101

CR76 13-May-02 12.00 SG5 G101

CR74 13-May-02 12.00 SG37 G102

CR56 1-Jul-02 10.30 SG5 G102

Figure 8 ClientInterview relation

ClientInterview

Page 221: Leading Software Technologies Chennai

Example of BCNF(2)

To transform the ClientInterview relation to BCNF, we must remove the violating functional dependency by creating two new relations called Interview and SatffRoom as shown below,

Interview (clientNo, interviewDate, interviewTime, staffNo)StaffRoom(staffNo, interviewDate, roomNo)

ClientNo interviewDate interviewTime staffNoCR76 13-May-02 10.30 SG5

CR76 13-May-02 12.00 SG5

CR74 13-May-02 12.00 SG37

CR56 1-Jul-02 10.30 SG5

staffNo interviewDate roomNoSG5 13-May-02 G101

SG37 13-May-02 G102

SG5 1-Jul-02 G102

Interview

StaffRoom

Figure 9 BCNF Interview and StaffRoom relations

Page 222: Leading Software Technologies Chennai

Fourth Normal Form (4NF)Multi-valued dependency (MVD) represents a dependency between attributes (for example, A, B and C) in a relation, such that for each value of A there is a set of values for B and a set of value for C. However, the set of values for B and C are independent of each other.

A multi-valued dependency can be further defined as being trivial or nontrivial. A MVD A > B in relation R is defined as being trivial if

• B is a subset of A or• A U B = R

A MVD is defined as being nontrivial if neither of the above twoconditions is satisfied.

Page 223: Leading Software Technologies Chennai

Fourth Normal Form (4NF)

Fourth normal form (4NF) A relation that is in Boyce-Codd normal form and containsno nontrivial multi-valued dependencies.

Page 224: Leading Software Technologies Chennai

Fifth Normal Form (5NF)Lossless-join dependencyA property of decomposition, which ensures that no spurioustuples are generated when relations are reunited through anatural join operation.

Join dependencyDescribes a type of dependency. For example, for a relation R with subsets of the attributes of R denoted as A, B, …, Z, arelation R satisfies a join dependency if, and only if, every legal value of R is equal to the join of its projections on A, B, …, Z.

Fifth normal form (5NF)A relation that has no join dependency.

Page 225: Leading Software Technologies Chennai
Page 226: Leading Software Technologies Chennai