You are on page 1of 226

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
INTRODUCTION
INTRODUCTION

 What is Database?

 Basic Database Concepts

 Introduction to DBMS.

 Data Model.

 Introduction to RDBMS.

 DBMS Vs RDBMS
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
What is a Database?

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.
Basic Database Concepts

 Field
– A single item of data Name: Rahul
common to all records

 Record Name: Rahul


College: SSNA
– A collection of data Tel: 9942131251
about an individual item

 Table Name: Rahul


– A set of related records College: SSNA
Tel: 9942131251
Basic Database Concepts

Example of Table :

Fields

Records Name Qualification Phone College


Rahul MSC 9942131251 SSNA
Harris MCA 9840945849 SRM
Priya BE 9834756906 MIT
Data Base Management System (DBMS)

A set of generalized system software for creating and


manipulating large databases, whose interfaces provide a broad
range of languages to aid all users

Application

DBMS

Database
Data Model

• 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

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

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

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.
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.
DBMS Vs. RDBMS

DBMS RDBMS

1.Set of data and tools to manage 1.Same as DBMS - Will Support


those data. - Will not support RELATION SHIP between Tables. -
RELATION SHIP between data. - Ex : Ex : - ORACLE,SQL 2000,DB 2 ...
- Foxpro data files and earlier Ms  
Access.
2.In DBMS only one user can access 2.In RDBMS many users
 the same database, at the same time 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.
 
SQL SERVER BASICS
SQL SEVER BASICS

 Introduction

 Data Type

 Working with Query Analyzer

 SQL Components
SQL

• 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

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

• 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.
Data Types

Binary data types Date and Time data types

Special data types Text and image data types

Unicode Character data types


Numeric data types

Integer data Character data types


types
Monetary data types User-Defined data types
Data Types

CHARACTER DATA TYPES

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

DATE AND TIME DATA TYPES

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.

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.
Data Types

NUMERIC DATATYPES

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

•NUMERIC[(P[, S])]

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.

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.
Data Types

NUMERIC DATATYPES (Cont.)

•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.
Data Types

INTEGER DATATYPES

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

MONETARY DATATYPES

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
Data Types

SPECIAL DATATYPES

•BIT
•SQL_VARIANT
•TIMESTAMP
•UNIQUEIDENTIFIER

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.
Data Types

SPECIAL DATATYPES (Cont.)

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

TEXT AND IMAGE DATATYPES

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.

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.
Data Types

UNICODE CHARACTER DATATYPES

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.

There are two unicode character datatypes:

NCHAR[(N)]
NVARCHAR[(N)]
Data Types

BINARY DATA TYPES

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.
Working with Query Analyzer

To start SQL SERVER

Start

Programs

MicrosoftSQLSERVER

Enterprise Manager Query Analyzer

Query analyzer
Working with Query Analyzer

Query Analyzer
Working with Query Analyzer

Server name

To log
Working with Query Analyzer

Create a new database named as


Ebidding
Working with Query Analyzer

Select the Query and Press F5 to


run the query
Working with Query Analyzer

Use command

• The USE command selects a database to use for future


processing.

Syntax

Use <databasename>
SQL Components

SQL

DDL DML DCL

RDBMS Structure Data I/O DBA Activities


Create/Delete DBs Create Record Create Users
Create/Delete Tables Read Record Delete Users
Alter Tables Update Record Grant privileges
Implement Access
Delete Record Security
DATA DEFINITION LANGUAGE
DATA DEFINITION LANGUAGE

 CREATE

 ALETR

 DROP
Data Definition Language (DDL)

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


DDL - CREATE

CREATE Table using Constraints


Syntax :
Create table <table name >(  
column name1 data type , Table 1: Employee
 
column name2 data type Eno varchar(10)
Ename varchar(100)
…….
Dateofbirth varchar(100)
) Salary int

Example :

Create table Employee (


Eno varchar(10),
Empname varchar(100),
Dateofbirth varchar(100),
Salary Numeric )
DDL - ALTER

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


constraints.

Syntax 1: Alter a table to add a new column Table 1 : Employee

Eno EmpName Dateofbirth Salary


ALTER TABLE <table name >
ADD column name1 data type

Example : Add “Age” column to Employee table

Table 1 : Altered table Employee


ALTER TABLE Employee
ADD age INT

Table 1: Employee Eno EmpName Dateofbirth Salary Age


 
Eno varchar(10)
Ename varchar(100)
Dateofbirth varchar(100)
Salary int
Age int
DDL - ALTER

Table 1 : Employee
Syntax 1: Modify Existing Column

Table 1: Employee
ALTER TABLE <table name >
 
ALTER column name1 data type Eno varchar(10)
Ename varchar(100)
Dateofbirth varchar(100)
Example : Modify “DateofBirth” data type to
DATETIME Salary int

ALTER TABLE Employee Table 1 : Altered table Employee


ALTER COLUMN DateofBirth DateTime

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

Salary int
DDL - ALTER

Table 1 : Employee
Syntax : Alter table to drop column
Eno EmpName Dateofbirth Salary Age
ALTER TABLE <Table Name>
DROP COLUMN <Columnname>

Example: Remove “Age” from Employee Table

Table 1 : Altered table Employee


ALTER TABLE Employee
DROP COLUMN Age
Eno EmpName Dateofbirth Salary
DDL - DROP

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

Syntax :
DROP TABLE <table name >

Example :
DROP TABLE Employee

Drop should destroy the values and structure of the table


DATA MANIPULATION LANGUAGE
DATA MANIPULATION LANGUAGE

 INSERT

 UPDATE

 DELETE

 SELECT
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
DML – INSERT

INSERT Statement is used to insert data into Database


table
 
Syntax : Simple Insert Table 1: Employee
 
INSERT INTO TableName Eno varchar(10)
VALUES(Fieldvalue1,Field Value2 …) Ename varchar(100)
Dateofbirth Datetime
Salary int

Example :
INSERT INTO Employee VALUES
(‘LST/1001’,’Menaga’,’05/22/1982’,12000)
Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 12000

Note :
Varchar,Char and DateTime values
should be given with single quotes. (Eg) ‘Menaga’
DML – INSERT

Insert data with fewer values than columns

 
Syntax : Table 1: Employee
 
INSERT INTO Eno varchar(10)
TableName(Field1,Field2…) Ename varchar(100)
VALUES(Fieldvalue1,Field Value2 …) Dateofbirth Datetime
Salary int

Example :
INSERT INTO Employee(Eno,Ename)
VALUES(‘LST/1001’,’Menaga’) Eno EmpName Dateofbirth Salary

LST/1001 Menaga

Note : Insert All not null values.


DML – INSERT

Insert data from Other table

 
Syntax : Table 1: Employee
 
INSERT INTO Eno varchar(10)
TableName(Field1,Field2…) Ename varchar(100)
SELECT(Fieldvalue1,Field Value2 …) Dateofbirth Datetime
Salary int

Example :
INSERT INTO Employee(Eno,Ename)
SELECT Eno,Ename FROM OldEmp Eno EmpName Dateofbirth Salary

LST/1001 Menaga

Note : Insert All not null values.


DML – INSERT

Insert data from Some otherFile System(Eg.


Notepad,XML)
Example File Format is :
Syntax :
LST/1001 * Menaga * 05/22/1982 * 10000>
BULK INSERT database_name.dbo.table_name  LST/1002 * Kavitha * 07/10/1982 * 12000>
FROM 'data_file'
     WITH
   (   FIELDTERMINATOR ='field_terminator‘,
ROWTERMINATOR = 'row_terminator' )

