Professional Documents
Culture Documents
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?
Introduction to DBMS.
Data Model.
Introduction to RDBMS.
DBMS Vs RDBMS
What is a Database?
Field
– A single item of data Name: Rahul
common to all records
Example of Table :
Fields
Application
DBMS
Database
Data Model
• Database model is the process of organizing the data into related record types.
Hierarchical
Network
Relational
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
DBMS RDBMS
Introduction
Data Type
SQL Components
SQL
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:
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
•NUMERIC[(P[, S])]
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
•FLOAT(N)
•REAL
Float[(n)] datatype
Real datatype
INTEGER DATATYPES
•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.
MONETARY DATATYPES
•MONEY
•SMALLMONEY
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.
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 data are stored on the Text/Image pages. There are three datatypes
in this category:
• TEXT
• NTEXT
• IMAGE
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.
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.
NCHAR[(N)]
NVARCHAR[(N)]
Data Types
•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
Start
Programs
MicrosoftSQLSERVER
Query analyzer
Working with Query Analyzer
Query Analyzer
Working with Query Analyzer
Server name
To log
Working with Query Analyzer
Use command
Syntax
Use <databasename>
SQL Components
SQL
CREATE
ALETR
DROP
Data Definition Language (DDL)
Example :
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
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>
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
INSERT
UPDATE
DELETE
SELECT
DML - Data Manipulation Language
Example :
INSERT INTO Employee VALUES
(‘LST/1001’,’Menaga’,’05/22/1982’,12000)
Eno EmpName Dateofbirth Salary
Note :
Varchar,Char and DateTime values
should be given with single quotes. (Eg) ‘Menaga’
DML – INSERT
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
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
Example :
BULK INSERT Master.dbo.Employee
FROM ‘C://empdetails.txt’'
WITH Eno EmpName Dateofbirth Salary
( FIELDTERMINATOR=‘*‘,
LST/1001 Menaga 05/22/1982 10000
ROWTERMINATOR = ‘ > ' )
Syntax:
SELECT * From <tablename>
WHERE Condition Table 1 : Employee
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 :
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
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
Not
SELECT * FROM TableName Eno EmpName Dateofbirth Salary
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
BETWEEN
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
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
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
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
Syntax
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
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
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
NULL
CONSTRAINTS
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.
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
Pcode Productname
Ord 100 Pears
102 Cinthol
UNIQUE CONSTRAINT
5.DEFAULT CONSTRAINT
Pcode Productname
Create table <tblname>(column name data type 100 Rin
default value)
101 Surf
Pcode Prodname
Order
Pcode Prodname
1000 pears
Select * from order
1001 Margo
FUNCTIONS
FUNCTIONS
AGGREGATE FUNCTIONS
STRING FUNCTIONS
MATHEMATICAL FUNCTIONS
DATE FUNCTIONS
FUNCTIONS
AGGREGATE 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
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
Output:
In the employees table its display the • 135000
sum of employee salary employees
FUNCTIONS
AGGREGATE FUNCTIONS
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
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
Output:
In the employees table its display
minimum salary of the employee • 25000
FUNCTIONS
STRING FUNCTIONS
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
Syntax
LEN ( string_expression )
Output:
Arguments
string_expression
Is the string expression to be
7
evaluated.
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:
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
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 )
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.
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.
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
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.
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 ( )
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
Arguments :
MONTH
YEAR
DATEADD Output:
2007/05/22
Returns a new datetime value based on adding an
interval to the specified date.
Output:
2009/05/22
FUNCTIONS
DATE AND TIME FUNCTIONS Select
DATEDIFF(DAY,'07/05/1979','11/08/1983')
DATEDIFF
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.
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
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 <>).
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
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:
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
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
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
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.
Sno Sname
100 preetha
Syntax 101 praveenkumar
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:
IN,NOT IN Keyword
103 Reethu
SUB QUERIES Table:Stud
Sno Sname
3.Sub Queries using NOT IN 100 Preetha
101 Praveenkumar
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
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
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
Sno Sname
104 Sathyakar
105 Susi
SUB QUERIES Table:Stud
Sno Sname
100 Preetha
101 Praveenkumar
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
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
101 Dravid
102 Sourvav
Table 2 : Product
100 Sachin Bat
CREATE INDEX
• TABLE Customer
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date)
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
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
EXECUTE
Syntax
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
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
ALTER PROCEDURE
Syntax:
Alter procedure <procedure name>
As
-----
Sql Statements
----
STORED PROCEDURES
Parameters
Input parameters allow the caller to pass a data value to the stored
procedure.
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.
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
Syntax:
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
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
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
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
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
LOCAL | GLOBAL
FORWARD_ONLY | SCROLL
STATIC | KEYSET | DYNAMIC
| FAST_FORWARD
CURSORS
3.Fetching and Scrolling
• FETCH NEXT Fetches the row after the last row fetched.
• FETCH PRIOR Fetches the row before the last row fetched.
• 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
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
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
// -- Check @@FETCH_STATUS
to see if
CURSORS
TYPES OF FETCHING
TYPES OF FETCHING
RULE
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
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
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
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
B is functionally
A B
dependent on A
• are nontrivial.
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
staffNo sName
staffNo position
staffNo salary
staffNo branchNo
staffNo bAddress
branchNo bAddress
branchNo, position salary
bAddress, position salary
The Process of Normalization
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
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
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:
PropertyOwner Owner
propertyNo pAddress rent ownerNo ownerNo oName
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
StaffRoom
staffNo interviewDate roomNo
SG5 13-May-02 G101
SG37 13-May-02 G102
SG5 1-Jul-02 G102
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.