Sudhakar SQL Server Notes
Sudhakar SQL Server Notes
INTRODUCTION TO DBMS
Why DBMS: Human needs have increased tremendously. Now people are
doing much more composite tasks than ever before. The society has become very
complex. a person has to work with huge amount of information every day. In
order to work with the enormous information, we must have a system where we
can store, manipulate and share the information all over the world. It is one of the
core reasons for introducing Database Management Systems (DBMS) as well as
Relational Database Management Systems (RDBMS) now-a-days.
So, one thing is clear to us that we store and manipulate data / information into a
database, where the database contains various types of tables for storing various
types of data / information.
Data:
Whatever we are inputting from the keyboard is known as Data. It can also
be called as RAWFACTS / FIGURES
Data never provides any meaning for us
Information:
Processed Data is known as Information
Information always gives meaning for us
Database:
Collection of information belongs to a particular topic (an organization)
written in a predetermined manner stored at a particular place is called as
database.
Types of DBMS:
1) FMS / FDMS (File Management System /File Management Database
System):
This is first model released into the market in 1950s. In this model there is
always arranged in a continue stream of character (or) in a sequential fashion
(or) manner.
Disadvantages:
The Main disadvantage of this model is whenever we need to retrieve any
data we have to start the searching from the beginning of the file so, it
automatically leads to increases the searching time.
Costly in maintains
Required more man power
There is no security
2) HMS/HDMS (Hierarchy Management System / Hierarchy Database
Management System):
This model was developed by IBM in 1960s, When they developed a
project called IMS (Information Management System)
In this model data is always arranged in the form of a tree structure in
different levels
The top level can be called as root. The 2nd , 3rd can be called as parent and
child levels respectively
The main advantage of this model is we can easily retrieve the value without
wasting much time
ROOT
Parent
Parent
Parent
Child
Child
Drawback:
Only one person can share the database simultaneously
No security
3) NDBMS (Network Database Management System):
This model was developed by IBM in 1969, when developing a project is
called IMS (Information Management System)
This model was developed on the basis of an Operating System called
MULTICS (Multiplex Information Computing System)
The main advantage of this model is more than one person can share the
database concurrently (Simultaneously)
Disadvantage:
There is no proper security for the centralized database
Redundancy of the database is increased
It occupies lot of memory and it leads to decrease system performance and
increase the inconsistency.
4) RDMS (Relational Database Management System):
This model was developed by a German scientist Mr. EF.CODD in 1970
Here relation can be defined as commonness between objects these relations
are classified into 3 types
One to One relation
One to Many relation / Many to One relation
Many to Many relation
STUDENT
EMPID
HALL-NO
.Net
Student
Java
Faculty
PHP
.Net
Java
P1
Vendor 2
P2
Vendor 3
P3
CODD RULES:
a.
b.
c.
d.
e.
f.
data definition
view definition
data manipulation (interactive and by program)
integrity constraints
authorization
Transaction boundaries (begin, commit, and rollback).
Note that based on these rules there is no fully relational database management
system available today. In particular rules 6, 9, 10, 11 and 12 are difficult to
satisfy.
Features of RDBMS
EID
P-ID
Sales
Representative
Cost
EName
Salary
Store
s
Products
Warehouse
PName
Servi
ces
Plac
es
Customer
Address
OrderId
CID
MbNo
CNAME
ORDER
Quantity
ordate
VERSIONS
1.0
1.1
4.21
6.0
6.5
7.0
8.0
9.0
10.0
10.5
11.0
12.0
YEAR
1989
1991
1993
1995
1996
1998
2000
2005
2008
2010
2012
2014
RELEASE NAME
SQL Server 1.0
SQL Server 1.1
SQL Server 4.21
SQL Server 6.0
SQL Server 6.5
SQL Server 7.0
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server 2008 R2
SQL Server 2012
SQL Server 2014
CODE NAME
SQLNT
SQL95
Hydra
Sphinx
Shiloh
Yukon
Katmai
Kilimanjaro
Denali
SQL14
Server Type
Server Name
Server Authentication
Username & Password
Server Type:
Database Engine: The Database Engine is the core service for storing,
processing, and securing data (or) it is used to store, manage and to access
the data from the database.
Analysis Services (SSAS): It is used for data warehouse it will show the
data in three dimensions (Rows, Columns and New dimension).
Reporting Services (SSRS): It is a reporting tool used to generate
reports in various formats such as creating interactive, tabular, graphical,
SQL Server Authentication: SQL Server will work on the current user
and when we work on SQL Server authentication then user should enter User Id
and Password (These User ID and Password will give at the time of SQL Server
installation).
Msdb: It is used to store the alerts and job information contains the
SQL commands which are executed by user.
Tempdb: When ever SQL server is started tempdb will be created in
SQL server. It is used to store temporary tables once we restart the
server the tempdb database is destroyed.
User Database: These databases are created and manage by the user for
storing their objects like tables, views, procedure etc.
Primary Data file: It contain the start up information of the database and used
to store database objects like tables, views .This file will saved with an extension
.mdf(Master Data file).
Log File: This file contains transaction query information will saved with an
extension .Ldf (Log Data file).
Data Types in SQL Server: A data type is an attribute that specifies what
types of data enter by the user such as integer, character, decimal, date time etc.
Integer data type: It will allows integer values only such as EID, SID etc
Data Type
Tiny Int
SmallInt
Range
0-255
-32768 to 32767
Stored Memory
1 byte
2 bytes
Int
-2,147,483,648 to 2,147,483,647
4 bytes
Bigint
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
8 bytes
Decimal Data Types: These data types will allow only decimal numbers and it can
divide into two types but both are same.
Decimal (P,S) ---------> P=Precision & D= Scale
Numeric (P,S)
Precision: It allows the total number of decimal digits i.e. both left and right side
of the decimal point. The default precision is 18 and maximum 38.
Ex of Precision:
3457.78543
----------
Precision =9
Scale: It allows right side digits of decimal point only. The default value of scale is
0.
Ex of Scale:
3457.78543
----------
Scale = 5
Precision
1-9
10-19
20-28
29-38
Stored Memory
5 bytes
9 bytes
13 bytes
17 bytes
Money Data Type: This data type will allows currency values and it contain two
type these are
Data Type
Range
Stored Memory
Small money
-214,748,3648
To
214,748,3647
922,337,203,685,477,5808
to
922,337,203,685,477,5807
4 bytes
Money
8 bytes
Date and Time Data Type: These data types are define a particular date and time
of the day.
Date: It defines date only the default format of date data type is yy/mm/dd
Time: It defines time of the day the default format is hh/mm/ss.ms
Date & Time: This will allows the both date and time of the day.
Yy/mm/dd
hh/mm/ss.ms
Binary Data Type: Binary data types are used to store images, videos and
audio data. These can be divided into the following types
Binary (n): It is a fixed length data type. The maximum length of binary
data type is 1-8000 bytes.
Varbinary (n/max): It is a variable length data type. The maximum length
of binary data type is 1-8000 bytes.
Image: it is same as a Varbinary (max)
Note: Instead of text, Ntext and image data types are using Varchar (max),
Nvarchar (max) and Varbinary (max) data types in latest versions of Microsoft
SQL server.
Features of SQL:
SQL is not a case sensitive language it means that all the commands of Sql
are not case sensitive
Every command of sql should ends with a semicolon (;) (It is exemption for
SQL Server)
SQL can be pronounced as Sequel (Structured English Query Language)
SQL can be called as Common Language Interface, which is used to
communicate with any type of database
SQL can be called as NLI (Natural Language Interface). It means that all the
SQL Commands are almost similar to normal English language
Structured query language is mainly divided into 4 sub languages
1. DDL (Data Definition Language)
2. DML (Data Manipulation Language)
3. TCL (Transaction Control Language)
4. DCL(Data Control Language)
SQL
DDL (DR.CAT)
DROP
SP_RENAME
CREATE
ALTER
TRUNCATE
DML (SUDI)
SELECT
UPDATE
DELETE
INSERT
TCL (CRS)
DCL
COMMIT
GRANT
ROLLBACK
REVOKE
SAVE TRANSACTION
2. ALTER:
This command is used to modify the structure of a table using this
command, we can perform four different operations
Using this command we can increase (or) decrease the size of the data
type & also we can change the data type from old data type to new
data type
We can add a new column to the existing table
We can change the column name from old column name to new
column name
We can remove the column from the existing table
This command contains 4 sub commands
1. ALTER- ALTER COLUMN
2. ALTER- ADD
3. SP_RENAME
4. ALTER- DROP
a. ALTER-ALTER COLUMN:
Syntax: ALTER TABLE <TABLE NAME> ALTER COLUMN
<COLUMN NAME> DATA TYPE (SIZE)
Ex: ALTER TABLE EMP ALTER COLUMN ENAME char (25);
b. ALTER-ADD:
Syntax: ALTER TABLE <TABLE NAME> ADD <COLUMNNAME
>DATA TYPE(size);
Ex: ALTER TABLE EMP ADD DEPTNO int;
c. ALTER-DROP:
Syntax: ALTER TABLE <TABLE NAME> DROP COLUMN <COLUMN
NAME>;
Ex: ALTER TABLE EMP DROP COLUMN SAL;
d. SP_RENAME:
Syntax: SP_RENAME TABLENAME.OLDCOLUMN,NEW COLUMN
NAME,COLUMN,;
Ex: SP_RENAME EMP.SAL,SALARY,COLUMN
3. SP_RENAME:
This command is used to change the table name from old table name to new
table name
Syntax: SP_Rename old table name, New table name
Ex: SP_Rename EMP,EMP1
4. TRUNCATE:
This command is used for to delete all the records from existing table
permanently
Syntax: TRUNCATE TABLE <TABLE NAME>
Ex: TRUNCATE TABLE EMP;
5. DROP:
This command is used to remove the table permanently from the database
Syntax: DROP TABLE <TABLE NAME>
Ex: DROP TABLE EMP;
Note: SP_help: This command is used to see the structure of table
Syntax: SP_help <table name>
Ex: SP_help EMP
Note: Syntax to view tables in the current database.
Insert
Update
Delete
Select
1. INSERT:
Using this command we can Insert the records into the existing table
We can insert the records into the table in two methods
Explicit method
Implicit method
Explicit method:
In this method user has to enter all the values into all the columns without
anything omitting (or) left any column data
Syntax: INSERT INTO <TABLE NAME> VALUES <VAL1, VAL2,
.VALN>;
(OR)
INSERT <TABLE NAME> VALUES <VAL1, VAL2, .VALN>;
(Here INTO Keyword is optional)
Ex1: INSERT INTO EMP VALUES (101,RAJ,9500);
Ex2: INSERT EMP VALUES (101,RAJ,9500);
1 Row(s) affected
Implicit method:
In this method we can enter the values into the required columns in the table,
so that user can omit (or) left some columns data while he enters the records
into the table
If the user omit any column data in the table then it automatically takes
NULL
Syntax: INSERT INTO <TABLE NAME> (COL1, COL2.COLN)
VALUES (VAL1, VAL2 VALN);
Ex: INSERT INTO EMP (EID, SAL) VALUES (106,9999);
2. UPDATE:
This command is used to modify the data in the existing table
By using this command we can modify all the records in the table & also
specific records in the table (Using where clause)
Syntax: UPDATE <TABLE NAME> SET COL=VALUE;
Ex: UPDATE EMP SET SAL=10000;
Syntax change for more than one data simultaneously
Syntax: UPDATE <TABLE NAME> SET COL1=VALUE,
COL2=VALUECOLN=VALUE;
Ex: UPDATE EMP SET EID=007,SAL=10000;
3. DELETE:
This command is used to delete the records from existing table
Using this command we can delete all the records and also to delete specific
record (by using where clause)
Syntax: DELETE FROM <TABLE NAME>
Ex: DELETE FROM EMP;
10 row(s) affected
TRUNCATE
DELETE
01
It is a DDL command
It is a DML command
02
It is a permanent deletion
It is temporary deletion
03
04
05
06
Truncate will reset the identity Delete will not reset the identity
Values
value
4. SELECT:
This command is used to retrieve the data from existing table.
Using this command we can retrieve all the records & also specific records
from existing table (by using where clause)
Using this command we can retrieve the data from the table in 3 ways
1. Projection
2. Selection
3. Joins
Syntax: SELECT * FROM <TABLE NAME>
Ex: SELECT * FROM EMP;
* represents all columns
Projection:
Retrieving the data from specific columns is known as Projection
Syntax: SELECT COL1,COL2..COLN FROM <TABLE NAME>
Ex: SELECT EID,ENAME FROM EMP;
Selection:
Retrieving the data based on some condition is called selection
In SQL, whenever we need to check a condition, we need to use a special
clause called where
Syntax: SELECT * FROM <TABLENAME> WHERE (CONDITION);
Ex: SELECT * FROM EMP WHERE EID=101;
WHERE CLAUSE:
This clause is used to check the condition based on the condition, we can
retrieve, update, delete specific records in the table
So we can apply the where clause only in select, update & delete
Select Command With Where clause:
Syntax: SELECT * FROM <TABLE NAME> WHERE <CONDITION>
Ex: SELECT * FROM EMP WHERE EID=102;
Update Command With Where clause:
Syntax: UPDATE <TABLE NAME> SET <COLUMN NAME>=VALUE
WHERE (CONDITION);
Ex: UPDATE EMP SET ENAME=sai WHERE EID=102;
Delete Command With Where clause:
Syntax: DELETE FROM <TABLE NAME>WHERE <CONDITION>
Ex: DELETE FROM EMP WHERE EID=102;
ALIAS:
ALIAS is a duplicate name (or) alternate name for the original column name
(or) Table name (or) an expression name.
Column level Alias:
Syntax: SELECT COLUMN NAME AS ALIAS NAME,
COLUMN NAME AS ALIAS NAME,
:
:
COLUMN NAME AS ALIAS NAME FROM <TABLE NAME>;
EX: SELECT EID AS EMPLOYEE ID, ENAME AS EMPLOYEE
NAME, SAL AS SALARY FROM EMP;
NOTE: In the above example the keyword as is optional
EX: SELECT EID EMPLOYEE ID, ENAME EMPLOYEE NAME,
SAL SALARY FROM EMP;
NOTE: In the above example quotations is also optional but there should
not be space between column name
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL
SALARY FROM EMP;
Ex: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL
SALARY, SAL*12 ANNUALSALARY FROM EMP;
EX: SELECT EID EMPLOYEEID, ENAME EMPLOYEENAME, SAL
SALARY FROM EMP WHERE ANNUALSALARY > 115000
In the above example returns the runtime error message invalid column
name annual salary because we cannot check the conditions on Alias name
select ABS(-15)---- 15
select ABS(45)----- 45
CEILING (): Returns the smallest integer greater than, or equal to, the given
numeric expression.
Ex:
select ceiling(15.000)----15
select ceiling(15.0001)----16
select ceiling(-12.34)-----(-12)
FLOOR (): Returns the largest integer less than or equal to the given numeric
expression.
Ex:
select floor(15.000)---15
select floor(15.0001)----15
select floor(-12.34)----(-13)
select SQUARE(5)---25
select SQUARE(25)---5
SIGN (): Returns the positive (+1), zero (0), or negative (-1) sign of the given
expression.
Ex:
select SIGN(42)------------1
select SIGN(0)-------------0
select SIGN(-42)-----------(-1)
select LOG10(10)----1
SIN (): Returns the trigonometric sine of the given angle (in radians) in an
approximate numeric expression.
Ex:
COS (): A mathematic function that returns the trigonometric cosine of the given
angle (in radians) in the given expression.
Ex:
LEFT (): Returns the left part of a character string with the specified number of
characters.
Ex:
RIGHT (): Returns the right part of a character string with the specified number of
characters.
Ex:
LEN (): Returns the number of characters, rather than the number of bytes, of the
given string expression.
Ex:
UPPER (): Returns a character expression with lowercase character data converted
to uppercase.
Ex:
Select LTRIM (
HELLO) --------HELLO
RTRIM (): Returns a character string after truncating all trailing blanks.
Ex:
) -------HELLO
REPLACE (): Replaces all occurrences of the second given string expression in
the first string expression with a third expression.
Ex:
SUDHAKAR
DAY (): Returns an integer representing the day date part of the specified date.
Ex: Select DAY (get date ())
MONTH (): Returns an integer that represents the month part of a specified date.
Ex: Select MONTH (get date ())
YEAR (): Returns an integer that represents the year part of a specified date.
Ex:
GETUTCDATE (): Returns the date time value representing the current UTC
time (Coordinated Universal Time).
Ex: Select GETUTCDATE ();
DATE NAME (): Returns a character string representing the specified date part of
the specified date.
Ex: Select DATE NAME (DW, get date ())
DATE PART (): Returns an integer representing the specified date part of the
specified date.
Ex: Select DATEPART (DD, get date ())
DATE ADD (): Returns a new date time value based on adding an interval to the
specified date.
Ex: Select DATEADD (DD, 5, get date ())
DATE DIFF (): Returns the difference between the start and end dates in the give
date part format.
Ex: Select DATEDIFF (MM, 2012-12-15, get date ())
Conversion Functions: These functions are used to convert one data type
to another. We have two conversion functions are CAST and CONVERT both
provide similar functionality.
CAST (): Convert to one data type to another type.
Syntax: CAST (Expression as data type [size])
Ex: Select CAST (10.2587 as Int) -------------10
CONVERT (): Convert function can be used to display date time data in different
format.
Syntax: Convert (Data type [size], Expression, Style value)
Ex: Select Convert (Varchar (24), get date (), 113)
The table below represents the style values for date time or small date time
conversion to character data:
Sno
Value
1
2
3
4
5
6
7
8
0 or 100
101
102
103
104
105
106
107
108
9 or 109
10
11
12
14
-
110
111
112
13 or 113
114
20 or 120
21 or 121
126
130
131
Output
mon dd yyyy hh:mi AM (or PM)
mm/dd/yy
yy.mm.dd
dd/mm/yy
dd.mm.yy
dd-mm-yy
dd mon yy
Mon dd, yy
hh:mm:ss
mon dd yyyy hh:mi:ss:mmmAM (or
PM)
mm-dd-yy
yy/mm/dd
Yymmdd
dd mon yyyy hh:mi:ss:mmm (24h)
hh:mi:ss:mmm (24h)
yyyy-mm-dd hh:mi:ss (24h)
yyyy-mm-dd hh:mi:ss.mmm (24h)
yyyy-mm-ddThh:mi:ss.mmm (no
spaces)
dd mon yyyy hh:mi:ss:mmmAM
dd/mm/yy hh:mi:ss:mmmAM
Standard
Default
USA
ANSI
British/French
German
Italian
Default+millisec
USA
Japan
ISO
ISO8601
Hijiri
Hijiri
AVG (): Returns the average of the values in a group. Null values are ignored.
Ex:
COUNT (): Returns the number of records in a table. This function again use in
three ways.
1. COUNT (*): It Returns total number of records in a table
Ex: SELECT COUNT (*) FROM EMP
2. COUNT (Expression/Column name): It returns number of records
including duplicate values but not null vales.
Ex: SELECT COUNT (ENAME) FROM EMP
3. COUNT (Distinct Column name): It returns number of records without
null and duplicate values.
Ex: SELECT COUNT (Distinct ENAME) FROM EMP
Distinct Key: If we use this key word on a column with in a query then it will
retrieve the values of the column without duplicates.
Assignment operator
Arithmetic operator
Comparison operator
Logical operator
Set operator
Select 20/5+20/5
Select 35.50+20
Ex2: WAQ to find student TOTAL, AVERAGE AND CLASS OF a table
Step1: Create table student (Sid int, sname varchar (50), maths int, phy int, che
int, total int, average int, class varchar (max))
Step2: Update student set total=maths+phy+che
Step3: Update student set average=total/3
Step4: Update student set class=
Case
When average>=60 then 'First class'
When average>=50 then 'second class'
When average>=40 then 'third class'
Else
'Fail'
End
CASE (): This function is used to execute list of conditions and returns a value.
Syntax: Case
<Condition 1>-----------<Condition N>
Else
<Statement>
End
Logical operator: Logical operators test for the truth of some condition.
Logical operators, like comparison operators, return a Boolean data type with a
value of TRUE or FALSE. Logical operators are AND , OR , NOT, BETWEEN,
NOT BETWEEN, LIKE, NOT LIKE, IN, NOT IN, EXISTS,NOT EXISTS, ANY,
ALL, SOME.
Examples:
Write a Query to display the employee details whose salary is greater than or
equal to 9000 and less than 15000
SELECT * FROM EMP WHERE SAL>=9000 AND SAL<=15000
(OR)
SELECT * FROM EMP WHERE SAL BETWEEN 9000 AND 15000
Write a Query to display the employee details whose salary is not between
9000 and 15000
SELECT * FROM EMP WHERE SAL NOT BETWEEN 9000 AND15000
Write a Query to display the employee details whose name starts with r
SELECT * FROM EMP WHERE ENAME LIKE r%
Write a Query to display the employee details whose name ends with y
SELECT * FROM EMP WHERE ENAME LIKE %Y
Write a Query to display the employee details whose name contains the
letter a
SELECT * FROM EMP WHERE ENAME LIKE %A%
Write a Query to display the employee details whose names contains only
three letters
SELECT * FROM EMP WHERE ENAME LIKE ---
Write a Query to display the employee details whose names contain r and
salary greater than 9000
SELECT * FROM EMP WHERE ENAME LIKE %R% AND SAL>9000
Write a Query to display the employee details whose greater than ram
SELECT * FROM EMP WHERE ENAME>RAM
Write a Query to display the employee details whose employee id starts with
1 and ends with 1
SELECT * FROM EMP WHERE EID LIKE 1%1
(SQL commands are not case sensitive and also data available in SQL also not case
sensitive, in oracle Data available is case sensitive)
Set Operators: Set operators combine results from two or more queries into a
single result set. SQL Server provides the following set operators.
UNION
UNION ALL
INTERSECT
EXCEPT
To combine the results of two queries we need to follow the below basic rules.
The number and the order of the columns must be the same in all queries.
The data types must be compatible(Well-Matched)
Example:
CREATE TABLE EMP_HYD (EID INT, ENAME VARCHAR (50), SALARY
MONEY)
CREATE TABLE EMP_CHENNAI (EID INT, ENAME VARCHAR (50))
EMP_HYD
EID
ENAME
SALARY
101
SAI
25000.00
102
SIDDHU
32000.00
103
KAMAL
42000.00
104
NEETHU
63000.00
-----------------------------------------------EMP_CHENNAI
EID
ENAME
101
SAI
105
POOJA
106
JASMIN
UNION: it combines the result of two or more select statements into a single result
set that includes all the records belongs to all queries except duplicate values.
Ex:
OUTPUT: ENAME
JASMIN
KAMAL
NEETHU
POOJA
SAI
SIDDHU
OUTPUT:
ENAME
SAI
SIDDHU
KAMAL
NEETHU
SAI
POOJA
JASMIN
INTERSECT: INTERSECT returns any distinct values that are common in left
and right tables.
Ex:
OUTPUT:
ENAME
SAI
EXCEPT: EXCEPT returns any distinct values from the left query that are not
found on the right query.
Ex:
ENAME
KAMAL
NEETHU
SIDDHU
Ex:
ENAME
JASMIN
POOJA
WHERE: This clause is used for filter or restricts the records from the table.
Ex: SELECT * FROM EMP WHERE SAL=10000
ORDER BY: The order by clause is used to sort or arrange the data in
ascending or descending order with in table. By default order by clause
arrange or sort the data in ascending order only.
TOP N CLAUSE: This clause is used to fetch a top n number of records from a
table.
Ex: SELECT TOP 3 * FROM EMP
Ex: UPDATE TOP 3 EMP SET ENAME=SAI
Ex: DELETE TOP 3 FROM EMP
GROUP BY: Group by clause will use for to arrange similar data into groups.
when we apply group by clause in the query then we use group functions like
count(),sum(),max(),min(),avg().
If we use group by clause in the query, first the data in the table will be divided
into different groups based on the columns and then execute the group function on
each group to get the result.
Ex1: WAQ to find out the number of employees working in the organization
Sol: SELECT COUNT (*) FROM EMP
Ex2: WAQ to find out the number of employees working in each group in the
organization.
Sol: SELECT DEPT, COUNT=COUNT (*) FROM EMP GROUP BY DEPT
Ex3: WAQ to find out the total salary of each department in the organization
Sol: SELECT DEPT, TOTALSALARY=SUM (SALARY) FROM EMP GROUP
BY DEPT (Like this we can find max, min, avg salary in the organization)
HAVING CLAUSE: Having clause is also used for filtering and restricting the
records in a table just like where clause.
Ex: WAQ to find out the number of employees in each department only if the
count is greater than 3
Sol: SELECT DEPT, COUNT=COUNT (*) FROM EMP GROUP BY DEPT
HAVING COUNT (*) >3
HAVING
HAVING clause is used to filter and
restrict the records after grouping
But we can use HAVING clause at this
situations
HAVING clause cannot be applied
without a group by clause
Where as HAVING clause is used along
with group by clause to filter or restrict
groups
Constraint in SQL
Why Constraint in SQL:
Domain Integrity: Domain integrity ensures the data values inside a database
follow defined rules for values, range, and format. A database can enforce these
rules using CHECK KEY constraints.
1. Unique Key:- Unique key constraint is use to make sure that there is no
duplicate value in that column. Both unique key and primary key both enforces the
uniqueness of column but there is one difference between them unique key
constraint allow null value but primary key does not allow null value.
In a table we create one primary key but we can create more than one unique key
in Sql Server.
Ex: create table EMP(EID int unique,ENAME
into
into
into
into
Department
Department
Department
Department
values(10,'Sales','Chennai')
values(20,'Production','Mumbai')
values(30,'Finance','Delhi')
values(40,'Research','Hyderabad')
To create Employee Table(CHILD TABLE):create table Employee(EID int,ENAME varchar(50),SALARY money,Deptno int
foreign key references Department(Deptno))
Insert Records Into Employee Table:
insert
insert
insert
insert
into
into
into
into
Employee
Employee
Employee
Employee
values(101,'Sai',35000,10)
values(102,'Pavan',45000,20)
values(103,'Kamal',74000,30)
values(104,'Ravi',58000,40)
When we impose the foreign key constraint and establish relation between the
table,the followiong three rules will come into picture.
Rule1:- Cannot insert a value into the foreign key column provided that value is
not existing under the refernce key column of the parent table.
Rule2:- Cannot update the reference key value of a parent table provided that
value has corresponding child record in the child table with out addressing what to
do with the child record.
Rule3:- Cannot delete a record from the parent table provided that records
reference key value has child record in the child table with out addressing what to
do with the child record.
If we want to delete or update a record in the parent table when they have
corresponding child records in the child table we are provide with a set of rules to
perform delete and update operations knows as cascade rules.
On delete cascade:- It is used to delete a key value in the parent table which is
referenced by foreign key in other table all rows that contains those foreign keys in
child table are also deleted.
On Update cascade:- It is used to Update a key value in the parent table which is
referenced by foreign key in other table all rows that contains those foreign keys in
child table are also updated.
If we apply this rule while creating the child table like below
create table Emp(EID int,ENAME varchar(50),SALARY money,Deptno int
foreign key references Department(Deptno)on delete cascade on update cascade)
Ex: update Department set Deptno=222 where Deptno=20
delete from Department where Deptno=222
Note: Before adding primary key constraint make the column is not null
later add primary key like below.
Ex: ALTER TABLE EMPLOYEE ALTER COLUMN EID INT NOT NULL
Ex: ALTER TABLE EMPLOYEE ADD CONSTRAINT X PRIMARY KEY (EID) (Here x is
constraint variable)
JOINS IN SQL: Joins are used for retrieving the data from more than one
table at a time. Joins can be classified into the following types.
EQUI JOIN
INNER JOIN
OUTER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
NON EQUI JOIN
SELF JOIN
CROSS JOIN
NATURAL JOIN
EQUI JOIN: If two or more tables are combined using equality condition then
we call as an Equi join.
Ex: WAQ to get the matching records from EMP and DEPT tables
Sol: SELECT * FROM EMP, DEPT WHERE (EMP.EID=DEPT.DNO) (NONANSI STANDARD)
Sol: SELECT E.EID, E.ENAME, E.SALARY, D.DNO, D.DNAME FROM EMP
E, DEPT D WHERE E.EID=D.DNO (NON-ANSI STANDARD)
INNER JOIN: Inner join return only those records that match in both table
Ex: SELECT * FROM EMP E INNER JOIN DEPT D ON E.EID=D.DNO (ANSI)
OUTTER JOIN: It is an extension for the Equi join. In Equi join condition we
will be getting the matching data from the tables only. So we loss UN matching
data from the tables.
To overcome the above problem we use outer join which are used to getting
matching data as well as UN matching data from the tables. This outer join again
classified into three types
LEFT OUTER JOIN: It will retrieve or get matching data from both table as well
as UN matching data from left hand side table
Ex: SELECT * FROM EMP LEFT OUTER JOIN DEPT ON
EMP.EID=DEPT.DNO;
RIGHT OUTER JOIN: It will retrieve or get matching data from both table as
well as UN matching data from right hand side table
Ex: SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON
EMP.EID=DEPT.DNO;
FULL OUTER JOIN: It will retrieve or get matching data from both table as well
as UN matching data from left hand side table plus right hand side table also.
Ex: SELECT * FROM EMP FULL OUTER JOIN DEPT ON
EMP.EID=DEPT.DNO;
NON EQUI JOIN: If we join tables with any condition other than equality
condition then we call as a non Equi join.
Ex: SELECT * FROM EMP, SALGRADE WHERE (SALARY > LOWSAL)
AND (SALARY < HIGHSAL)
SELF JOIN: Joining a table by itself is known as self join. When we have some
relation between the columns within the same table then we use self join.
When we implement self join we should use alias names for a table and a table
contains any no. of alias names.
Select * from course c inner join student s on c.cid=s.cid inner join register r on
s.cid=r.cid
Select * from student s left outer join course c on s.cid=c.cid left outer join
register r on c.cid=r.cid
BEGIN TRANSACTION
COMMIT
ROLLBACK
SAVE POINT
Begin transaction
<Write Statements>
COMMIT: Commit command is used to end the transaction and save the data
permanent part of the database (or) it is used to make the transaction is permanent
so we cannot undo or recall the records.
Commit is used for saving the data that has been changed permanently
because whenever you perform any DML (Data Manipulation Language)
like UPDATE, INSERT OR DELETE then you are required to write
Commit at the end of all or every DML operation in order to save it
permanently.
If you do not write Commit then your data will be restored into its previous
condition.
Syntax:
Begin Transaction
<Write Statements>
Commit
Ex:
BEGIN TRANSACTION
INSERT INTO EMPLOYEE VALUES(105,'KAMAL',62000,'MUMBAI')
INSERT INTO EMPLOYEE VALUES(106,'SUJATHA',82000,'DELHI')
COMMIT
The above records are stored permanently into a table because we commited
that records.so we cannot roll back in to its previous position.
ROLLBACK: Rollback command is used to undo the transactions and gets back
to the initial state where transaction started.
Whereas if you want to restore your data into its previous condition then
you can write Rollback at any time after the DML queries has been written
but remember once Commit has been written then you cannot rollback the
data.
Moreover you can only rollback the DML queries that have been written
after the last commit statement. The concept of commit and rollback is
designed for data consistency because many users manipulate data of the
same table, using the same database so the user must get updated data.
That is why commit and rollback are used.
Syntax:
Ex:
Begin Transaction
Rollback
BEGIN TRANSACTION
DELETE FROM EMPLOYEE WHERE EID=105
DELETE FROM EMPLOYEE WHERE EID=106
BEGIN TRANSACTION
ROLLBACK
The above records we can rollback into a table because those records are not
commited.
SAVEPOINT: Save point is used for dividing (or) breaking a transaction into
multiple units. So that user will have a chance of roll backing a transaction up to a
location.
When a user sets a save point with in a transaction the save point defines a
location to which a transaction can return if part of the transaction
conditionally canceled.
If a transaction is roll back to a save point, it must be proceed to completion
of the transaction with commit statement or it must be cancelled altogether
by rolling the transaction back to its beginning
Syntax:
Begin Transaction
Save transaction < transaction name>
<Write Statements>
Ex:
BEGIN TRANSACTION
UPDATE EMPLOYEE SET SALARY=99000 WHERE EID=101
UPDATE EMPLOYEE SET SALARY=88000 WHERE EID=102
SAVE TRANSACTION S1
UPDATE EMPLOYEE SET SALARY=77000 WHERE EID=103
UPDATE EMPLOYEE SET SALARY=66000 WHERE EID=104
SAVE TRANSACTION S2
UPDATE EMPLOYEE SET SALARY=55000 WHERE EID=105
UPDATE EMPLOYEE SET SALARY=44000 WHERE EID=106
In the above case we are dividing or breaking the transaction into three
units.so we have a chance of rollbacking either completely i.e six statements
get roll back (or) roll back save point S1 i.e four statements(103 to 106) (or)
rollback save point S2 i.e two records (105,106 ) only
CASE 1:
BEGIN TRANSACTION
ROLLBACK
All records will roll back i.e complete records(six records)
CASE 2:
BEGIN TRANSACTION
ROLLBACK TRANSACTION S1
BEGIN TRANSACTION
ROLLBACK TRANSACTION S2
We can roll back two records only i.e 105 and 106
Sub Query: A select query contains another select query is called sub Query.
In this, there will be two queries those are called as inner query and outer query.
When it is executed, first inner query is executed later outer query will be executed
Nested Sub queries: In a sub query, Outer query depends on result of inner
query is called as Nested sub query.
Examples:
1) WAQ to find the details of employee who is earning the highest salary.
Sol: select * from employee where Salary=(select MAX(salary) from
employee)//subquery
2) WAQ to find the details of employee who is earning second highest salary.
Sol: select * from employee where Salary=(select MAX(salary)from employee
where Salary<(select MAX(salary) from employee)) //multiple sub query
3) WAQ to find the details of employee who is earning third highest salary.
Sol: select * from employee where Salary=(select MAX(salary)from employee
where Salary<(select MAX(salary) from employee where Salary <(select
MAX(salary) from employee))) //nested subquery
4) WAQ to display employee details who are working in .NET department.
Sol: select * from employee where EID IN (select EID FROM employee where
DNAME='.NET')
5) WAQ to display employee details who are working in JAVA or HR
department.
Sol: select * from employee where EID IN (select EID FROM employee where
DNAME='.NET' OR DNAME='HR')
Disadvantage: Sub query execution will be fast and co related sub query
execution is slow because it will check every row of inner query with every row of
the outer query.
Examples:
6) WAQ to display top 2 salaries list from employee table.
Sol: Select * from employee E where 2>(select count(salary) from employee M
where M.salary>E.salary)
(Or)
Sol: Select * from employee E where 2>(select count(Distinct salary) from
employee M where M.salary>E.salary)
Note: - Here Distinct Key will be used when the table contain duplicate values.
7) WAQ to display least 2 salaries list from employee table.
Sol: Select * from employee E where 2>(select count(salary) from employee M
where M.salary<E.salary)
(Or)
Sol: Select * from employee E where 2>(select count(Distinct salary) from
employee M where M.salary<E.salary)
8) WAQ to display N th salary from employee table.
Sol: Select * from employee E where 0=(select count( salary) from employee
M where M.salary>E.salary)
Note: When condition is M.salary>E.salary / M.salary<E.salary then
N=0 then first highest salary / first least salary
N=1 then second highest salary/second least salary
N=2 then third highest salary / third least salary
9) WAQ to get the details of the department in which employee are working.
Select * from department D Exists (select * from employee E where
E.deptno=D.deptno)
10)
WAQ to get the details of the department in which employee are not
working.
Select * from department D not Exists (select * from employee E where
E.deptno=D.deptno)
Syntax to Find Any Position Record From A table
SELECT * FROM(SELECT * ,ROW_NUMBER() OVER (ORDER BY
empid) AS RowNum FROM Employee) employee WHERE RowNum
=15
Syntax to Delete Duplicate Records from a table contains more than two same
duplicate values:
SID
10
20
30
30
30
30
30
SNAME
Sai
Siddhu
Meena
Meena
Meena
Meena
Meena
FEE
12000
45000
65000
65000
65000
65000
65000
rownum
1
1
1
2
3
4
5
with duplicates as
(select * ,ROW_NUMBER() over(partition by sid,sname, fee order by
sid,sname,fee) rownum from student)
delete from duplicates where rownum > 1
select the complete above query and execute then we delete all duplicate records
which are greater than 1 i.e.output is like below
SID
10
20
30
SNAME
Sai
Siddhu
Meena
FEE
12000
45000
65000
rownum
1
1
1
INDEXES IN SQL:
Why We Need Indexes:
1. Generally a library has a huge collection of books, files, etc... A student
requests the librarian for a book of Microsoft SQL Server 2008, if we think
without an index the librarian had to find this without any help she/he has to
search one by one! This must be time consuming; so with a proper
arrangement, that is with the help of an index, it very much easier and faster
to find out the desired one.
2. One of the most important routes to high performance in a SQL Server
database is the index. Indexes speed up the querying process by providing
quickly access to rows in the data tables, similarly to the way a books index
helps you find information quickly within that book.
What is INDEX:
Index is a database object which is used for the quick retrieving of the data
from the table.
An index contains keys built from one or more columns in the table and map
to the storage location of the specified data.
By using indexes we can save time and can improve the performance of
database queries and applications.
When we create an indexes on any column, SQL server internally maintain a
separate table called index table. So that when ever user trying to retrieve the
data from existing table depends on index table SQL server directly go to the
table and retrieve required data very quickly.
In a table we can use max 250 indexes. The index type refers to the way the
index is stored internally by SQL Server. So a table can contain the two
types of indexes.
1. Clustered
2. Non-Clustered
Clustered Index:
The only time the data rows in a table are stored in sorted (ascending order
only) order structure is when the table contains a clustered index. When a
table has a clustered index then is called a clustered table. If a table has no
clustered index, its data rows are stored in an unordered structure.
A table can have only 1 clustered index on it, which will be created when
primary key constraint is used in a table.
Non-Clustered Indexes:
Non-clustered indexes will not have any arrangement order (Unordered
structure) of the data in the table. In a table we can create 249 non-clustered
indexes.
If we dont mention clustered indexes in a table then default is stored as nonclustered indexes.
Syntax: Create Index <Index Name> on <Table Name> (Column Name);
EX:
VIEWS IN SQL: View is database object which is like table but logical.
We can call it as a logical or virtual table because it does not has a physical
existence.
It is a logical table use to get the required information from the table. View
will be created by using select statement and table used for the creation of
the view is called as base table.
View will not store records in it and will not occupy memory space with
help of structure existing in it and records will be displayed from table.
Simple view: we create a view based on one table is called simple view or
Updatable view.
Complex view: we create a view based on more than one table is called complex
view or Non-Updatable view.
Syntax:
T/SQL Programming
T/SQL stands for Transact Structure Query Language. It is an extension of
SQL language. This T/SQL is same as PL/SQL in oracle.
In SQL we can execute single line statement only where as in T/SQL we can
execute block of statements at a time.
SQL does not support conditional and looping statements like IF-Else and
While loop. But we can implement these conditional and looping statements
in T/SQL.
SQL language will not provide reusability facilities where as T/SQL
language will provide reusability facilities by defining objects such as
Procedures and Functions.
T/SQL commands can be embedded inside the programs where program is a
block of code.
T/SQL Program blocks can be divided into two types. Those are
1. Anonymous Blocks
2. Sub-Program Blocks
Sub-Programs: Sub program Blocks are called as named block of code which
is executed at any point of time and stored on database. These blocks are providing
reusability of code.
{
Statements
}
EX: If there are multiple statements being enclosed between each block then we
can put them under Begin and End Statements.
DECLARE @WEEK INT
SET @WEEK=DATEPART(DW, GETDATE())
IF @WEEK=1
PRINT 'SUNDAY'
ELSE IF @WEEK=2
PRINT 'MONDAY'
ELSE IF @WEEK=3
PRINT 'TUESDAY'
ELSE IF @WEEK=4
PRINT 'WEDNESDAY'
ELSE IF @WEEK=5
PRINT 'THURSDAY'
ELSE IF @WEEK=6
PRINT 'FRIDAY'
ELSE IF @WEEK=7
PRINT 'SATURDAY'
CASE FUNCTION: The case function what we have discussed under the System
Functions can also be used here as following:
DECLARE @WEEK INT
SET @WEEK=DATEPART(DW, GETDATE())
SELECT CASE @WEEK
WHEN 1 THEN 'SUNDAY'
[BEGIN]
< sql_statement | statement_block >
[BREAK]
< sql_statement | statement_block >
[CONTINUE]
< sql_statement | statement_block >
[END]
-If there are multiple statements being enclosed then we can put them under Begin
and End Statements.
BREAK: Causes an exit from the innermost WHILE loop. Any statements that
appear after the END keyword, marking the end of the loop, are executed.
CONTINUE: Causes the WHILE loop to restart, ignoring any statements after the
CONTINUE keyword.
Program 1:
DECLARE @X INT
SET @X=0
WHILE @X<10
BEGIN
SET @X=@X+1
PRINT @X
END
Program 2:
DECLARE @X INT
SET @X=0
WHILE @X<10
BEGIN
SET @X=@X+1
IF @X=6 BREAK
PRINT @X
END
-In this case the break statement brings the control out of the loop printing from 1
to 5.
Program 3:
DECLARE @X INT
SET @X=0
WHILE @X<10
BEGIN
SET @X=@X+1
IF @X=6 CONTINUE
PRINT @X
END
-In this case the continue statement will skip the print statement when the value of
x is 6 so prints from 1 to 5 and 7 to 10.
Comments in TSQL: Comments will be ignored will executing the program, they
will increase the readability and aids understanding of the program.
Single Line Comments (--)
Multi Line Comments (/* .. */)
Assinging values from columns into variables: Till now we were assigning static
values to the variables using the SET statement, but we can also assign values from
a column into the variables as following:
SELECT @<var>=<col_name> [, n] FROM <table_name>
[CONDITIONS]
SELECT @ENAME=ENAME FROM EMP WHERE EMPNO=1001
-A simple TSQL program which takes the Empno and prints the Name and Salary.
DECLARE @EMPNO INT, @ENAME VARCHAR(50), @SAL MONEY
SET @EMPNO=1005
SELECT @ENAME=ENAME, @SAL=SAL FROM EMP WHERE
EMPNO=@EMPNO
PRINT @ENAME + ' EARNS ' + CAST(@SAL AS VARCHAR)
-A Program which takes the Empno and increments the Salary of the person on the
following criteria:
If Job is President increment with 10%
If Job is Manager increment with 8%
If Job is Analyst increment with 6%
If Job is any thing other incrment with 5%
Stored Procedures/Procedure:
end
Output: exec spdel 4
5)create a procedure to accept employee ID and update the employee details from
employee table.
create procedure spupdate
@eid int,@ename varchar(max),@salary money,@address char(30)
as
begin
update Employee set
EmpName=@ename,Salary=@salary,Address=@address where
EmpID=@eid
end
Output: exec spupdate 1,'kamal',88000,'vizag'
6)create a procedure to add records in employee table.
create procedure spinst
@eid int,@ename varchar(50),@salary money,@address varchar(50)
as
begin
insert into Employee values(@eid,@ename,@salary,@address)
end
Output: exec spinst 6 ,'Suman' ,41000 ,'chennai'
9) A Procedure which takes the Empno and prints the Net Salary of the Employee.
CREATE PROCEDURE Net_Sal(@Empno int)
As
Begin
Declare @VSal money, @NSal money, @VPF money, @VPT money
EXEC Deductions @Empno, @VPF OUTPUT, @VPT OUTPUT
SELECT @Sal=Sal FROM Emp WHERE Empno=@Empno
SET @NSal = @VSal - @VPF - @VPT
Print Net Salary of the Employee is: + Cast(@NSal as Varchar)
End
-Executing the above Procedure:
EXEC Net_Sal 1005
2) Create a function that takes an employee id and returns the salary of that
employee.
create function fsal(@eid int)
returns money
as
begin
declare @sal money
select @sal=salary from employee where empid=@eid
return @sal
end
Output:select dbo.fsal(1)
Syntax:
Create Function <Function Name> (@parameter <Data Type> [size])
Returns <Table>
As
Return <return select statement>
Ex: Create a function that accept the Address and returns the list of employee
working in given address from the table.
Ex:Create a function to get the deptno and return list of employee working in EMP
and DEPT tables.
DML Triggers: DML triggers execute when the user tries to modify or change
data through data manipulation language events. Those are Inserting, Update and
Delete statements on the table.
DML triggers can be used to enforce business rules and data integrity. With the
help of a DML trigger we can enforce integrity which cannot be done with
constraints.
Syntax:
Ex: A trigger that will convert the dname and location into upper case when the
user insert in lowercase.
create trigger per_trg
on person after insert
as
begin
declare @pid int,@pname varchar(50),@loc varchar(50)
select @pid=pid,@pname=pname,@loc=loc from inserted
update person set pname=upper(@pname),loc=upper(@loc) where pid=@pid
end
EX: A program which will restrict the Delete operation if the Job of the person is
Manager.
ALTER TRIGGER EMP_DELETE_TRG
ON EMP AFTER DELETE
AS
BEGIN
DECLARE @JOB VARCHAR(50)
SELECT @JOB=JOB FROM DELETED
IF @JOB='MANAGER'
BEGIN
ROLLBACK
RAISERROR('CANNOT DELETE MANAGER FROM THE TABLE', 15,
1)
END
END
-To test the following Trigger execute the following statement:
DELETE FROM EMP WHERE EMPNO=1002
EX: A Trigger which will restrict to update the Salary of the Employee if the New
Salary is less than the Old Salary.
CREATE TRIGGER EMP_UPDATE_TRG
ON EMP AFTER UPDATE
AS
BEGIN
DECLARE @OLDSAL MONEY
DDL Triggers: DDL triggers fire in response to a data definition language event
like create, Alter, drop etc.A DDL triggers is a special type of procedure that
executes in response to a server scoped or database scoped events.
Syntax:
Create Trigger <Trigger Name> on database after <Event type>
As
Begin
<Statements>
End
Ex: Write a trigger which restricts dropping of a table from the database.
create trigger restdrop on database after drop_table
as
begin
rollback
raiserror('Can not drop table under this database',1,1)
end
Ex2: Write a trigger which restricts Creating of a table from the database.
create trigger restcret on database after create_table
as
begin
rollback
raiserror('Can not create table under this database',1,1)
end
Ex3: Write a trigger which restricts Alter of a table from the database.
create trigger restalt on database after Alter_table
as
begin
rollback
raiserror('Can not Alter table under this database',1,1);end
Magic Tables: SQL Server allows you to define a Magic Table. Magic
Tables are invisible tables or virtual tables. You can see them only with the help
Triggers in SQL Server.
Magic Tables are those tables which allow you to hold inserted, deleted and
updated values during insert delete and update DML operations on a table in
SQL Server.
Basically there are two types of magic table in SQL server namely inserted
and deleted magic tables update can be performed with help of these twos.
Generally we cannot see these two table, we can only see it with the help
Trigger's in SQL server.
Inserted Magic Table: Whenever you insert a record on that table, that
record will be shown in the INSERTED Magic Table. Now creating a trigger to
see the data in Inserted Magic table.
Example:
Create TRIGGER Trigger_ForInsertmagic
ON Employee
FOR INSERT
AS
Begin
SELECT * FROM INSERTED
End
Now insert a new record in Employee table to see data within Inserted virtual
tables.
Insert into Employee values (12, 'Rahul', 25000,HYD)
SELECT * FROM Employee
Deleted Magic Table: Whenever you delete the record on that table, that
record will be shown in the DELETED Magic Table Only. To create a trigger to
see the data in the deleted Magic table use the following,
Example:
Create TRIGGER Trigger_Fordeletemagic
ON Employee
FOR DELETE
AS
Begin
SELECT * FROM Deleted
End
Now delete a record in the Employee table to see the data in the Deleted virtual
tables.
Delete from Employee where Eid=12
SELECT * FROM Employee
Explicit Cursors: When user can create a memory location to store the tables
then it is called as Explicit Cursors. These cursors will access the records in the
table record by record or one by one only. Whenever we want to go for record by
record manipulation then explicit cursors will be used.
3)Fetching Data From The Cursor:In this process we access row by row from
cursor.
Syntax: Fetch first/last/next/prior/absolute n/relative n from <cursorname> into
<variables>
4)Closing A Cursor: In this Process,it releases the current result set of the cursor
leaving the datastructure available for reopening.
Syntax:
Close <cursorname>
Deallocate <cursorname>
Create an explicit cursor to display all the records from the table.
while @@FETCH_STATUS=0
begin
print @dno
print @dname
print @loc
fetch next from c1 into @dno,@dname,@loc
end
close c1
deallocate c1
Ex:
Else if @job=Manager
Update employee set sal+=sal*0.05 where eid=@eno
Else
Update employee set sal+=sal*0.03 where eid=@eno
Fetch next from empcur into @eno,@job
End
Close empcur
Deallocate empcur
open c1
fetch next from c1
while @@FETCH_STATUS=0
begin
fetch next from c1
end
close c1
deallocate c1
Ex: Create an explicit cursor to fetch the records from bottom -first (LastFirst)from the table.
Sol: declare c1 cursor scroll for select * from dept
open c1
fetch last from c1
while @@FETCH_STATUS=0
begin
fetch prior from c1
end
close c1
deallocate c1
Ex: Create an explicit cursor on fetching methods.
declare @id int
declare e cursor scroll
for select sid from student
open e
fetch next from e into @id
print @id
fetch last from e into @id
print @id
fetch prior from e into @id
print @id
fetch absolute 3 from e into @id
print @id
fetch relative -1 from e into @id
print @id
fetch first from e into @id
print @id
close e
deallocate e
GRANT: Grant command is used for giving a privilege or permission for a user to
perform operations on the database.
Syntax: GRANT <Privilege Name> on <object name>
To {User} [With GRANT OPTION]
Privilege Name: Used to granted permission to the users for some rights are ALL,
EXECUTE and SELECT.
Object Name: It is the name of database objects like Table, Views and Stored
Procedure etc.
User: Used for to whom an access rights is being granted.
With Grant Option: Allows a user to grant access rights to other users.
There are different types of Normalizations form available in the Database. Lets
see one by one.
1. First Normal Form (1NF): First normal form (1NF) sets the very basic
rules for an organized database:
Create separate tables for each group of related data and identify each row
with a unique column or set of columns (the primary key).
a. Remove repetitive groups
b. Create Primary Key
Example:
Name
John
Bob
Rob
PK
?
ID
1
2
3
4
5
6
State
101
102
201
Country
1
1
2
Name
John
John
John
Bob
Rob
Rob
State
101
101
101
102
201
201
Phone1
Phone2
488-511-3258
781-896-9897
861-856-6987
587-963-8425
425-698-9684
[ Phone Nos ]
?
Country
Phone
1
488-511-3258
1
781-896-9897
1
425-983-9812
1
861-856-6987
2
587-963-8425
2
425-698-9684
Phone3
425-983-9812
ID
1
2
3
Name
John
Bob
Rob
State
101
102
201
Country
PhoneID
1
2
3
4
5
6
ID
1
1
1
2
3
3
Phone
488-511-3258
781-896-9897
425-983-9812
587-963-8425
587-963-8425
425-698-9684
3. Third Normal Form (3NF): Third normal form (3NF) goes one large
step further:
Meet all the requirements of the second normal form.
Remove columns those are not dependent upon the primary key.
Country can be derived from State also so removing country
ID
Name
State
Country
1
2
John
Bob
101
102
1
1
Rob
201
4. Fourth Normal Form (4NF): Finally, fourth normal form (4NF) has
one additional requirement:
Meet all the requirements of the third normal form.
A relation is in 4NF if it has no multi-valued dependencies.
If PK is composed of multiple columns then all non-key attributes should be
derived from FULL PK only. If some non-key attribute can be derived from partial
PK then remove it. The 4NF also known as BCNF NF
ID
1
2
3
Name
John
Bob
Rob
State
101
102
201