Example :
BULK INSERT Master.dbo.Employee
FROM ‘C://empdetails.txt’'
WITH Eno EmpName Dateofbirth Salary
 (  FIELDTERMINATOR=‘*‘,
LST/1001 Menaga 05/22/1982 10000
ROWTERMINATOR = ‘ > ' )

LST/1002 Kavitha 07/10/1982 12000


DML - UPDATE

UPDATE Statement is used to update data into Database Table 1 : Employee


table
Eno EmpName Dateofbirth Salary
LST/1001 Menaga 22/05/1982 12000
Syntax :
LST/1002 Kavitha 10/07/1982 15000
UPDATE <tablename> SET columname=value LST/1003 Shakthi 12/05/1985 12000
WHERE conditon
LST/1004 Karthik 15/09/1980 20000

Eno EmpName Dateofbirth Salary


1) Simple Update LST/1001 Menaga 22/05/1982 20000
LST/1002 Kavitha 10/07/1982 20000
UPDATE Employee Set salary=20000
LST/1003 Shakthi 12/05/1985 20000
LST/1004 Karthik 15/09/1980 20000

2).More than 2 values with Condition

Eno EmpName Dateofbirth Salary

LST/1001 Menaga 22/05/1982 20000


UPDATE employee SET
salary=50000,Empname=‘Preetha’ LST/1002 Kavitha 10/07/1982 20000

WHERE Eno=‘LST/1003’ LST/1003 Preetha 12/05/1985 50000

LST/1004 Meena 15/09/1980 20000


DML - DELETE

DELETE Statement is used to delete data from Database Table 1 : Employee


table
Eno EmpName Dateofbirth Salary
Syntax : LST/1001 Menaga 22/05/1982 12000
DELETE FROM <tablename> LST/1002 Kavitha 10/07/1982 15000

WHERE conditon LST/1003 Shakthi 12/05/1985 12000


LST/1004 Karthik 15/09/1980 20000

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

Eno EmpName Dateofbirth Salary


DELETE FROM Employee
LST/1001 Menaga 22/05/1982 12000
WHERE eno=‘LST/1004’ LST/1002 Kavitha 10/07/1982 15000
LST/1003 Shakthi 12/05/1985 12000

2.) Delete all records in Employee

Delete values only not structure


DELETE FROM Employee of the table
DML - SELECT

SELECT is Used to retrieve the data from the


database Table

Syntax:
SELECT * From <tablename>
WHERE Condition Table 1 : Employee

SELECT Field1,Field2.. FROM TableName Eno EmpName Dateofbirth Salary


LST/1001 Menaga 22/05/1982 12000
WHERE Condition
LST/1002 Kavitha 10/07/1982 15000
1) Display Employee details LST/1003 Shakthi 12/05/1985 12000
LST/1004 Karthik 15/09/1980 20000
SELECT * FROM Employee

2) Display all the details of Employee no


‘LST/1001’
Eno EmpName Dateofbirth Salary
SELECT * FROM Employee WHERE LST/1001 Menaga 22/05/1982 12000
Eno=‘LST/10001’
DML - SELECT

Table 1 : Employee
SELECT USING ORDER BY
Eno EmpName Dateofbirth Salary
Arrange the Rows by Ascending or Descending
LST/1001 Menaga 22/05/1982 12000
LST/1002 Kavitha 10/07/1982 15000

Syntax : LST/1003 Sakthi 12/05/1985 12000


LST/1004 Karthik 15/09/1980 20000
SELECT * FROM tablename
ORDER BY Fieldname ASC/DESC ORDER BY ASC
Eno EmpName Dateofbirth Salary

* By default is is Ascending LST/1004 Karthik 15/09/1980 20000


LST/1002 Kavitha 10/07/1982 15000
LST/1001 Menaga 22/05/1982 12000
Example : LST/1003 Sakthi 12/05/1985 12000

SELECT * FROM Employee


ORDER BY DESC
ORDER BY Empname
Eno EmpName Dateofbirth Salary
LST/1003 Sakthi 12/05/1985 12000
SELECT * FROM Employee LST/1001 Menaga 22/05/1982 12000
ORDER BY Empname DESC LST/1002 Kavitha 10/07/1982 15000
LST/1004 Karthik 15/09/1980 20000
DML - SELECT

SELECT DISTINCT Table 1 : Employee

The DISTINCT keyword eliminates Eno EmpName Dateofbirth Salary


duplicate rows from the results of a SELECT statement. LST/1001 Menaga 22/05/1982 12000
If DISTINCT is not specified, all rows are returned, LST/1002 Kavitha 10/07/1982 15000
including duplicates. LST/1003 Karthik 12/05/1985 12000
LST/1004 Karthik 15/09/1980 20000

Syntax :
With out Distinct
SELECT DISTINCT( Field Name) FROM TableName
EmpName
Menaga
Kavitha
Example : Karthik
SELECT Empname FROM Employee Karthik

Using Distinct
EmpName
SELECT DISTINCT( Empname) FROM Employee Menaga
Kavitha
Karthik
DML - SELECT

SELECT USING LOGICAL OPERATORS Table 1 : Employee

The Where Conditions may includes the Eno EmpName Dateofbirth Salary
following logical operatos: AND , OR , NOT LST/1001 Menaga 22/05/1982 12000
LST/1002 Kavitha 10/07/1982 15000
AND - Both Conditions should be True. LST/1003 Karthik 12/05/1985 12000
OR - Both or Any one of the Condition should be True
LST/1004 Karthik 15/09/1980 20000
NOT – If Condition is True then return False
If Condition is False then return True
AND
Example : Eno EmpName Dateofbirth Salary
SELECT * FROM Employee LST/1001 Menaga 22/05/1982 12000

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


Eno EmpName Dateofbirth Salary
SELECT * FROM TableName LST/1001 Menaga 22/05/1982 12000

WHERE Eno=‘LST/1001’ OR Salary=12000 LST/1003 Karthik 12/05/1985 12000

Not
SELECT * FROM TableName Eno EmpName Dateofbirth Salary

WHERE NOT (Salary=12000) LST/1002 Kavitha 10/07/1982 15000


LST/1004 Karthik 15/09/1980 20000
DML - SELECT

Table 1 : Employee
SELECT USING BETWEEN
Eno EmpName Dateofbirth Salary
BETWEEN Specifies a range to test.
LST/1001 Menaga 22/05/1982 12000
LST/1002 Kavitha 10/07/1982 15000

Syntax : LST/1003 Sakthi 12/05/1985 12000


LST/1004 Karthik 15/09/1980 20000
SELECT * FROM tablename
WHERE Fieldname BETWEEN value1 AND value2

BETWEEN

Example : Eno EmpName Dateofbirth Salary

SELECT * FROM Employee LST/1002 Kavitha 10/07/1982 15000


LST/1004 Karthik 15/09/1980 20000
WHERE Salary BETWEEN 15000 AND 20000
DML - SELECT

Table 1 : Employee
SELECT USING LIKE
Eno EmpName Dateofbirth Salary
Determines whether or not a given character
LST/1001 Menaga 22/05/1982 12000
string matches a specified pattern.
LST/1002 Kavitha 10/07/1982 15000

Syntax : LST/1003 Sakthi 12/05/1985 12000


LST/1004 Karthik 15/09/1980 20000
SELECT * FROM tablename
WHERE Fieldname LIKE ‘%Characterstring%’

% - Indicated any string before and after

Example : Select Employee details whose name starts LIKE


with ‘K’

Eno EmpName Dateofbirth Salary


