SQL Server 2005 - Courseware
SQL Server 2005 - Courseware
Courseware
1
Table of Contents
2
4.8 Try Catch 102
5 Database Architecture 107
3
1. Querying Data
1.1. Basic Select Statement
Relational Operators
1. >
2. >=
3. <
4. <=
5. =
6. != or <> (For Not Equal To)
7. Between lower value And higher value
8. Not Between lower value And higher value
9. IN (List of Values)
10. NOT IN (List of Values)
11. Like
12. NOT Like
Examples
1. Between
2. IN
IN is equivalent to logical OR
Logical Operators
1. AND
2. OR
3. NOT
4
1) AND operator will check conditions in combination
Example of %
To see records of employees which have S as the starting character.
select ename,sal,deptno
from emp
where ename like 'S%';
select ename,sal,deptno
from emp
where ename not like 'S%';
5
Insert into pcodes values(‘PACZ-90’,102);
Insert into pcodes values(‘PADZ-90’,102);
Insert into pcodes values('PW1-RT',89);
Insert into pcodes values('PW2-RT',56);
Insert into pcodes values('PW3-RT',98);
Insert into pcodes values('PW4-RT',187);
Insert into pcodes values('PW5-RT',5);
[^range]
6
Concatenation :
+ operator
select lastname + firstname "complete name" from employees
(+ needs all data types matching)
For different data types such as number and varchar use cast function
7
Dealing with Nulls
8
1.2 JOINS
Inner-Join
Retrieving common records from the 2 tables on equality condition –
To see names and department names from emp and dept table
Non-ANSI Method:
Select ename, dname
From emp, dept
Where emp.deptno = dept.deptno;
ANSI Method:
select ename, dname
from emp inner join dept
on emp.deptno = dept.deptno;
In the Select Statement if the common column has to be displayed then it has to be
prefixed by table name in both ANSI and NON-ANSI methods.
To see names, department names and product names from the 3 tables on matching
values –
Non-ANSI Method:
select ename, dname, pname
from e, d, p
where e.deptno = d.deptno AND d.pcode = p.pcode;
9
ANSI Method:
select ename, dname, pname
from e join d
on e.deptno = d.deptno
join p
on d.pcode = p.pcode;
Cross Join
No join condition. So each row of first table gets combined with each record of the other.
Cartesian product takes place.
Cross join is effective for financial applications such as calculations of interest rates for
each month.
In the tables period and rates nothing is common. Still cross product can be achieved.
Non-ANSI Method:
select roi, month, roi*month as "Interest"
from rates, period;
ANSI Method:
select roi, month, roi*month as "Interest"
from rates CROSS join period;
In the tables emp1 and dept1, both the tables have one record non-matching.
To see names of the employee and their departments and also the names of the
employees who do not have any department
ANSI Syntax
select ename,dname
from emp1 LEFT outer join dept1
on emp1.deptno = dept1.deptno
10
Right Outer Join
To take matching records from both the tables and all remaining records from the
right table.
To see the names of the employees and their department names and also the --department
names which do not have any employee;
ANSI Syntax
select ename, dname
from emp1 RIGHT outer join dept1
on emp1.deptno = dept1.deptno
First Matching records from both tables, then remaining records from left table and
then the remaining records from the right table are displayed.
To see employee names and their departments, employees who do not have department
as well as department names which are not having any employee
ANSI Syntax
11
Self Join
In self join the table is joined to itself. To images of the same table will get created
with different alias name for each table.
create table EM
(empno varchar(4),
ename varchar(30),
mgr varchar(4));
Example 2
To see if a record is duplicated
The same student’s record is duplicated with different roll number.
create table sj
(roll integer not null primary key,
name varchar(50),
sem varchar(10),
marks integer);
12
SQL Server 2000 Syntaxes of Joins
Join Syntaxes till SQL Server 2000 had some proprietary clauses like *= and =*.
If we are in 2005 then the compatibility has to be given to 2000 by the inbuilt stored
procedure sp_dbcmptlevel. It has two parameters : Database name and
version.
sp_dbcmptlevel master, 80
select ename,dname
from emp1, dept1
where emp1.deptno *= dept1.deptno -- Left Outer Join
select ename,dname
from emp1, dept1
where emp1.deptno =* dept1.deptno -- Right Outer Join
13
1.3 SET OPERATORS
UNION
UNION ALL
--UNION
--Combines the result of two or more queries eliminating duplicates
--Rule -- The couln list and their data types of all the queries should be same
--To see distinct products sold to 107 and 108
select prodname
from pune
where custid =107
UNION
select prodname
from pune
where custid =108;
14
UNION ALL
Shows all the values form both the queries including duplicates
To see all product names for 107 and 108
select prodname
from pune
where custid =107
UNION ALL
select prodname
from pune
where custid =108;
SET OPERATORS WITH TWO TABLES (Effective when no columns are matching)
15
select rollno,marks
from mech
where marks >= 70
UNION
select rollno,marks
from comp
where marks >= 70
order by marks desc;
Here rollno and marks combination is checked in both queries. So individual --marks
duplication is allowed. But no duplication of combination is done.
If only marks was the column the 78 will not be repeated.
UNION ALL
-- To see the master list of mech and com tables
select rollno,marks
from mech
UNION ALL
select rollno,marks
from comp;
16
1.4 Summary Queries
Aggregate Functions
1. SUM()
2. MAX()
3. MIN()
4. AVG()
5. COUNT()
Group By clause will eliminate duplicates for a value and sort the values in ascending
manner.
Select deptno
From emp
Group by deptno;
Group by clause
Having clause
Nested Grouping
17
COMPUTE (SS SPECIFIC)
Generates totals that appear as additional summary columns at the end of the result set.
After showing all the records, it shows the summary record
select deptno,sal
from emp
Compute Max(Sal)
select deptno,sal
from emp
Compute Max(Sal),min(sal),avg(sal),sum(sal)
To show deptno wise highest salary, as well as the highest salary amongst those.
18
select deptno,max(sal)
from emp
group by deptno
compute max(max(sal))
COMPUTE BY
To show deptno ,salaries and the sub-total of salary at each deptno change.
select deptno,sal
from emp
order by deptno
For successful execution of the Compute By clause the grouping field must be
sorted.
select job,deptno,sal
from emp
order by job,deptno
Compute sum(sal) by job,deptno
In this case here sorting is done for deptno within each job. So once the combination is
getting changed the total for that combination is shown.
If only one column is there in order by then that same column has to be there in
compute by clause
select job,deptno,sal
from emp
order by job
Compute sum(sal) by deptno --- Wrong
If more than one columns are in the order by clause then at least the first
column has to be there in the compute by clause
19
select job,deptno,sal
from emp
order by job,deptno
Compute sum(sal) by deptno ----- Wrong
select job,deptno,sal
from emp
order by job, deptno
In this case the deptno are sorted within each job and when job changes the total
of salary is shown
When the number of columns and names in the Order By and Compute by
are matching then still the Order By clause first column and the Compute By
clause first column needs to be same.
select job,deptno,sal
from emp
order by job, deptno
Compute sum(sal) by deptno, job -- Wrong
select job,deptno,sal
from emp
order by job, deptno
Compute sum(sal) by job, deptno -- Correct
20
ROLLUP
SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY DEPTNO, JOB WITH ROLLUP
21
CUBE
SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY DEPTNO, JOB WITH CUBE
22
23
1.5 Date Functions
select getdate()
Syntax
Arguments
datepart
Datepart Abbreviations
Year yy, yyyy
Quarter qq, q
Month mm, m
Dayofyear dy, y
Day dd, d
Week wk, ww
Weekday dw
Hour hh
Minute mi, n
Second ss, s
Millisecond ms
24
1.6 SUB QUERY
Single Row Sub Query
To see records of person who earn salary higher than SMITH’s salary.
25
ANY in subqueries
To see the salary, names, job of the employees who earn more than any employee in
the job Salesman.
select sal,job,ename
from emp
where sal >ANY (select sal
from emp
where job = ‘SALESMAN’)
select sal,job,ename
from emp
where sal >ALL (select sal
from emp
where job = ‘SALESMAN’)
order by sal desc;
26
Multiple Column Sub-Queries –
To display the records of employees who have the deptno and job same as that of
SMITH.
27
Nested Sub queries
To display records having salary above the highest salaries for the job
of Miller.
select ename,dname,sal
from emp inner join dept
on emp.deptno = dept.deptno
where emp.sal > (select sal
from emp
where ename = 'MARTIN');
28
CORRELATED Sub Queries
To see employees who earn salary less than the average salary of their own job
Parent query takes each row and submits it to child query.
Child query gets executed for each row
update emp
set dname = (select dname
from dept
where emp.deptno = DEPT.deptno);
Alter Table Emp
Drop Column Dname;
Creating the table retired_emp without taking data of the emp table.
Now to delete records from Emp table for all those have been retired.
29
where empno = (select empno
from Retired_Emp R
where Emp.empno = R.empno);
Exists Operator:
The EXISTS operator tests for existence of rows in the results set
of the sub query.
• If a subquery row value is found:
– The search does not continue in the inner query
– The condition is flagged TRUE
• If a subquery row value is not found:
– The condition is flagged FALSE
-The search continues in the inner query till either the
condition becomes TRUE or if not then till the last record.
create table e1
(empno integer,
ename varchar(20),
deptno integer);
create table d1
(deptno integer,
location varchar(20));
30
Insert Into D1 Values(10,'Pune');
Insert Into D1 Values(10,'Mumbai');
Insert Into D1 Values(10,'Bangalore');
Insert Into D1 Values(20,'Mumbai');
Insert Into D1 Values(20,'Chennai');
Insert Into D1 Values(20,'Bangalore');
Insert Into D1 Values(30,'Chennai');
Insert Into D1 Values(30,'Delhi');
Insert Into D1 Values(30,'Pune');
To display records of employees from e1 table who have the same deptno as that of
d1 table.
select e1.deptno,e1.ename
from e1, d1
where e1.deptno = d1.deptno; --- Odd Result
select * from e1
where exists
(select * from d1
where e1.deptno = d1.deptno);
To display records of employees from e1 table who do not have the same deptno as
that of d1 table.
select * from e1
where not exists
(select * from d1
where e1.deptno = d1.deptno);
31
Sub-Query in From Clause (Inline Views)
Example –
To see names, salaries, job, average salary and difference (raise) with
average salary of those employees who earn more than the average
salary in their jobs.
32
2 DDL Commands
33
Create Table Statement
,
tax int
check (sales>tax));
34
Creating foreign key on table level.
CREATE TABLE Y2
(A INTEGER,
Z INTEGER,
FOREIGN KEY (A) REFERENCES Y1)
35
Computed Columns (SSS)
Note –
Insert Into allowance_details Values(1,900,1200,400)
It is not possible to insert value in the total column and also the total column
cannot be updated manually.
But when the values of the arguments are updated then the computed column gets
refreshed implicitly.
CREATE TABLE Y5
(A INTEGER,
Z INTEGER,
FOREIGN KEY (A) REFERENCES Y4)
36
Creating a new table from an existing table.(SS Specific)
5) Summary Table.
37
6) Data from multiple tables
7) The constraints are not copied in the new table.Only Not Null
status is applied to the new table.
38
39
Referential Integrity
Now if the parent record is tried to delete then it will throw dependency error
Also if the parent record’s roll is tried to update then it will show dependency error.
update student1
set roll = 55
where roll=1;
To resolve these issues in the foreign key definition on delete cascade and on update
cascade have to be specified.
40
select * from result1;
To drop the primary key constraint or to drop the primary key column the
dependencies have to be taken care of.
41
Identity (SS Specific)
Example –
select * from X;
SET IDENTITY_INSERT X ON
42
To see the last identity value use IDENT_Current built-in
SELECT IDENT_CURRENT('X');
43
RULE (SS Specific)
To drop a rule
44
drop rule r1
45
ALTER Statement
Adding column
Dropping a column
alter table emp_data
drop column address
(If data is present in the column then still from integer to varchar conversion is possible,
but varchar to integer is not possible)
Adding constraint
alter table emp_data
add constraint u1 unique(empid)
Dropping constraint
Alter table emp_data
Drop constraint u1
Dropping table
Drop table emp_data
46
Constraints – Enable and Disable
create table sales(sid integer, amt integer constraint ch_amt check(amt >= 100));
47
2.7 Temporary table
There are two types of temporary tables.
1 Local temporary table: The scope of Local temporary table is limited to the current
session only. It is created by prefixing single # to the table name.
But the city_records table is limited to the first session. Once the session is closed
then the table is no more.
48
2.8 VIEWS
Advantage: Due to views we can hide the original table and give some conditional
access of records to the user
create view V1
as
select * from emp
where sal >= 3500
Views can be based on data from more than one table through join.
create view v3
as
select ename,dname
from emp join dept
on emp.deptno = dept.deptno
Summary view –
create view v4
as
select deptno,max(sal) "Top Sal" from emp
group by deptno
(Note – Must provide column name for the aggregate function max(sal))
With Check Option – This clause is used to restrict data from the view to get entered in
the base table. Also data cannot be updated through the view of the criteria specified.
create view v7
as
select * from emp
where deptno = 10
WITH CHECK OPTION
49
Will throw error if deptno is tried to update through view.
update v7
set deptno = 8
50
2.9 Indexes
Guidelines for creating Indexes
A column can be selected for indexing based on the following criteria
Frequently searched column
If the table is large
Do not index the column in the following cases
If column is not frequently searched.
If the table is small
Clustered Index
A Clustered index determines the storage order of data in a table (physical order)
A table can have only one clustered index
A clustered index is analogous to a telephone directory, which arranges data by last name
It is effective on columns that are accessed very frequently and Queries that return large
result sets
Non-Clustered Index
A non-clustered index specifies a logical ordering only.
A table can have multiple non-clustered indexes (max 249).
It is similar to a textbook index
The data is stored in one place and the index in another
Composite Index
A composite index consists of two or more columns indexed together
Maximum 16 columns can be combined together
Composite indexes require fewer overheads than single column indexes
Unique Index
A Unique Index ensures that the indexed column contains no duplicate values
Both clustered and non-clustered indexes can be unique
Considerations
• Specifying a unique index makes sense only when
uniqueness is a characteristic of the data
51
• If uniqueness must be enforced to ensure data integrity,
create a UNIQUE or PRIMARY KEY constraint on the column
rather than a unique index
• Creating a PRIMARY KEY or UNIQUE constraint automatically
creates a unique index on the specified columns in the table
Viewing Indexes
52
Programming Basics
Declare @x integer
set @x = 98
print @x
print 'Value of x variable is ' + cast(@x as varchar)
end
If condition is not given then shows the last record’s salary value from the table
declare
@x integer
begin
select @x = sal from emp
print @x
end
If Condition
Syntax –
IF <condition>
[begin]
----
----
[end]
else
[begin]
-----
-----
[end]
53
declare
@x integer
begin
set @x = 56
if @x >= 40
print 'Passed'
else
print 'Failed'
end
Multiple statements in true and false block with begin and end
declare
@x integer
begin
set @x = 56
if @x >= 40
begin
print 'Passed'
print 'Marks are ' + cast(@x as varchar)
end
else
begin
print 'Failed'
print 'Marks are ' + cast(@x as varchar)
end
end
declare
@x integer
begin
set @x = 41
if @x >= 70
print 'Dist'
else if @x >= 60
print 'FC'
else if @x >= 50
print 'SC'
else if @x >= 40
print 'Passed'
else
54
print 'Failed'
end
Nested if’s ……
declare
@s integer,
@j varchar(9)
begin
select @s = sal from emp
where ename = 'SMITH'
if @s <= 1000
begin
select @j = job from emp
where ename = 'SMITH'
if @j = 'MANAGER'
PRINT '30 PERCENT RAISE'
else
PRINT '20 PERCENT RAISE'
end
else
PRINT 'NO RAISE'
End
55
While Loop
To display 1 to 10
Declare @w integer
set @w = 1
while @w <= 10
begin
print @w
set @w = @w + 1
end
declare @w integer
set @w = 1
while @w <= 10
begin
if @w = 5
break
else
print @w
set @w = @w + 1
end
print 'End of loop'
56
Drop table part;
create table PART (Part_Id int, Category_Id int, Description varchar(50));
OUTPUT
To generate records in the table part. For part_id 1 and category_id 2 the record should
not be inserted. So using continue clause for that condition.
57
GOTO Label:
declare
@s integer,
@n varchar(40)
begin
delete from flight_allowance;
delete from rail_allowance;
delete from petrol_allowance;
select @s = sal,@n = ename from emp
where ename = 'FORD'
IF @S >= 5000
goto FA
else if @s >= 3000
goto RA
else if @s >= 2000
goto PA
FA:
Insert into flight_allowance values(@n);
RA:
Insert into rail_allowance values(@n);
PA:
Insert into petrol_allowance values(@n);
end
select * from flight_allowance;
select * from rail_allowance;
select * from petrol_allowance;
58
3.2 Cursors
59
Fetch absolute 1 from c3
@@Fetch_Status is the global variable. It returns an integer value 0 for the last cursor
fetch statement..i.e. After the last record is fetched it becomes not equal to zero.
@@cursor_rows returns the number of qualifying rows that are in the currently opened
cursor.
Declare
c5 cursor SCROLL
for select distinct sal from emp
order by sal desc
open c5
fetch first from c5
fetch next from c5
60
open c6
fetch first from c6
while @n <= 4
begin
fetch Next from c6
set @n = @n + 1
end
declare @n integer
Declare
c7 cursor SCROLL
for select * from emp
set @n = 1
open c7
fetch Last from c7
while @n <= 2
begin
fetch Prior from c7
set @n = @n + 1
end
STATIC
Open c10
update emp set sal = 3000 where ename = 'SMITH'-- Independent update
DYNAMIC
61
declare c11 cursor DYNAMIC SCROLL
FOR SELECT * FROM EMP
OPEN C11
FETCH FIRST FROM C11 --- Shows the changed salary 2000
(Note -- The fetch type Absolute cannot be used with dynamic cursors.)
Whenever multiple conditions are there for updating a table then instead of
executing them separately and having a full table scan for every update statement,
we can use where current of clause. The cursor will update each row as per the
conditions.
declare @s integer
declare c12 cursor SCROLL DYNAMIC
for select sal from emp
for update of sal
open c12
Begin
if @s >= 5000
set @s = 10000
else if @s >= 4000
set @s = 9000
else if @s >= 3000
set @s = 8000
else if @s >= 2000
set @s = 7000
else if @s >= 1000
set @s = 6000
else if @s < 1000
set @s = 5500
62
update emp
set sal = @s
where current of c12
Fetch next from c12 into @s
End
63
3.3 Stored Procedures
Execute p1
OR Exec p1
OR p1
exec p2 123,'abc',10
Exec p3 456,'def'
64
Print 'One record created'
exec p4 789,default,'pqr'
EXEC P5 'CLERK'
OR EXEC P5
declare @a integer
exec @a = p7 3,5
select @a
(Note - If the procedure is executed independently then the answer will not be displayed)
In procedure p8 the ename will be supplied by the user as input parameter and the
procedure will return the sal for that ename as the output parameter.
65
create procedure p8 (@name varchar(50), @salary integer output)
as
select @salary = sal
from emp
where ename = @name
declare @x integer
exec p8 'KING', @x OUTPUT
SELECT @x
66
exec show_proctab1 – Works properly
67
3.4 Functions
Update emp_sal1
set tax = dbo.get_Tax1(60000)
where empid = 2
68
OR
Insert Into Emp_Sal Values(3,40000,null)
The RETURNS clause contains only the keyword table. You do not have to
define the format of a return variable because it is set by the format of the result
set of the SELECT statement in the RETURN clause.
69
Calling a function for a computed column of a table
70
3.5 Triggers
Example 2 -- Deleted row from tab1 should get inserted in table tab3
71
Example 3 – If the new value inserted is < 100 then the record should not be
inserted.(Conditional Insert)
72
Example 5 – To show how inserted and deleted tables of trigger work with Update
statement
Example 6 – Table Level Update Trigger. It gets fired when any field from the row gets
updated.
update emp
set sal = 90000
where ename = 'KING' – Throws error
73
Example 7 – Column Level Update Trigger. It gets fired only when a particular field
from the row gets updated.
update emp
set deptno = 20
where ename = 'MARTIN' --- Throws error
Example 8 – To ensure that more than 5 records cannot get deleted in one stroke.
74
insert into lowcost values(1,900);
insert into lowcost values(2,1100);
insert into lowcost values(3,1300);
Rollback Tran
end
End
75
Example 10 – Cascade Triggers
Similar to cascade delete and cascade update options
When a record from Emp_Details is deleted then the corresponding same record
from Emp_performance should also get deleted.
76
select * from check_inserts
Example 12 – Instead Of Trigger
Directly DML cannot be done on a view based on more than one tables. But using
Instead of triggers it is possible.
create view sr
as
select s.roll,s.name,r.marks
from s,r
where s.roll = r.roll;
77
Restricting DML on Sunday
update emp
set sal = 1000
where ename = 'ALLEN'
When a new record is inserted then the cost should be greater than all the existing
records cost value
78
Create Trigger tx1 on Costing
for insert
as
declare @max_cost integer
begin
select @max_cost=max(cost) from costing
if (select cost from inserted) < @max_cost
Begin
Print 'Cost Value has to be greater than all existing cost'
Rollback Tran
End
End
79
4. New Features of SQL Server 2005 –
SQL Server 2005 has extended the trigger functionality you normally use with Data
Manipulation Language (DML) commands such as INSERT, UPDATE, and DELETE to
incorporate Data Definition Language (DDL) commands like CREATE DATABASE,
DROP TABLE, and ALTER TABLE.
Also, like DML triggers, DDL triggers run in the same transaction as the DML
statement. So for instance, when a DDL TSQL statement has completed, you can
rollback a transaction whenever appropriate.
Some other differences between DDL and DML triggers include the following:
80
TOP clause Enhancements
TOP was introduced in SQL Server 7. Until SQL Server 2005, the TOP clause allowed
the user to specify the number or percent of rows to be returned in a SELECT statement.
In SQL Server 2005, the TOP clause can be used also for UPDATE, and DELETE (in
addition to SELECT), and the syntax is as follows: TOP (expression) [PERCENT].
Notice the parentheses around the expression; this is required when TOP is used for
UPDATE, INSERT, and DELETE.
New of 2005
81
DML OUTPUT clause
82
OUTPUT with DELETE
The example inserted the id and col1 values of the rows that were
deleted into the table variable @del.
begin tran
select empno,ename,sal into #temp1 from emp where 4 = 6
delete from emp
output Deleted.empno,Deleted.ename,Deleted.sal into
#temp1
where sal <= 2000
83
OUTPUT with UPDATE
84
4.5 Pivot
Example 1 –
Generating a report in which Job values will be the column heading, the
deptno values will be row headings and the total (sum) of salaries for
the combination of job and deptno will be the data.
Output –
select * from P_emp
PIVOT
(
SUM(Sal)
For JOB in (ANALYST,MANAGER,SALESMAN,CLERK)
)
AS P
85
To get summary for a particular deptno use the where clause after the pivot
Example 2—
CREATE TABLE SALES
(
[Year] INT,
Quarter CHAR(2),
Amount FLOAT
)
86
INSERT INTO SALES VALUES (2002, 'Q2', 60)
INSERT INTO SALES VALUES (2002, 'Q3', 120)
INSERT INTO SALES VALUES (2002, 'Q3', 110)
INSERT INTO SALES VALUES (2002, 'Q4', 180)
Select * from sales
order by year, quarter, amount;
To get the sum of Amount for each Quarter within each year.
Quarter values will be column headings, year values will be row headings and sumation
of amount will be done.
87
Example 3 –
Pivot report can also have only column headings (No row values)
For that the from clause query has to be used and only two columns have to be
mentioned, one column or aggregation and the other column for the column headings.
Example 4-
If a table has more than 3 columns then the from clause query should be used to
select the 3 columns for the pivot table.
select * from
(select sal,job,deptno from emp) as A
pivot
(sum(sal) for job in (analyst,clerk)
)
as P;
88
Example 5 –
select * from
(select dname, job, sal
from emp inner join dept
on emp.deptno = dept.deptno) as A
pivot
(
max(sal) for dname in (Accounting, Research,Sales, Operations)
)
as P
89
4.5. Common Table Expression (CTE)
SQL Server 2005 significantly enhances both the functionality and performance of SQL to
address the requirements of business intelligence queries. The SELECT statement’s WITH
clause, introduced in SQL Server 2005, provides powerful new syntax for enhancing query
performance. It optimizes query speed by eliminating redundant processing in complex
queries.
Consider a lengthy query that has multiple references to a single sub query block. Processing sub
query blocks can be costly, so re-computing a block every time it is referenced in the SELECT
statement is highly inefficient. The WITH clause enables a SELECT statement to define the sub
query block at the start of the query, process the block just once, label the results, and then refer
to the results multiple times.
The WITH clause, formally known as the sub query factoring clause, is part of the SQL-99
standard. The clause precedes the SELECT statement of a query and starts with the keyword
“WITH.” The WITH is followed by the sub query definition and a label for the result set. The query
below shows a basic example of the clause:
Query1 – To display maximum salaries department number wise for the department numbers
having max salary greater than the max salary of department number 20.
In the above query there is lot of performance overhead due to the following factors:
1. Initially the max(sal) for deptno 20 is calculated.
2. Once the max(sal) is calculated and returned by the sub query then again the
parent query will do the job of finding the max(sal) deptno wise and compare with
the value given by max(sal) of deptno 20.
with summary as
( select max(sal) as highest, deptno
from emp
group by deptno)
select deptno, highest
from summary
where highest > (select highest
from summary
where deptno = 20);
A temporary table summary gets created which does the job of finding deptno wise
highest salaries. Using this summary table then simply the max(sal) of deptno 20 is
filtered. Here the aggregation is done only once.
90
Query 2- To list the Sum of Salaries for departments comprising more than 1/3 of the
firm's annual salary.
with summary as
(select dname,sum(sal) as DTOTAL
from emp,dept
where emp.deptno = dept.deptno
group by dname)
select dname, DTOTAL
from summary
where DTOTAL >
(select sum(DTOTAL) * 1/3
from summary);
91
6. Analytical functions
Though analytic functions give aggregate result they do not group the result set. They
return the group value multiple times with each record. As such any other non-"group by"
column or expression can be present in the select clause.
Partition by will do aggregation and display it for all the records (After aggregating the
value grouping is not done)
select ename, job, max(sal) over (partition by job) "Job Wise Max Sal"
from emp;
92
Example 2
select deptno,ename, job, max(sal) over (partition by deptno) "Deptno Wise Max
Sal" from emp
SQL> select ename, job, max(sal) over () "Highest Salary" from emp;
93
Example 4 – To perform calculations with aggregate values
and actual values
To see the difference in the max(sal) and sal for each employee.
select ename, job, max(sal) over () "Highest Salary", sal "Actual Salary",
max(sal) over() - sal "Difference"
from emp;
94
95
RANK and DENSE_RANK both provide rank to the records based on some column
value or expression. In case of a tie of 2 records at position N, RANK declares 2
positions N and skips position N+1 and gives position N+2 to the next record. While
DENSE_RANK declares 2 positions N but does not skip position N+1.
Rank()
select ename, sal, deptno,
rank() over(partition by deptno order by sal desc) as
"Rank123" from emp
order by deptno, Rank123
For DEPTNO 20 there are two contenders for the first position Scott and
Ford. So it has given the same number 1 for those but has skipped 2 and
directly given rank number 3 for Jones of the same deptno 20.
Same case is for 3 records of deptno 30.
96
Dense_Rank()
select ename,sal,deptno,
dense_rank() over(partition by deptno order by sal desc)
"Dense Rank"
from emp
order by 3,4
For DEPTNO 20 there are two contenders for the first position Scott and
Ford. So it has given the same number 1 for those and directly given
rank number 2 for Jones of the same deptno 20.
Same case is for 3 records of deptno 30.
97
Row_Number()
It will provide the row numbers for the result set once the records are sorted.
Order By is the mandatory clause required for row_number().
98
4.6 Set operators Enhancements
INTERSECT
-- Shows the common values from the queries.
-- It eliminates the duplicates
-- To see the common products of 107 and 108
select prodname
from pune
where custid =107
INTERSECT
select prodname
from pune
where custid =108;
EXCEPT
-- Shows the records retrieved from the first query which are not present in the
-- second query
--Eliminates duplicates
-- To see products sold to 107 and not to 108
select prodname
from pune
where custid =107
EXCEPT
select prodname
from pune
where custid =108
99
4.8. Referential Integrity Enhancements
On Delete Set Null – Whenever the parent record is deleted then the corresponding
child table(s) foreign key will become null. But the child record is not deleted.
100
On Delete Set Default – Whenever the parent record is deleted then the
corresponding foreign key value gets the default value and the child record is intact.
101
4.9 Try Catch
SQL Server versions before 2005 offered only one simple way to work with exceptions:
the @@ERROR function. This function can be used to determine if an error occurred in
the last statement that was executed before evaluating @@ERROR. For example:
SELECT 1/0
SELECT @@ERROR
-----------
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
-----------
8134
(1 row(s) affected)
In this case @@ERROR returns 8134, which is the error number for a divide-by-zero
error.
Using @@ERROR, you can detect errors and control them to some degree. However,
proper use of this function requires that you check it after every statement; otherwise it
will reset, as shown in the following example:
SELECT 1/0
IF @@ERROR <> 0
BEGIN
SELECT @@ERROR
END
-----------
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
-----------
0
(1 row(s) affected)
Trying to catch the error in this case actually ends up resetting it; the @@ERROR in the
SELECT returns 0 rather than 8134 because the IF statement did not throw an exception.
102
In addition to the fact that the exception resets after each statement, @@ERROR does
not actually handle the exception -- it only reports it. The exception is still sent back to
the caller, meaning that even if you do something to fix the exception in your T-SQL
code, the application layer will still receive a report that it occurred. This can mean
additional complexity when creating application code because you need to handle
exceptions that may needlessly bubble up from stored procedures.
In SQL Server 2005, exceptions can now be handled with a new T-SQL feature:
TRY/CATCH blocks. This feature emulates the exception handling paradigm that exists
in many languages derived from the C family, including C/C++, C#, Java and JavaScript.
Code that may throw an exception is put into a try block. Should an exception occur
anywhere in the code within the try block, code execution will immediately switch to the
catch block, where the exception can be handled.
The term "catch" is of special importance here. When TRY/CATCH is used, the
exception is not returned to the client. It is "caught" within the scope of the T-SQL that
caused it to be thrown.
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
SELECT 'Error Caught'
END CATCH
-----------
(0 row(s) affected)
------------
Error Caught
(1 row(s) affected)
When this batch is run, no exception is reported. Instead, the message "Error Caught" is
selected back. Of course, your T-SQL code does not have to send back any kind of
specific message in the CATCH block. Any valid T-SQL can be used, so you can log the
exception or take action to remedy the situation programmatically, all without reporting it
back to the caller.
While merely being able to catch an exception is a great enhancement, T-SQL is also
enhanced with new informational functions that can be used within the CATCH block.
103
These functions are:
Unlike @@ERROR, the values returned by these functions will not reset after each
statement and, as a result, the functions will return consistent values over the entire time a
CATCH block is executed. For instance:
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
select ERROR_MESSAGE()
select ERROR_NUMBER()
END CATCH-----------
(0 row(s) affected)
------------
Error Caught
(1 row(s) affected)
-------------------------------------------- ---------------
Divide by zero error encountered. 8134
(1 row(s) affected)
Error control is important in database programming because it gives you the ability to roll
back transactions in response to problems. By default, SQL Server typically does not stop
transactions due to exceptions, which can result in invalid data. Consider the following
batch:
104
BEGIN TRANSACTION
INSERT Funds VALUES (10)
INSERT Funds VALUES (-1)
COMMIT TRANSACTION
SELECT *
FROM Funds
(1 row(s) affected)
Msg 547, Level 16, State 0, Line 9
The INSERT statement conflicted with the CHECK constraint
"CK__Funds__Amount__67A95F59". The conflict occurred in database "master", table
"dbo.Funds", column 'Amount'.
The statement has been terminated.
Amount
-----------
10
(1 row(s) affected)
In this case, a table called Funds is created, which includes a CHECK constraint on the
Amount column to ensure that amounts are greater than 0. Once the table is created, a
transaction starts. This implies that INSERTs will be atomic -- all values or no values
should be inserted. However, even though an exception occurs due to violation of the
CHECK constraint, the transaction is committed and one of the values remains in the
table.
BEGIN TRY
BEGIN TRANSACTION
INSERT Funds VALUES (10)
INSERT Funds VALUES (-1)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK
END CATCH
Now, any exception in the TRY block immediately causes code execution to shift to the
CATCH block, thereby rolling back the transaction and ensuring that invalid values stay
out of the table.
105
Exception handling is new to SQL Server, so the question of when to handle exceptions
may be new to many DBAs and database developers. Here I will supply a few general
guidelines to help you get started.
1. Overuse is much better than underuse when it comes to dealing with exceptions. As
illustrated in the transaction example, failure to properly handle exceptions when they
occur leaves you with invalid data in the database. Imagine a database being used to back
financial transactions and think of the possibilities. Exception handling is an absolute
necessity when you care about the quality of your data.
2. Strive to use a TRY/CATCH block whenever you use an explicit transaction and
whenever you modify data. Some practitioners advocate using TRY/CATCH blocks in
every stored procedure in order to log any exception that occurs in the database.
Although this seems like overkill for some applications, it can be a good model for
applications that require extreme integrity. Again, consider financial transactions.
3. Even though you may often use TRY/CATCH to facilitate structured exception
logging, try to remember that not getting exceptions at all is far more desirable than just
catching them when they occur. Heavily test your code and the code around problems
you know exist, rather than letting exception handlers deal with them for you. Just
because the exception is caught does not mean that it didn't occur. Exception handling is
no excuse for sloppy coding techniques. If anything, it should give you a chance to more
readily discover where your problems lie and fix them.
106
5 Database Architecture
Database Files
Secondary data files make up all the data files, other than
the primary data file. Some databases may not have any
secondary data files, while others have several secondary
data files. The recommended file name extension for
secondary data files is .ndf.
Log files
Log files hold all the log information that is used to recover
the database. There must be at least one log file for each
database, although there can be more than one. The
recommended file name extension for log files is .ldf.
SQL Server 2005 does not enforce the .mdf, .ndf, and .ldf file
name extensions, but these extensions help you identify the
different kinds of files and their use.
107
In SQL Server 2005, the locations of all the files in a database
are recorded in the primary file of the database and in the
master database. The Database Engine uses the file location
information from the master database most of the time.
Primary
The primary file group contains the primary data file and any
other files not specifically assigned to another file group. All
pages for the system tables are allocated in the primary file
group.
User-defined
User-defined file groups are any file groups that are specified
by using the FILEGROUP keyword in a CREATE DATABASE or
ALTER DATABASE statement.
Log files are never part of a file group. Log space is managed
separately from data space.
108