SELECT * FROM Employee LST/1002 Kavitha 10/07/1982 15000

WHERE EmpName LIKE ‘ K %’ LST/1004 Karthik 15/09/1980 20000


DML - SELECT

Table 1 : Employee
SELECT USING GROUP BY
Eno EmpName Dateofbirth Salary
•The GROUP BY clause is used to group the
LST/1001 Menaga 22/05/1982 12000
output of the WHERE clause.
Syntax : LST/1002 Kavitha 10/07/1982 15000
LST/1003 Sakthi 12/05/1985 12000
SELECT [ALL | DISTINCT] LST/1004 Karthik 15/09/1980 20000
columnname1 [,columnname2] FROM
tablename1 [,tablename2] [WHERE Using WHERE
condition] [ and|or condition...]
15000
[GROUP BY column-list] [HAVING
20000
"conditions] [ORDER BY "column-list"
[ASC | DESC] ]
Example :
SELECT SUM(salary) FROM Employee where
Using Having
salary >12000 GROUP BY Eno

Example : Kavitha
SELECT EmpName FROM EMPLOYEE Karthik
GROUP BY SALARY HAVING EMPNAME LIKE ‘k%'
DML - SELECT

UNION

•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
1)Combining Two Tables

Table 1 : Employees_Chennai
SELECT E_Name FROM Employees_Chennai
UNION Employee_Id Name
SELECT E_Name FROM Employees_Banglore 100 Sachin
101 Dravid
Name
102 Ganguly
Sachin
Dravid

Ganguly
Table 2 :Employees_Banglore
Kumble

Prasad Employee_Id Name

Agarkar 100 Saachin

101 Kumble

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

UNION ALL

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
1)Combining Two Tables

Table 1 : Employees_Chennai
SELECT E_Name FROM Employees_Chennai
UNION ALL Employee_Id Name
SELECT E_Name FROM mployees_Banglore 100 Sachin
101 Dravid
Name
102 Ganguly
Sachin
Sachin
Dravid
Table 2 :Employees_Banglore
Kumble
Prasad Employee_Id Name

Agarkar 100 Sachin

101 Kumble

102 Prasad
This command can be used to list all employees in
Chennai and Banglore. In the example above we 103 Agarkar
have two employees with equal names, and all of
them is listed.
DATA CONTROL LANGUAGE
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.
CONSTRAINTS
CONSTRAINTS

 PRIMARY KEY

 FOREIGN KEY

 CHECK

 DEFAULT

 NULL
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
CONSTRAINTS

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.

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

 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
1.PRIMARY KEY CONSTRAINT
Create table table name (column name data type
prmary key

create table product (pcode int primary key ,pname Table 1 : Product
varchar(100))
Pcode Pname
Pcode Pname
100 Rin
100 Rin
101 Surf
101 Surf
. 102 Ariel
102 Ariel
103 Power
103 Power

Create table tablename (Column name data type foreign Table 2 : Order
key references primarykey tablename(columnname)
Pcode Orderid
100 Ord100
2.FOREIGN KEY CONSTRAINT
101 Ord101
Pcode Orderid 101 Ord102
100 Ord100 102 Ord103
101 Ord101
101 Ord102
102 Ord103
INSERT statement conflicted with COLUMN
FOREIGN KEY constraint
create table orders (pcode int foreignkey references 'FK__orders__pcode__76A18A26'. The conflict
product(pcode),orderid varchar(100)) occurred in database 'master', table 'product',
column 'pcode'.
insert into orders values(104,'ord105' ) The statement has been terminated.

Note:Pcode 104 is not belongs to product


3.CHECK CONSTRAINT

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

Product
Table 1 : Product
Pcode Pname
Pcode int
Pname varchar(100) 100 Rin
Price numeric check (price >250)
101 Surf
Pcode Pname Price
102 Ariel
100 Rin 300
101 Surf null 103 Power

102 Ariel null


103 Power null

4.NOT NULL CONSTRAINT


Table 2 : Ord
create table ord (pcode int not null,prodname
varchar(100) not null)

Pcode Productname
Ord 100 Pears

Pcode int not null 101 Hamam


Pname varchar(100) not null
101 Liril

102 Cinthol
UNIQUE CONSTRAINT

Create table <tblname>(columnname unique)


Table 1 : Orde
create table orde (pcode int unique,prodname
varchar(100) )
Pcode Productname
Orde

Pcode int unique


Pname varchar(100)
Pcode Productname
100 Rin
101 Surf
102 Ariel
103 Power
Table 1 : Orde1

5.DEFAULT CONSTRAINT
Pcode Productname
Create table <tblname>(column name data type 100 Rin
default value)
101 Surf

create table ord1 (pcode int unique,prodname 102 Ariel


varchar(100) default ‘surf’) 105 Surf

insert into ord1(pcode) values(105)


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)
Table :Empnew
 
Eno int
Ename varchar(100)
Salary numeric
Designation varchar(30)
Dob datetime

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


IDENTITY

Create table <tblname>(columnname data type Table 1 : Order


identity)

Pcode Prodname

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


varchar(100) )

Order

Pcode int identity(1000,1)


Prodname varchar(100)
Table 1 : Order
insert into order(prodname) values('pears')
insert into order(prodname) values('Margo')

Pcode Prodname
1000 pears
Select * from order
1001 Margo
FUNCTIONS
FUNCTIONS

 AGGREGATE FUNCTIONS

 STRING FUNCTIONS

 MATHEMATICAL FUNCTIONS

 DATE FUNCTIONS
FUNCTIONS

AGGREGATE FUNCTIONS

• 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
FUNCTIONS

AGGREGATE FUNCTIONS

COUNT
Table 1:Employees
Its used to count the total
number of records in the table
Eno Ename Salary
100 Praveen 50000
101 Preetha 30000
102 Aravinth 25000
Ex: 103 Priya 30000

SELECT COUNT(eno) FROM employees

Output:
In the employees table its display the • 4
total number of employees
FUNCTIONS

AGGREGATE FUNCTIONS

Table 1:Employees
SUM
Its used to sum the total number Eno Ename Salary
of records in the table 100 Praveen 50000
101 Preetha 30000
102 Aravinth 25000
Ex: 103 Priya 30000

SELECT SUM(salary)FROM employees

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

AGGREGATE FUNCTIONS

Avg Table 1:Employees


Its used to calculate the average
value for the given records in the Eno Ename Salary
100 Praveen 50000
table
101 Preetha 30000
102 Aravinth 25000
Ex: 103 Priya 30000

SELECT AVG(salary)FROM employees

Output:
In the employees table its display the • 33750
average salary of the employees
FUNCTIONS

AGGREGATE FUNCTIONS

Table 1:Employees
MAX
Its used display the maximum values of Eno Ename Salary
records in the table 100 Praveen 50000
101 Preetha 30000
102 Aravinth 25000

Ex: 103 Priya 30000

SELECT MAX(salary)FROM employees

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

AGGREGATE FUNCTIONS

Table 1:Employees
MIN
Its used display the minimum values of Eno Ename Salary
records in the table 100 Praveen 50000
101 Preetha 30000
102 Aravinth 25000

Ex: 103 Priya 30000

SELECT MIN(salary)FROM employees

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

STRING FUNCTIONS

These scalar functions perform an operation on a string input


value and return a string or numeric value

ASCII
Returns the ASCII code value of the
leftmost character of a character
expression. Ex:
Syntax
Select ASCII(‘A’)
ASCII ( character_expression )
Arguments
character_expression Output:
Is an expression of the type char or 65
varchar.
Return Types : int
FUNCTIONS

STRING FUNCTIONS

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

Syntax
CHAR ( integer_expression )
Ex:

Arguments
select CHAR(65)
integer_expression
Is an integer from 0 through 255. NULL
is returned if the integer expression is
not in this range.
Output:
Return Types
char(1) A
FUNCTIONS

STRING FUNCTIONS

LEN

Returns the number of characters, Ex:


rather than the number of bytes, of
the given string expression, select len('praveen')
excluding trailing blanks.

Syntax
LEN ( string_expression )
Output:
Arguments
string_expression
Is the string expression to be
7
evaluated.

Return Types : int


FUNCTIONS

STRING FUNCTIONS

SUBSTRING
Returns part of a character, binary, text, or
image expression

Syntax
SUBSTRING ( expression , start , length )

Arguments Ex:
expression
select SUBSTRING('preetha',1,3)
Is a character string, binary string, text, image, a
column, or an expression that includes a column.
Do not use expressions that include aggregate
functions. Output:
start
Is an integer that specifies where the substring
begins.
pre
length
Is an integer that specifies the length of the
substring (the number of characters or bytes to
return).
FUNCTIONS

STRING FUNCTIONS

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

Syntax Ex:

REPLACE ( 'string_expression1' , SELECT


'string_expression2' , 'string_expression3' ) REPLACE('abcdefghicde','cde','xxx')

Arguments
'string_expression1‘ : Is the string expression to be
searched. string_expression1 can be of character or Output:
binary data.
'string_expression2‘ : Is the string expression to try abxxxfghixxx
to find. string_expression2 can be of character or
binary data.
'string_expression3‘ : Is the replacement string
expression string_expression3 can be of character This example replaces the string
or binary data. cde in abcdefghi with xxx.
FUNCTIONS

STRING FUNCTIONS

UPPER
Returns a character expression with
lowercase character data converted
to uppercase.

Syntax
UPPER ( character_expression )

Arguments Ex:
character_expression
Is an expression of character data. Select UPPER(‘priya’)
character_expression can be a
constant, variable, or column of
either character or binary data.

Return Types
Output:
varchar
PRIYA
FUNCTIONS

STRING FUNCTIONS

LOWER
Returns a character expression after
converting uppercase character data to Ex:
lowercase.

Syntax
Select LOWER(‘PRIYA’)
LOWER ( character_expression )

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

Return Types
varchar
FUNCTIONS

MATHEMATICAL FUNCTIONS

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

ABS
Examples
Returns the absolute, positive value of
the given numeric expression. This example shows the effect of
the ABS function on three
Syntax different numbers.
ABS ( numeric_expression )

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


numeric_expression ABS(1.0)
Is an expression of the exact numeric
or approximate numeric data type
category, except for the bit data type.
Output:
Return Types
Returns the same type as
numeric_expression
1.0, .0 ,1.0
FUNCTIONS

MATHEMATICAL FUNCTIONS

CEILING
Returns the smallest integer greater Examples
than, or equal to, the given numeric
expression. This example shows positive numeric,
negative, and zero values with the
Syntax CEILING function.
CEILING ( numeric_expression )
SELECT CEILING(123.45),
Arguments CEILING(-123.45), CEILING(0.0)
numeric_expression
Is an expression of the exact numeric or
approximate numeric data type category, Output
except for the bit data type.

Return Types 124.00, -123.00, 0.00


Returns the same type as
numeric_expression.
FUNCTIONS

MATHEMATICAL FUNCTIONS

FLOOR
Returns the largest integer less than or equal to Examples:
the given numeric expression.
This example shows positive numeric,
Syntax negative numeric values with the
FLOOR ( numeric_expression ) FLOOR function.

Arguments SELECT FLOOR(123.45), FLOOR(-


numeric_expression 123.45), FLOOR(123.45)
Is an expression of the exact numeric or
approximate numeric data type category, except
for the bit data type. Output:
Return Types 123 ,-124 ,123.0000
Returns the same type as numeric_expression.
FUNCTIONS
MATHEMATICAL FUNCTIONS

POWER

Returns the value of the given expression to the


specified power.

Syntax
POWER ( numeric_expression , y )

Arguments
Ex:
numeric_expression
Is an expression of the exact numeric or select POWER(2,2)
approximate numeric data type category, except
for the bit data type.
y
Is the power to which to raise numeric_expression.
y can be an expression of the exact numeric or
approximate numeric data type category, except Output:
for the bit data type.
4
Return Types
Same as numeric_expression.
FUNCTIONS

MATHEMATICAL FUNCTIONS Examples

This example shows two


expressions illustrating that with
ROUND the ROUND function the last digit
is always an estimate
Returns a numeric expression, rounded to
the specified length or precision.
Syntax SELECT ROUND(123.9994, 3),
ROUND(123.9995, 3)
ROUND ( numeric_expression , length [ ,
function ] )
Output:
Arguments

numeric_expression
123.9990,
Is an expression of the exact numeric or 124.0000
approximate numeric data type category,
except for the bit data type.
length
Is the precision to which numeric_expression
is to be rounded.
FUNCTIONS
MATHEMATICAL FUNCTIONS

SQUARE : Ex:
Returns the square of the given expression.
select square(4)
Syntax : SQUARE ( float_expression )

Arguments
Output:
float_expression : Is an expression of type float.
16.0
Return Types : float

SQRT Ex:
Returns the square root of the given expression.
select sqrt(4)
Syntax : SQRT ( float_expression )

Arguments Output:
float_expression : Is an expression of type float.

Return Types : float


2.0
FUNCTIONS
DATE AND TIME FUNCTIONS

These scalar functions perform an operation on a date and


time input value and return a string, numeric, or date and
time value.

 GETDATE
 DAY
 MONTH
 YEAR
 DATEADD
 DATEDIFF
FUNCTIONS
DATE AND TIME FUNCTIONS

GETDATE Ex:
Returns the current system date and time in Select GETDATE( )
the SQL Server standard internal format for
datetime values.

Syntax : GETDATE ( )

Return Types : datetime

Remarks Output:
Date functions can be used in the SELECT
statement select list or in the WHERE clause of
a query. 2007-05-26 18:00:56.153
FUNCTIONS
DATE AND TIME FUNCTIONS

DAY

Returns an integer representing the Example:


day datepart of the specified date.
Select DAY(’05/12/2007’)
Syntax : DAY ( date )

Arguments :

Date : Is an expression of type


datetime or smalldatetime. Output:
Return Type : int 12
FUNCTIONS
DATE AND TIME FUNCTIONS

MONTH

Returns an integer that represents the


month part of a specified date.
Example:
Syntax : MONTH ( date )
Select MONTH(’05/12/2007’)
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 Output:
after January 1, 1753.
5
Return Types : int
FUNCTIONS
DATE AND TIME FUNCTIONS

YEAR

Returns an integer that represents Example:


the year part of a specified date.

Syntax : YEAR ( date ) Select YEAR(’05/12/2007’)


Arguments

Date : An expression of type datetime


or smalldatetime.
Output:
Return Types : int
2007
FUNCTIONS
DATE AND TIME FUNCTIONS Select
DATEADD(DAY,10,’03/12/2007’)

DATEADD Output:
2007/05/22
Returns a new datetime value based on adding an
interval to the specified date.

Syntax : DATEADD ( datepart , number, date ) Select


DATEADD(MONTH,04,’03/12/2007’)
number
Is the value used to increment datepart. If you Output:
specify a value that is not an integer, the 2007/07/22
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(YEAR,02,’03/12/2007’)

Output:
2009/05/22
FUNCTIONS
DATE AND TIME FUNCTIONS Select
DATEDIFF(DAY,'07/05/1979','11/08/1983')
DATEDIFF

Returns the number of date and time Output:


boundaries crossed between two specified dates.
1587
Syntax
DATEDIFF ( datepart , startdate , enddate )
Select
Arguments DATEDIFF(MONTH,'07/05/1979','11/08/1983')

datepart
Is the parameter that specifies on which part of Output:
the date to calculate the difference
52
startdate
Is the beginning date for the calculation.
startdate is an expression that returns a
datetime or smalldatetime value, or a character Select
string in a date format. DATEDIFF(YEAR,'07/05/1979','11/08/1983')
enddate
Is the ending date for the calculation. enddate is
an expression that returns a datetime or
Output:
smalldatetime value, or a character string in a
date format. 4
JOINS
JOINS

 INNER JOIN

 OUTER JOIN

 CROSS JOIN
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
JOINS

Table 1 : Employee
Display all the details of Employee no ‘LST/1001’
Eno EmpName Dateofbirth Salary
LST/1001 Menaga 22/05/1982 12000
SELECT E.Eno,E.Ename,E.DateofBirth,D.
DeptName,E.Salary FROM Employee E,Department LST/1002 Kavitha 10/07/1982 15000
D,EMpDept ED LST/1003 Shakthi 12/05/1985 12000
WHERE E.Eno=ED.Eno AND ED.Deptno=D.Deptno AND LST/1004 Karthik 15/09/1980 20000
AND E.Eno=‘LST/10001’

Table 2 : Department
Eno EmpName Dateofbirth DeptName Salary DeptNo DeptName Shortname
LST/1001 Menaga 22/05/1982 Accounts 12000
100 Human Resourse HR
101 Accounts AC
102 Reaserch and Development RD

Table 3 : EmpDept
DeptNo ENO
100 LST/1003
101 LST/1001
101 LST/1004
102 LST/1002
Simple Join
1)Joining Two Tables

select *from Employees,Orders Table 1 : Employees

Employee_ID Name Prod_ID Product Employee_ID Employee_Id Name


100 Sachin 1000 Bat 100 100 Sachin
101 Dravid
101 Dravid 1000 Bat 100
102 Ganguly
102 Ganguly 1000 Bat 100

100 Sachin 1003 Ball 100 Table 2 :Orders


101 Dravid 1003 Ball 100 Prod_Id Product Employee_Id

102 Ganguly 1003 Ball 100 1000 Bat 100


1003 Ball 100
100 Sachin 1005 Glouse 101
1005 Glouse 101
101 Darvid 1005 Glouse 101

102 Ganguly 1005 Glouse 101


JOINS

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

INNER JOINS

1)Joining Two Tables with specified condition Table 1 : Employees

SELECT Employees.Name, Orders.Product Employee_Id Name


FROM Employees INNER JOIN Orders ON 100 Sachin
Employees.Employee_ID=Orders.Employee_ID
101 Dravid

Name Product 102 Ganguly

Sachin Bat

Table 2 :Orders
Sachin Ball
Prod_Id Product Employee_Id
Dravid Glouse
1000 Bat 100
1003 Ball 100
1005 Glouse 101
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.
JOINS

OUTER JOINS

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.
LEFT OUTER JOIN
1)Joining Two Tables with specified condition

Table 1 : Employees
SELECT Employees.Name, Orders.Product
Employee_Id Name
FROM Employees
100 Sachin
LEFT JOIN Orders 101 Dravid
ON Employees.Employee_ID=Orders.Employee_ID 102 Ganguly

Name Product

Sachin Bat Table 2 :Orders


Sachin Ball Prod_Id Product Employee_Id

Dravid Glouse 1000 Bat 100

Ganguly Null
1003 Ball 100
1005 Glouse 101

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

OUTER JOINS

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.
RIGHT OUTER JOIN
1)Joining Two Tables

Table 1 : Employees
SELECT Employees.Name, Orders.Product FROM Employees
RIGHT JOIN Orders ON Employee_Id Name
Employees.Employee_ID=Orders.Employee_ID 100 Sachin
101 Dravid
Name Product
102 Ganguly

Sachin Bat

Sachin Ball
Table 2 :Orders
Dravid Glouse Employee_Id
Prod_Id Product
1000 Bat 100
1003 Ball 100

The RIGHT JOIN returns all the rows from the second table
1005 Glouse 101
(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.
JOINS

OUTER JOINS

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.
FULL OUTER JOIN
1)Joining Two Tables

Table 1 : Employees
SELECT Employees.Name, Orders.Product
Employee_Id Name
FROM Employees
100 Sachin
FULL Outer JOIN Orders 101 Dravid
ON Employees.Employee_ID=Orders.Employee_ID 102 Ganguly

Name Product

Sachin Bat
Table 2 :Orders
Prod_Id Product Employee_Id
Sachin Ball
1000 Bat 100
Dravid Glouse
1003 Ball 100
Ganguly Null
1005 Glouse 101
JOINS

CROSS JOINS

 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 JOIN
1)Joining Two Tables with Cross Join

select *from Employees cross join Orders Table 1 : Employees

Employee_ID Name Prod_ID Product Employee_ID Employee_Id Name

100 Sachin 1000 Bat 100 100 Sachin


101 Dravid

101 Dravid 1000 Bat 100 102 Ganguly

102 Ganguly 1000 Bat 100

100 Sachin 1003 Ball 100 Table 2 :Orders


101 Dravid 1003 Ball 100 Prod_Id Product Employee_Id

1000 Bat 100


102 Ganguly 1003 Ball 100
1003 Ball 100
100 Sachin 1005 Glouse 101
1005 Glouse 101
101 Darvid 1005 Glouse 101

102 Ganguly 1005 Glouse 101


SUB QUERIES
SUB QUERIES

 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 Table:Stud

Sno Sname
100 preetha
Syntax 101 praveenkumar

Select * from <tblname> 102 Ramkumar

where condition( select * from 103 Reethu


104 Sathyakar
<tblname>)
105 Susi

Example Table:Payment
Sno Amount Balance
select * from stud where sno 100 7000 2000
in(select sno from payment) 101 7000 0
102 7000 1000
103 7000 3000

Sno
100 Result
101
102
103
SUB QUERIES
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

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 Table:Stud
Sno Sname
100 preetha
1.Sub Queries using operators 101 praveenkumar
102 Ramkumar

select * from stud where sno 103 Reethu


104 Sathyakar
=(select sno from payment where
105 Susi
balance=0)
Table:Payment
Result Sno Amount Balance
100 7000 2000
Sno Sname
101 7000 0
102 7000 1000
101 praveenkumar 103 7000 3000
SUB QUERIES Table:Stud
Sno Sname
2.Sub Queries using IN
100 Preetha
Using IN the inner query 101 Praveenkumar
execute and return value.Based on the 102 Ramkumar
inner query the outer query return 103 Reethu
values 104 Sathyakar
105 Susi
syntax
Select stmt IN  ( subquery | Table:Payment
expression [ ,...n ] ) Sno Amount Balance

100 7000 2000


select * from stud where sno in(select 101 7000 0
sno from payment where 102 7000 1000
balance>1000) 103 7000 3000
Result
Sno Sname
100 preetha

103 Reethu
SUB QUERIES Table:Stud
Sno Sname
3.Sub Queries using NOT IN 100 Preetha
101 Praveenkumar

Using NOT IN the inner


102 Ramkumar
query execute and return value.The
103 Reethu
outer query return values which is not
104 Sathyakar
belong to Sub query
105 Susi
syntax
Table:Payment
Select stmt NOT IN  ( subquery |
expression [ ,...n ] ) Sno Amount Balance

100 7000 2000


select * from stud where sno NOT IN 101 7000 0
(select sno from payment where 102 7000 1000
balance>1000) 103 7000 3000

Result
Sno Sname
101 Praveenkumar
102 Ramkumar
SUB QUERIES
4.Sub Queries using EXISTS
Table:Stud
Exists function check’s inner
query if it contains at least one row. Sno Sname
It returns a value of TRUE or FALSE. 100 Preetha
101 Praveenkumar
syntax
102 Ramkumar
Select stmt where EXSTS  ( subquery |
103 Reethu
expression [ ,...n ] )
104 Sathyakar
105 Susi
select * from stud where exists (select *
from payment where
stud.sno=payment.sno) Table:Payment
Sno Sname
Sno Amount Balance
100 Preetha
100 7000 2000
101 Praveenkumar 101 7000 0
102 Ramkumar 102 7000 1000
103 Reethu 103 7000 3000
SUB QUERIES Table:Stud
Sno Sname
100 Preetha
101 Praveenkumar
5.Sub Queries using NOT EXISTS
102 Ramkumar
103 Reethu
It works just opposite to EXISTS
104 Sathyakar
105 Susi
syntax
Select stmt where NOT EXSTS  ( Table:Payment
subquery | expression [ ,...n ]     ) Sno Amount Balance

100 7000 2000


101 7000 0
102 7000 1000
select * from stud where not exists 103 7000 3000
(select * from payment where
stud.sno=payment.sno)

Sno Sname
104 Sathyakar

105 Sus
SUB QUERIES Table:Stud
Sno Sname
5.Sub Queries using ANY 100 Preetha
101 Praveenkumar
102 Ramkumar
syntax 103 Reethu
104 Sathyakar
Select stmt where ANY  ( 105 Susi

subquery | expression [ ,...n ]


    ) Table:Payment
Sno Amount Balance
SELECT sname FROM stud WHERE 100 7000 2000
sno = any(SELECT sno FROM payment 101 7000 0
where balance=0) 102 7000 0
103 7000 3000

Sno Sname
101 Praveenkumar
102 Ramkumar
SUB QUERIES Table:Stud
Sno Sname
100 Preetha
7.Sub Queries using ALL 101 Praveenkumar

102 Ramkumar
syntax 103 Reethu
104 Sathyakar
Select stmt where ALL 105 Susi
(subquery | expression [ ,...n ]
Table:Payment
    )
Sno Amount Balance

100 7000 2000


SELECT * FROM stud WHERE sno <> 101 7000 0
ALL (SELECT sno FROM payment) 102 7000 1000
103 7000 3000

Sno Sname
104 Sathyakar
105 Susi
SUB QUERIES Table:Stud
Sno Sname
100 Preetha
101 Praveenkumar

8.UPDATE statement in Sub Queries 102 Ramkumar


103 Reethu
104 Sathyakar
update stud set sno =sno+1
105 Susi
where sno IN(select sno from
payment where balance>1000)

Result
Table:Payment
Sno Sname
101 Preetha
101 Praveenkumar Sno Amount Balance
102 Ramkumar 100 7000 2000
104 Reethu 101 7000 0
104 Sathyakar 102 7000 1000
105 Susi 103 7000 3000
SUB QUERIES Table:Stud
Sno Sname
100 Preetha
9.DELETE statement in Sub Queries 101 Praveen
102 Ramkumar
103 Reethu
DELETE stud WHERE sno IN
104 Sathyakar
(SELECT sno from payment where
105 Susi
balance=0)

Result
Table:Payment
Sno Sname
100 Preetha
103 Reethu Sno Amount Balance
104 Sathyakar 100 7000 2000
105 Susi 101 7000 0
102 7000 0
103 7000 3000
VIEWS AND INDEXES
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
VIEWS

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

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
1)Creating Temporary table using view

Table 1 : Employees
Create view v1 as select *from employees
Employee_Id Name
100 Sachin
101 Dravid
Select *from v1 102 Ganguly

Employee_Id Name
100 Sachin
101 Dravid
102 Ganguly

Now the employee information should be


temporarily stored to view v1
VIEWS
1)Update The view
Table 1 : Employees

update v1 set Name=Sourvav where Employee_Id Name


Employee_id=102 100 Sachin
101 Dravid
Employee_Id Name
102 Ganguly
100 Sachin

101 Dravid

102 Sourvav

While creating view for single table it


should be update but creating view
from more than one table shouldn’t
updated
VIEWS
Creating view from more than one table
Table 1 : Employees
Create view v2 as select
Employees.Employee_Id,Employees.Name,Pr Employee_Id Name
oduct.Products from employees 100 Sachin
101 Dravid
Select *from v2 102 Ganguly

Employee_Id Name Products

Table 2 : Product
100 Sachin Bat

101 Dravid Ball


Prod_Id Products Employee_Id
102 Ganguly Glouse
1000 Bat 100
1003 Ball 100
1005 Glouse 101
INDEXES

• 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

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

• 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

• CREATE INDEX IDX_CUSTOMER_LAST_NAME


on CUSTOMER (Last_Name)

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


would type in,

• CREATE INDEX IDX_CUSTOMER_LOCATION


on CUSTOMER (City, Country)
STORED PROCEDURES
STORED PROCEDURES

 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

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

Characteristics
A Precompiled transact Sql statements that
stored under a single name.
Compiled once and executed more times
Stored batch of Sql statements

Advantages:
Itallows modular programming
Security
Reduce Network Traffic
Compilation speed is much faster than statements
STORED PROCEDURES

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

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

@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

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

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

Create Procedure
Table 1:Emp
INSERT:
Create Procedure emp_insert( Eno Ename
@eno int,
@ename Varchar(10)) As
Begin
Insert into emp values(@eno,@ename)
End
Exec emp_insert 104,’Praveen’
Eno Ename

104 Praveen
STORED PROCEDURES

Update Procedure

Table 1:Emp
Update:
Create Procedure emp_Update( Eno Ename
@eno int, 104 Praveen
@ename Varchar(10)) As
105 Kumar
Begin
Update emp set ename=@ename where
eno=@eno
End

Eno Ename

104 Praveen
Exec emp_Update 105,’Naveen’ 105 Naveen
STORED PROCEDURES

Delete Procedure
Table 1:Emp
Update:
Create Procedure emp_Delete(@eno int) Eno Ename
As 104 Praveen
Begin
105 Naveen
Delete from emp where eno=@eno
106 Kumar
End

Exec emp_Delete 106


Eno Ename

104 Praveen

105 Naveen
STORED PROCEDURES

Select Procedure
Table 1:Emp
Select:
Eno Ename
Create Procedure emp_Select(@eno int)
As 104 Praveen
Begin 105 Kumar
Select * from emp where eno=@eno
End
Eno Ename
Exec emp_Selects 104
Select: 104 Praveen

Create Procedure emp_Select


Eno Ename
As
Begin 104 Praveen

Select * from emp 105 Kumar


End
Exec emp_Selects
STORED PROCEDURES

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

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

Example
The 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
Find ‘n’th maximum salary using Output parameter

create procedure nmax(@n int,@max


numeric output) Table 1:Emp
as
select @max=max(salary) from emp Eno Salary
while(@n>1) 100 4000
begin 101 7000

select @max=max(salary) from emp 102 8000


where salary<@max 103 6000
set @n=@n-1
end
Return @max

Execution Part:
declare @m numeric Output : (Second Maximum)
exec nmax 2,@max=@m output Maximum Value Is:7000
print ‘Maximum Value Is:’+@m
STORED PROCEDURES

DROP PROCEDURE

Removes one or more stored procedures or groups from the


current database.
Syntax:
DROP PROCEDURE procedure_name
TRIGGERS
TRIGGERS

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.

 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.
TRIGGERS

Syntax:

Create trigger <trigger name> on <table name>


For insert/update/delete
As
Begin
---------------------
--Sql statements--
----------------------
End
TRIGGERS
Checking salary condition using Insert Trigger

Create Trigger
create trigger sa on sals
for insert as
begin
declare @salary numeric
1.Table : Sals
select @salary=salary from inserted
if(@salary<1000)
Eno Salary
begin
100 5000
rollback transaction
print 'Salary should be >1000'
End
end
Inserting values
insert into sals
values(100,5000) Output
Inserting salary as <1000
insert into sals values(100,5000)
Salary should be >1000
TRIGGERS

Create table

create table sample(eno int,m1 int,m2


int,tot int)

Create trigger 1.Table:sample

1.The Trigger is used to insert the Eno M1 M2 tot


values in table then the total
should be automatically updated

create trigger s on sample


for insert
as
update sample set tot=m1+m2
TRIGGERS

Inserting values in table

insert into 1.Table : Sample


sample(eno,m1,m2)values(101,90,90)
Eno M1 M2 tot
Inserting another value

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

2.Table : Sample
Select the values from the table
Eno M1 M2 tot
Select *from sample 101 90 90 180

102 80 80 160
Here the total should be
automatically updated using
trigger
TRIGGERS

Checking salary condition using Update Trigger

Create Trigger 1.Table : Sals


create trigger sa on sals Eno Salary
for update as 100 5000
begin
declare @salary numeric
select @salary=salary from inserted
if(@salary<1000)
begin
rollback transaction
print ‘ Cannot Update Salary should be >1000'
End
end
Updating salary as <1000 Output
Update sals set salary=500 where eno=100 Cannot Update Salary should be >1000'
TRIGGERS

1.Table:Employees
Delete Trigger
Eno Salary
Transferring one table value to 100 5000
other table using trigger 101 6000
create trigger ds on employees
102 8000
for delete as
begin
2.Table: OldEmp
insert into oldemp select * from deleted
end Eno Salary

3.Table :OldEmp

Eno Salary
100 5000
101 6000

102 8000
CURSORS
CURSORS

 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

 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
Steps in Cursors
 The steps followed in cursor

1.DECLARE

2.OPEN

3.FETCH

4.CLOSE

5.DEALLOCATE
CURSORS

1.DECLARE 2.OPEN
Is used to declare the cursor Used to open the cursor
• Syntax •Syntax

DECLARE cursor_name CURSOR


FOR select_statement OPEN cursor_name

• cursor may be declared as

LOCAL | GLOBAL
FORWARD_ONLY | SCROLL
STATIC | KEYSET | DYNAMIC
| FAST_FORWARD
CURSORS
3.Fetching and Scrolling

• 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.
CURSORS

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

Return Description
value

0 FETCH statement was successful.

-1 FETCH statement failed or the


row was beyond the result set.
-2 Row fetched is missing.
CURSORS

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.D EAL LO CAT E

Re m o v e s a c u rs o r re fe r e nc e .

Syn tax

DE AL LOC AT E c ur s or _ n am e
CURSORS
Table:Emp
Example for Cursor

DECLARE c1 CURSOR FOR


SELECT ename FROM emp
OPEN c1
FETCH NEXT FROM c1 Result
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM c1
END
CLOSE c1
DEALLOCATE c1
Note: cursor fetch single row at
a time

// -- Check @@FETCH_STATUS

to see if
CURSORS

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

TYPES OF FETCHING

1. Use FETCH in a simple cursor


This example declares a simple
Cursor for the rows in employee
table
  RESULT
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
CURSORS
2.Use FETCH to store values in variables
Table:Emp
• 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 RESULT
WHILE @@FETCH_STATUS = 0
BEGIN pinky
PRINT @e praveenkumar
FETCH NEXT FROM c into @e preetha
END
CLOSE c
DEALLOCATE c
CURSORS
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.
RESULT
DECLARE c SCROLL CURSOR FOR
SELECT ename FROM emp
Orderby ename
FETCH LAST FROM c
FETCH PRIOR FROM c
FETCH FIRST FROM c
FETCH NEXT FROM c
FETCH ABSOLUTE 2 FROM c
FETCH RELATIVE 3 FROM c
FETCH RELATIVE -2 FROM c
CLOSE c
DEALLOCATE c
 
CURSORS
Cursor used in update
Table :Emp

DECLARE c1 CURSOR FOR


Select * from emp
OPEN c1
FETCH NEXT FROM c1
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH c1
RESULT
update emp set eno=eno+1 where
current of c1
END
CLOSE c1
DEALLOCATE c1
CURSORS

Cursor used in delete


Table:Emp

DECLARE c1 cursor for


Select * from emp where eno=101
OPENc1
FETCH c1
While (@@fetch_status=0)
Begin Duplicate record deleted
FETCH c1
Delete from emp where current of
c1
End
CLOSE c1
DEALLOCATE c1
CURSORS

Cursor for delete duplicate records


Table:Emp
Create procedure noduplicate as
DECLARE @e int
DECLARE c1 cursor for
Select * from emp where eno=@e
OPEN c1
FETCH c1 Duplicate records deleted
While (@@fetch_status=0)
Begin
FETCH c1
Delete from emp where current of
c1
End
CLOSE c1
Note:Duplicate records are not
FETCH next from c1 into @e mentioned cursor fetches each row
DEALLOCATE c1 and delete duplicate wherever it
occurred
USER DEFINED DATA TYPES
USER DEFINED DATA TYPES

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

Syntax

CREATE RULE rule AS condition_expression

Arguments
rule
Is the name of the new rule. Rule names must conform to the rules for
identifiers. Specifying the rule owner name is optional.
condition_expression
Is 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

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:

Name
System data type upon which the new data type is based

Syntax
sp_addtype [ @typename = ] type,[ , [ @nulltype = ] 'null_type' ]
USER DEFINED DATA TYPES
Arguments

[@typename =] type
Is 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 Used in tables


Create table emp(sno int,gender gend)
EXEC sp_addtype gend, 'VARCHAR(6)',
'NOT NULL'

Examples With Null Used in Tables


Create table emp(sno int,dob birthday)
EXEC sp_addtype birthday, datetime,
'NULL'
USER DEFINED DATA TYPES

Drop user-Defined Type

Examples
Syntax:
This example drops the user-
sp_droptype [ @typename = ] 'type'
defined data type birthday.
Arguments
[@typename =] 'type'
Note This user-defined data type
Is the name of a user-defined data type that must already exist or this example
you own. type is sysname, with no default. returns an error message.
EXEC sp_droptype 'birthday'
Normalization
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)
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 candidate
keys and the functional dependencies among their
attributes.
Functional Dependencies

Functional dependency describes the relationship between


attributes 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 of
A is associated with exactly one value of B. ( A and B may
each
consist of one or more attributes.)

B is functionally
A B
dependent on A

Determinant Refers to the attribute or group of attributes on the


left-hand side of the arrow of a functional dependency
Functional Dependencies (2)

Trival functional dependency means that the right-hand


side is a subset ( not necessarily a proper subset) of the left-
hand side.
For example: (See Figure 1)
staffNo, sName  sName
staffNo, 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.
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.
Functional Dependencies

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

Inference Rules
A set of all functional dependencies that are implied by a
given
set of functional dependencies X is called closure of X, written
X+. 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  B


2. Augmentation: If A  B, then A, C  B
3. Transitivity: If A  B and B  C, then A C
4. Self-determination: AA
5. Decomposition: If A  B,C then A  B and A C
6. Union: If A  B and A  C, then A B,C
7. Composition: If A  B and C  D, then A,C B,
Functional Dependencies

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 with


dependency C B, where C is a proper subset of A, and
still 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

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  sName
staffNo  position
staffNo  salary
staffNo  branchNo
staffNo  bAddress
branchNo  bAddress
branchNo, position  salary
bAddress, position  salary
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 that


it is only first normal form (1NF) that is critical in creating
relations. All the subsequent normal forms are optional.
First Normal Form (1NF)
Repeating group = (propertyNo, pAddress,
rentStart, rentFinish, rent, ownerNo, oName)
Unnormalized form (UNF)
A table that contains one or more repeating groups.
ClientNo cName propertyNo pAddress rentStart rentFinish rent ownerNo oName
CR76 John PG4 6 lawrence 1-Jul-00 31-Aug-01 350 CO40 Tina Murphy
kay St,Glasgow
PG16 Tony Shaw
5 Novar Dr, 1-Sep-02 1-Sep-02 450 CO93
Glasgow

CR56 Aline PG4 6 lawrence 1-Sep-99 10-Jun-00 350 CO40 Tina Murphy
Stewart St,Glasgow
Tony Shaw
PG36 2 Manor Rd, 10-Oct-00 1-Dec-01 370 CO93
Glasgow Tony Shaw

PG16 5 Novar Dr, 1-Nov-02 1-Aug-03 450 CO93


Glasgow

Figure 3 ClientRental unnormalized table


Definition of 1NF

First Normal Form is a relation in which the intersection of each


row 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.
1NF ClientRental relation with the first
approach
The ClientRental relation is defined as follows,
With the(first
ClientRental approach,
clientNo, wecName,
propertyNo, remove the repeating
pAddress, group rent,
rentStart, rentFinish,
(property rented
ownerNo, details) by entering the appropriate client
oName)
data into each row.
ClientNo propertyNo cName pAddress rentStart rentFinish rent ownerNo oName
CR76 PG4 John 6 lawrence 1-Jul-00 31-Aug-01 350 CO40 Tina Murphy
Kay St,Glasgow
CR76 PG16 John 5 Novar Dr, 1-Sep-02 1-Sep-02 450 CO93 Tony Shaw
Kay Glasgow
CR56 PG4 Aline 6 lawrence 1-Sep-99 10-Jun-00 350 CO40 Tina Murphy
Stewart St,Glasgow

CR56 PG36 Aline 2 Manor Rd, 10-Oct-00 1-Dec-01 370 CO93 Tony Shaw
Stewart Glasgow

CR56 PG16 Aline 5 Novar Dr, 1-Nov-02 1-Aug-03 450 CO93 Tony Shaw
Stewart Glasgow

Figure 4 1NF ClientRental relation with the first approach


1NF ClientRental relation with the second
approach
Client (clientNo,
With the second approach, cName) the repeating group
we remove
PropertyRentalOwner (clientNo, propertyNo, pAddress, rentStart,
(property rented details) by placing the repeating data along with
rentFinish, rent, ownerNo, oName)
aClientNo
copy of the original key attribute (clientNo) in a separte relation.
cName
CR76 John Kay
CR56 Aline Stewart

ClientNo propertyNo pAddress rentStart rentFinish rent ownerNo oName

CR76 PG4 6 lawrence 1-Jul-00 31-Aug-01 350 CO40 Tina Murphy


St,Glasgow
CR76 PG16 5 Novar Dr, 1-Sep-02 1-Sep-02 450 CO93 Tony Shaw
Glasgow
CR56 PG4 6 lawrence 1-Sep-99 10-Jun-00 350 CO40 Tina Murphy
St,Glasgow
CR56 PG36 2 Manor Rd, 10-Oct-00 1-Dec-01 370 CO93 Tony Shaw
Glasgow
CR56 PG16 5 Novar Dr, 1-Nov-02 1-Aug-03 450 CO93 Tony Shaw
Glasgow

Figure 5 1NF ClientRental relation with the second approach


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 AB is partially dependent if there is


some attributes that can be removed from A and the dependency
still holds.
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 the


removal of partial dependencies. If a partial dependency
exists, we remove the function dependent attributes from
the relation by placing them in a new relation along with
a copy of their determinant.
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)
2NF ClientRental relation
After
Clientremoving the partial dependencies,
(clientNo, cName) the creation of the three
new relations called
Rental Client, Rental,
(clientNo, and PropertyOwner
propertyNo, rentStart, rentFinish)
PropertyOwner (propertyNo, pAddress, rent, ownerNo, oName)
Client Rental
ClientNo cName ClientNo propertyNo rentStart rentFinish
CR76 John Kay CR76 PG4 1-Jul-00 31-Aug-01
CR56 Aline Stewart 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
PropertyOwner
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

Figure 6 2NF ClientRental relation


Third Normal Form (3NF)
Transitive dependency
A condition where A, B, and C are attributes of a relation such that
if 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.
3NF ClientRental relation
The functional dependencies for the Client, Rental and
PropertyOwner relations are as follows:

Client
fd2 clientNo  cName (Primary Key)

Rental
fd1 clientNo, propertyNo  rentStart, rentFinish (Primary Key)
fd5 clientNo, rentStart  propertyNo, rentFinish (Candidate
key)
fd6 propertyNo, rentStart  clientNo, rentFinish (Candidate
key)

PropertyOwner
fd3 propertyNo  pAddress, rent, ownerNo, oName (Primary Key)
fd4 ownerNo  oName (Transitive Dependency)
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)
3NF ClientRental relation
Client Rental
ClientNo cName ClientNo propertyNo rentStart rentFinish
CR76 PG4 1-Jul-00 31-Aug-01
CR76 John Kay
CR56 Aline Stewart 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

PropertyOwner Owner
propertyNo pAddress rent ownerNo ownerNo oName

PG4 6 lawrence St,Glasgow 350 CO40 CO40 Tina Murphy

PG16 5 Novar Dr, Glasgow 450 CO93 CO93 Tony Shaw

PG36 2 Manor Rd, Glasgow 370 CO93

Figure 7 2NF ClientRental relation


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 functional


dependency 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 a
relation, A must be a candidate key.
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.

ClientInterview
ClientNo interviewDate interviewTime staffNo roomNo
CR76 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


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)
Interview
ClientNo interviewDate interviewTime staffNo
CR76 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

StaffRoom
staffNo interviewDate roomNo
SG5 13-May-02 G101
SG37 13-May-02 G102
SG5 1-Jul-02 G102

Figure 9 BCNF Interview and StaffRoom relations


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
•AUB=R
A MVD is defined as being nontrivial if neither of the above
two
conditions is satisfied.
Fourth Normal Form (4NF)
Fourth normal form (4NF)
A relation that is in Boyce-Codd normal form and contains
no nontrivial multi-valued dependencies.
Fifth Normal Form (5NF)
Lossless-join dependency
Fifth normal form (5NF)
A property of decomposition, which ensures that no spurious
A relation that has no join dependency.
tuples are generated when relations are reunited through a
natural join operation.

Join dependency
Describes a type of dependency. For example, for a relation R
with subsets of the attributes of R denoted as A, B, …, Z, a
relation 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.

You might also like