0% found this document useful (0 votes)
2 views

MSC Is

Uploaded by

vishvanath sk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

MSC Is

Uploaded by

vishvanath sk
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

1

SQL SERVER
(TSQL,PL/SQL)

NAME : ----------------------------------------------------------

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

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

Mr. V.G.Reddy
International Corporate Trainer and
Project Manager
Mobile No: 9885464910
Email id: [email protected]

1
2

LEGEND OF VGREDDY

Mr. V.G.Reddy
International Corporate Trainer and
Project Manager
Mobile No: 9885464910
Email id: [email protected]
Vgreddy was native of small hamlet village within 50 kms radius of hyderabad.This village is
under the border of ranga reddy dist(east) and nalgonda district(West). Vgreddy was unable to
bear financial problems young age life doing in cultivation in village and studying in government
schools. Vgreddy didn't live with parents from childhood and he was faced lot of problems
economically,educationally.Vgreddy himself prepares food and studies in Government Schools.
Vgreddy living as tenant from schooling to nearly 26 years. From thereafter Vgreddy was fully
settled in hyderabad.Vgreddy was working since 1994-95 as faculty he used to teach home
tutions from school level to engineering subjects in young age life.vgreddy having good
experience in IT industry on client/server,internet,ERP Technologies and Engineering
Subjects.Vgreddy is a teacher,trainer,consultant in field of Information Technology and Bio
Technology.Vgreddy like honest and understanding people and a man of vision, truth and
hardworking. Vgreddy full name is Venkat G. Reddy. Vgreddy having good international
exposure with various countries Clients and Universities like USA, MIDDLE
EAST,AUSTRALIA,UK,IRELAND,CANADA,EUROPE,SOUTH AMERICA AND SOUTH AFRICA.Lakhs
of students are studied with Vgreddy. If you have any doubts you can mail to
[email protected]

Moulding the child right way into the right direction - Vgreddy

2
3

SQL SERVER
 CREATING THE DATABASE TABLES
 STORING INFORMATION INTO THE DATABASE TABLES
 MANIPULATION MEANS CHANGES CAN BE DONE IN THE DATABASE TABLES (OR ) CHANGING
THE EXISTING COLUMN VALUES
 EXTRACTING/RETRIEVAL OF THE INFORMATION FROM THE DATABASE TABLES

CLIENT/SERVER APPLICATIONS

SQL SERVER WAS DEVELOPED BY MICROSOFT CORPORATION

1988 SYBASE CORPORATION


1990 SQL SERVER was developed by Microsoft Corproation

SQL SERVER 4.0


1996
1998
SQL SERVER 4.2 VERSION
SQL SERVER 4.2 VERSION
SQL SERVER 6.0 VERSION
SQL SERVER 6.5 VERSION
SQL SERVER 7.0 VERSION
SQL SERVER 8.0 VERSION /2000
SQL SERVER 9.0 VERSION /2005
SQL SERVER 2008
The 2012 release of Microsoft SQL Server changes how you develop applications for
SQL Server. With this comprehensive resource, SQL Server authority Robert Vieira
presents the fundamentals of database design and SQL concepts, and then shows
you how to apply these concepts using the updated SQL Server. Publishing time and
date with the 2012 release, Beginning Microsoft SQL Server 2012 Programming begins
with a quick overview of database design basics and the SQL query language and then
quickly proceeds to show you how to implement the fundamental concepts of Microsoft
SQL Server 2012.

SQL Server 2012, like its predecessors, is more than a database engine. It is a collection of
components you can implement either separately or as a group to form a scalable, cloud-ready
information platform. In broad terms, this cloud-ready information platform consists of
twocategories:those that help you manage data and those that help you deliver business
intelligence (BI).Accordingly, we divided this book into two parts to focus on the new
capabilities for each of these areas.

3
4

SQL SERVER IS A DATABASE

DBMS STANDS DATABASE MANAGEMENT SYSTEM

database

organized collection of required information


(or)
collection of interrelated data

example:-news paper TOI


HINDU
D.C.

APPLICATIONS OF DATABASE

1) DATA DEFINITION MEANS DEFINING THE DATABASE TABLES (OR) CREATING


THE DATABASE TABLES USING SPECIFIED SQL SERVER DATATYPES

2) DATA CONSTRUCTION MEANS STORING INFORMATION INTO THE DATABASE


TABLE

3) DATA MANIPULATION MEANS CHANGES CAN BE DONE IN THE DATABASE


TABLES OR CHANGING THE EXISTING COLUMN VALUES

4) DATA INTEGRITY MEANS IT ENSURES ACCURACY

5) DATA SECURITY MEANS THERE ARE ONE THOUSAND ROWS AND TWO
HUNDRED COLUMNS ARE THERE IF DELETED PARTICULAR COLUMN VALUE OTHER
COLUMNS CAN'T TO BE DISTURBED. IF DELETED PARTICULAR COLUMN ROW
OTHER ROWS CAN'T TO BE DISTURBED. AND OTHER SECURITY IS FEATURE FOR
OUR CLIENTS WE HAVE TO CREATE OUR OWN USER NAME AND PASSWORD THAT
MEANS AUTHENTICATION FEATURE IS AVAILABLE FOR OUR SQL SERVER
DATABASE

THE COLLECTION OF PROGRAMS ENABLES USERS TO CREATE AND MAINTAIN THE


DATABASE IS CALLED DATABASE MANAGEMENT SYSTEM

DATA MODELS ALSO CALLED DATABASE MODELS

4
5

MODEL IS ALSO CALLED STRUCTURE. THE COLLECTION OF RELATED STRUCTURES


OR MODELS ARE CALLED DATA MODELS.

THERE ARE FIVE TYPES OF DATA MODELS

HDBMS1) HIERARCHICAL MODEL WAS INTRODUCED IN THE INFORMATION


MANAGEMENT SYSTEM (IMS) BY IBM (INTERNATIONAL BUSINESS MACHINES) IN
THE 1968. IT IS IN THE FORM OF HIERARCHY RELATION SHIP.

IT IS ALSO CALLED PARENT CHILD RELATIONSHIP. A PARENT UNIT MAY HAVE


MANY CHILD UNITS , CHILD UNIT IS RESTRICTED TO ONLY ONE PARENT UNIT.

1:MANY RELATIONSHIP

EXAMPLE:- TATA MOTORS , MUL

IT IS A LOW LEVEL DATABASE PROGRAMMING LANGUAGE

HIERARCHY MODEL STRUCTURE IS USEFUL IN LARGE SCALE MANUFACTURING


INDUSTRIES

NDBMS 2) NETWORK MODEL :- IT IS AN IMPROVEMENT ON THE HIERARCHICAL


MODEL. IT IS IN THE FORM OF MULTIPLE PARENT CHILD RELATIONSHIP.

MANY:MANY

A PARENT UNIT MAY HAVE MANY CHILD UNITS , CHILD UNIT CAN ALSO HAVE
DIFFERENT PRODUCTS FROM THE DIFFERENT PARENT UNITS.

EXAMPLE:- REYNOLDS

IT IS A LOW LEVEL DATABASE PROGRAMMING LANGUAGE

NETWORD MODEL STRUCTURE IS USEFUL IN SMALL SCALE MANUFACTURING


INDUSTRIES

RDBMS 3) RELATIONAL MODEL:- 1:1 EXAMPLE:- STUDENT:UNIVERSITY

5
6

High Level Database Programming Language. The Relational Model Principles Were
Laid Down By Dr. E.F.Codd In June 1970, He Was Published A Paper Called "A
Relational Model Of Data For Large Shared Database" . He Was Proposed 12 Rules.
Dr. Ef Codd Says If You Satisfy Atleast 6/12 Then You Can Say Your Product Name
Is Called Rdbms Product.

SQL SERVER 1996 RDBMS PRODUCT

ORACLE,
SQL SERVER
INFORMIX
INGRES
MY SQL
DB2
MS ACCESS

ORDBMS4) OBJECT RELATIONAL MODEL:- TRADIONAL RDBMS INCLUDES OBJECT


RELATIONAL FEATURES SUCH AS ABSTRACT DATATYPES,NESTED TABLES AND
VARRAYS(VARYING ARRAYS)

1:1

IT IS A HIGH LEVEL DATABASE PROGRAMMING LANGUAGE

SSDBMS 5) SEMI STRUCTURAL DATA MODEL:- TRADITIONAL ORDBMS IT


INCLUDES XML FEATURES SUCH AS XML TAGS AND XML DOCUMENTS.

1:1

IT IS A HIGH LEVEL DATABASE PROGRAMMING LANGUAGE

RDBMS

Relational Database Management System It Is An Information System,


Information Contained In The Form Of Tables. A Table Is Holding Information In
Terms Of The Rows And Columns. The Intersection Of Row And Column Must Give
Single Value. The Set Of Columns Are Called Row.

6
7

FEATURES OF RDBMS

1) THE ABILITY TO CREATE MULTIPLE RELATIONS AND STORE DATA INTO THEM.
2) IT IS AN INTERACTIVE QUERY LANGUAGE
3) RETRIEVAL OF INFORMATION STORED IN MORE THAN ONE TABLE

RELATIONAL PRINCIPLES (OR) DR. EF CODD RULES

1) UNIFORM REPRESENTATION DATA


2) GUARANTEED ACCESS
3) DATABASE DESCRIPTION
4) SYSTEMATIC TREATMENT OF NULL VALUES
5) COMPREHENSIVE DATA SUB LANGUAGE
6) HIGH LEVEL UPDATE,INSERT,DELETE
7) VIEW UPDATING
8) PHYSICAL DATA INDEPENDENCE
9) LOGICAL DATA INDEPENDENCE
10) NON SUBVERSION
11) DATA DISTRIBUTION
12) INTEGRITY RULE
DATABASE DESIGN IS ACHIEVED FROM TWO LEVELS

1) ENTITY RELATIONSHIP DIAGRAM


2) NORMALIZATION

1) ENTITY RELATIONSHIP DIAGRAM (ER DIAGRAM)

ER DIAGRAM WAS PROPOSED BY PETER.

ENTITY MEANS IT IS A DATA OBJECT IN A SYSTEM UNIQUELY IDENTIFIABLE BY


INDENTIFIER. IT IS REPRESENTED BY GRAPHICAL NOTATION RECTANGLE SYMBOL.

(OR) THE COLLECTION OF FIELDS (OR) ATTRIBUTES ARE CALLED ENTITY.

ATTRIBUTE MEANS IT DESCRIBES ACCORDING TO AN ENTITY. IT IS


REPRESENTED BY GRAPHICAL NOTATION ELLIPSE SYMBOL

RELATIONSHIP:- IT RELATES BETWEEN TWO ENTITIES UNIQUELY IDENTIFIABLE


BY IDENTIFIER. IT IS REPRESENTED BY GRAPHICAL NOTATION RHOMBUS SYMBOL.

REFINEMENT OF ER DIAGRAM

7
8

1) THE TABLE RELATIONSHIP SHOULD HAVE 1:MANY, 1:1 RELATIONSHIP

2) IF ANY MANY:MANY RELATIONSHIP IS THERE BREAK ALL THE MANY:MANY


RELATIONSHIP AND CONVERT INTO 1:MANY,1:1 RELATIONSHIP INTRODUCING
ADDITIONAL ENTITY

3) A GOOD ER DIAGRAM ALWAYS HAS 1:MANY RELATIONSHIP

NORMALIZATION

The Goal Of Normalization Is To Generate Set Of Tables, Reducing The Unnecessary


Data And Retrieval Of The Information Effectively And Efficiently. In
Unnormalization Structure Insertion/Updation/Deletion Is Not Allowed.

1) REFINEMENT OF ER DIAGRAM
2) NORMALIZATION
i) FIRST NORMAL FORM (1NF)
ii) SECOND NORMAL FORM (2NF)
iii) THIRD NORMAL FORM (3NF)
i) FIRST NORMAL FORM (1NF):- YOU HAVE TO REMOVE THE REPEATING FIELDS OF
A TABLE WHICH IS UNNECESSARY DATA.

ii) SECOND NORMAL FORM (2NF):- YOU HAVE TO IDENTIFY THE TABLENAMES AND
FIELDS. FIELD SHOULD BE ACCORDING TO THE TABLE THEN YOU HAVE TO
SPECIFY NAME OF THE TABLE.

iii) THIRD NORMAL FORM (3NF):- YOU HAVE TO IDENTIFY THE KEYS, FIELDS OF A
TABLE WHICH IS MASTER TABLE AND CHILD TABLE. PRIMARY KEY COLUMN TABLE
IS CALLED MASTER TABLE. FOREIGN KEY COLUMN TABLE IS CALLED CHILD TABLE.
CHILD TABLE COLUMN VALUE IS DEPENDENT ON THE MASTER TABLE.

TSQL STANDS FOR TRANSACT STRUCURED QUERY LANGUAGE

PRONOUNCIATION IS SQL IS SEQUEL MEANS STRUCTURED ENGLISH QUERY


LANGUAGE

SQL WAS INVENTED AND DEVELOPED BY IBM (INTERNATIONAL BUSINESS


MACHINES) IN THE 1970T

ANSI (AMERICAN NATIONAL STANDARD INSTITUTE) ADOPTED SQL IN 1986

ISO

8
9

FEATURES OF TSQL

NON PROCEDURAL LANGUAGE

UNIFIED LANGUAGE

IT IS NOT A CASE SENSITIVE QUERY LANGUAGE

COMMON LANGUAGE FOR ALL RELATIONAL DATABASE

THIS LANGUAGE IS USED TO ACCESS WITHIN THE SQL SERVER DATABASE

CREATING THE DATABASE TABLEUS

STORING INFORMATION INTO THE DATABASE TABLES

MANIPULATION MEANS CHANGES CAN BE DONE IN THE DATABASE


TABLES (OR) CHANGING THE EXISTING COLUMN VALUES

EXTRACTING/RETRIEVAL INFORMATION FROM THE DATABASE TABLES

TSQL (TRANSACT SQL)

TSQL LANGUAGE CLASSIFIED INTO 5 SUB LANGUAGES SUCH AS

1) DATA DEFINITION LANGUAGE (DDL):- CREATE ALTER DROP


2) DATA MANIPULATION LANGUAGE (DML):- INSERT UPDATE DELETE
3) DATA RETRIEVAL LANGUAGE (DRL):- SELECT
4) DATA CONTROL LANGUAGE (DCL):- GRANT,REVOKE
5) TRANSACTION CONTROL LANGUAGE (TCL):- ROLLBACK COMMIT

CREATE

IS USEFUL FOR CREATING THE DATABASE TABLES. TABLE NAME MUST BE


UNIQUE IN THE DATABASE. THE COLUMN NAME MUST BE UNIQUE IN THE
DATABASE TABLE. THE COLUMN NAMES MUST BE SPECIFIED ALONG WITH SQL
SERVER DATATYPES. THE TABLE NAME MUST START WITH LETTER OF ALPHABET.
THE LENGTH OF THE TABLE NAME IS 1 - 30 CHARACTERS.

9
10

HOW TO CREATE THE DATABASE TABLES

SYNTAX:-

CREATE TABLE <TABLENAME>

(<COLUMNNAME> <DATATYPE><SIZE>,

<COLUMNNAME> <DATATYPE><SIZE>,

-------------------------------------- )

SP_HELP IS USED TO DESCRIBE THE DATABASE STRUCTURE

SP_HELP DEPT

SQL SERVER DATATYPES

Data Type From To Bytes


EXACT NUMERICS
Bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807 8
Int -2,147,483,648 2,147,483,647 4
Smallint -32768 32767 2
Tinyint 0 255 1
Bit 0 1 1
Decimal -1038 +1 1038 -1 5 to 17
1-9 5 bytes
10-19 9 bytes
20-28 13 bytes
29-38 17 bytes
38 38
Numeric -10 +1 10 -1 Same As Decimal
Money -922,337,203,685,477.5808 -922,337,203,685,477.5807 8
Smallmoney -214,748.3648 +214,748.3647 4
numeric and decimal are Fixed precision and scale data types and are functionally equivalent.
APPROXIMATE NUMERICS
Float -1.79E + 308 1.79E + 308 4 bytes if P is 1 – 24
8 bytes if P is 25 - 53
Real -3.40E + 38 3.40E + 38 4
DATE AND TIME
Date Jan 1st 0001 Dec 31st 9999 3 [New 2008]

10
11

DateTime Jan 1st 1753 / 00:00:00 Dec 31st 9999 / 8


23:59:59.997
DateTime2 Jan 1st 0001 / 00:00:00 Dec 31st 9999 / 6 – 8 [New 2008]
23:59:59.997
SmallDateTime Jan 1st 1900 / 00:00:00 June 6th 2079 / 23:59:59 4
Time 00:00:00.0000000 23:59:59.9999999 5 [New 2008]
st st
DateTimeOffset Jan 1 0001 / 00:00:00 Dec 31 9999 / 23:59:59 10 [New 2008]
Defines a date that is combined with a time of a day that has time zone awareness and is based on a 24-
hour clock.
CHARACTER STRINGS (each char occupies 1 byte)
Char Fixed Length Non-Unicode Char Data With a Maximum of 8000 characters
Varchar Variable Length Non-Unicode Data With a Maximum of 8000 characters
Varchar(max) Variable Length Non-Unicode Data With a Maximum of 231 characters [New 2005]
Text Variable Length Non-Unicode Data With a Maximum of 2,147,483,647 characters
UNICODE CHARACTER STRINGS (each char occupies 2 bytes)
Nchar Fixed-length Unicode data with a maximum of 4,000 characters
Nvarchar Variable-length Unicode data with a maximum of 4,000 characters
Nvarchar(max) Variable-length Unicode data with a maximum of 230 characters [New 2005]
Ntext Variable-length Unicode data with a maximum of 1,073,741,823 characters
BINARY STRINGS
Binary Fixed-length binary data with a maximum of 8,000 bytes
Varbinary Variable-length binary data with a maximum of 8,000 bytes
Varbinary(max) Variable-length binary data with a maximum of 231 bytes [New 2005]
Image Variable-length binary data with a maximum of 2,147,483,647 bytes
OTHER DATA TYPES
SQL_Variant Stores values of various SQL Server-supported data types, except text, ntext, and
timestamp.
Timestamp Stores a database-wide unique number that gets updated every time a row gets
updated.
Uniqueidentifier Stores a globally unique identifier (GUID).
Xml Stores XML data. You can store xml instances in a column or a variable
Cursor A reference to a cursor.
Table Stores a result set for later processing.
Hierarchyid The hierarchyid data type is a variable length, system data type. Use hierarchyid to
represent position in a hierarchy. A column of type hierarchyid does not
automatically represent a tree. It is up to the application to generate and assign
hierarchyid values in such a way that the desired relationship between rows is
reflected in the values.
Geometry The geometry data type (planar) supported by SQL Server conforms to the Open
Geospatial Consortium (OGC)
Geography The geography spatial data type, geography, is implemented as a .NET common
language runtime (CLR) data type in SQL Server. This type represents data in a
round-earth coordinate system. The SQL Server geography data type stores
ellipsoidal (round-earth) data, such as GPS latitude and longitude coordinates.
FileStream FILESTREAM integrates the SQL Server Database Engine with an NTFS file system
by storing varbinary(max) binary large object (BLOB) data as files on the file

11
12

system.

DEPT

EMP PREDEFINED TABLES

SELECT MEANS IT INSTRUCTS THE DATABASE TO RETRIEVE/EXTRACTING


INFORMATION FROM THE DATABASE TABLE.

SYNTAX:- SELECT * FROM <TABLENAME>;

* REPRESENTS ALL COLUMNS

SELECT * FROM DEPT

SELECT DEPTNO,DNAME FROM DEPT

ALTER

TO ADD NEW COLUMN TO THE EXISTING DATABASE TABLE


TO MODIFY THE DATATYPE, SIZE OF THE COLUMND
TO DROP THE COLUMN FROM THE DATABASE TABLE
TO ADD CONSTRAINT TO THE COLUMN
TO DROP CONSTRAINT FROM THE COLUMN

HOW TO ADD NEW COLUMN TO THE EXISTING DATABASE TABLE

SYNTAX:-

ALTER TABLE <TABLENAME> ADD(<COLUMN NAME> <DATATYPE>);

EXAMPLE:-

ALTER TABLE STUDENT ADD SADDRESS VARCHAR(20)

12
13

HOW TO MODIFY THE COLUMN DATATYPE SIZE

SYNTAX

ALTER TABLE <TABLENAME> ALTER COLUMN <COLUMNNAME> <DATATYPE>,,,,,;

ALTER TABLE STUDENT ALTER COLUMN SNAME VARCHAR(30)

HOW TO DROP THE COLUMNS FROM THE DATABASE TABLE

SYNTAX

ALTER TABLE <TABLENAME> DROP COLUMN


<COLUMNNAME1>,<COLUMNNAME2>,;

ALTER TABLE STUDENT DROP COLUMN SADDRESS

HOW TO CHANGE NAME OF THE COLUMN

SYNTAX:-

SP_RENAME '<TABLENAME>.<OLDCOLUMNNAME>','<NEW COLUMNNAME>'

SP_RENAME 'STUDENT.SNO','STUDENTID'

DROP

IS USED TO DROP A TABLE SQL SERVERDATABASE

SYNTAX:-

DROP TABLE <TABLENAME>,<TABLENAME>;

DROP TABLE STUDENT

INSERT:- IS USED INSERTING ROWS INTO THE DATABASE TABLE. CHARACTER


DATATYPE COLUMN VALUES MUST BE ENCLOSED WITHIN SINGLE QUOTES.

13
14

THERE ARE TWO TYPES OF INSERT ROWS INTO THE DATABASE TABLE

1) INSERTING ALL COLUMN VALUES

SYNTAX:-

INSERT INTO <TABLENAME> VALUES (<LIST OF COLUMN VALUES>)

EXAMPLE:-

INSERT INTO DEPT VALUES(45,'SOFTWARE','HYD')

UPDATE IS USED UPDATING OR CHANGING THE EXISTING COLUMN VALUES IN


THE DATABASE TABLE.

SYNTAX:-

UPDATE <TABLENAME> SET <COLUMNNAME>=<VALUE> WHERE <CONDITION>

EXAMPLE:-

UPDATE DEPT SET DNAME='SAPABAP' WHERE DEPTNO=50

DELETE :- IS USED DELETING ROWS FROM THE DATABASE TABLE. WHERE


CLAUSE IS USED TO SPECIFY THE CONDITION. WHERE CONDITION IS USED

SYNTAX:-

DELETE FROM <TABLENAME> WHERE <CONDITION>;

EXAMPLE:-

DELETE FROM DEPT WHERE DEPTNO=55

OPERATORS

OPERATOR IS A SYMBOL TO PERFORM MATHEMATICAL CALCULATIONS. (OR) TO


PERFORM AN ACTION.

OPERATORS ARE CLASSIFIED INTO 4 WAYS

1) ARITHMETIC OPERATORS

14
15

+ =5+4=9

- =5-4=1

* =5*4=20

/ =5/2=2.5

% =28%4=0

2) COMPARISON OPERATORS ARE USED TO COMPARE ARE EXPRESSION WITH


ANOTHER EXPRESSION

>

>=

<

<=

<> OR !=

= (ASSIGNMENT OPERATOR IN SQL SERVER) A=20

3) LOGICAL OPERATORS

AND

OR

NOT

4) SPECIAL OPERATORS

IN MEANS SET OF VALUES

BETWEEN MEANS RANGE OF VALUES

IS NULL MEANS CHECKING FOR NULL VALUES

LIKE MEANS MATCHING CHARACTER PATTERN

% REPRESENTS ANY NO OF CHARACTERS

15
16

_ (underscore) represents single character

DISPLAY THE DEPARTMENT DETAILS

SELECT * FROM DEPT

DISPLAY THE EMPLOYEE DETAILS

SELECT * FROM EMP

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE BELONGS TO THE


DEPTNO 20

SELECT * FROM EMP WHERE DEPTNO=20

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE NOT BELONGS TO


THE DEPTNO=10

SELECT * FROM EMP WHERE DEPTNO<>10

(OR)

SELECT * FROM EMP WHERE DEPTNO!=10

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS MORE


THAN 2500

16
17

SELECT * FROM EMP WHERE SAL>2500

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS 2000


AND LESS THAN 2000

SELECT * FROM EMP WHERE SAL<=2000

DISPLAY THE DESIGNATIONS FROM EMPLOYEE TABLE WHOSE JOB IS MANAGER


AND CLERK

SELECT JOB FROM EMP WHERE JOB='MANAGER' AND JOB='CLERK'

DISPLAY THE DESIGNATIONS FROM EMPLOYEE TABLE WHOSE JOB IS MANAGER


OR CLERK

SELECT JOB FROM EMP WHERE JOB='MANAGER' OR JOB='CLERK'

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE NOT BELONGS TO


THE DEPTNO 10,30 AND 40

SELECT * FROM EMP WHERE DEPTNO NOT IN (10,30,40)

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE EMPNOS ARE


7566,7788,7839

SELECT * FROM EMP WHERE EMPNO IN (7566,7788,7839)

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SAL BETWEEN


2000 AND 3000

17
18

SELECT * FROM EMP WHERE SAL BETWEEN 2000 AND 3000

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE COMMISSION IS


NULL

SELECT * FROM EMP WHERE COMM IS NULL

DISPLAY THE EMPLOYEE NAME OF EMPLOYEE TABLE WHOSE ENAME STARTING


WITH S

SELECT ENAME FROM EMP WHERE ENAME LIKE 'S%'

DISPLAY THE EMPLOYEE NAME OF EMPLOYEE TABLE WHOSE ENAME ENDING WITH
S

SELECT ENAME FROM EMP WHERE ENAME LIKE '%S'

DISPLAY THE EMPLOYEE NAME OF EMPLOYEE TABLE WHOSE ENAME 3RD


CHARACTER AS A

SELECT ENAME FROM EMP WHERE ENAME LIKE '__A%'

TRUNCATE IS USED DELETING ALL THE ROWS FROM THE DATABASE TABLE AT A
TIME. WHERE CLAUSE IS NOT USED.

YOU CAN'T ROLLBACK

SYNTAX:-

TRUNCATE TABLE <TABLENAME>;

EXAMPLE:-

TRUNCATE TABLE STUDENT

18
19

ORDER BY CLAUSE IS USED TO DISPLAY THE ROWS COLUMN WISE ASCENDING


AND DESCENDING ORDER

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS IN THE


FORM OF ASCENDING ORDER

SELECT * FROM EMP ORDER BY SAL

DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS IN THE


FORM OF DESCENDING ORDER

SELECT * FROM EMP ORDER BY SAL DESC

FUNCTIONS ALSO CALLED BUILT IN FUNCTIONS

FUNCTIONS ARE USED TO COMPUTE THE VALUES. FUNCTIONS ARE CLASSIFIED


INTO 5 WAYS

1) AGGREGATE FUNCTIONS 2) CHARACTER FUNCTIONS 3) DATE FUNCTIONS 4)


ARITHMETIC FUNCTIONS 5) GENERAL FUNCTIONS

1) AGGREGATE FUNCTIONS ALSO CALLED GROUP FUNCTIONS

ARE USED TO PRODUCE SINGLE RESULT COLUMN OF A VALUE. THE SET OF


ROWS INTO SINGLE ROW (OR) GROUP

DISPLAY THE TOTAL SALARY FROM EMPLOYEE TABLE

SELECT SUM(SAL) AS TOTAL FROM EMP

DISPLAY THE DEPTNO, TOTAL SALARY FROM EMPLOYEE TABLE DEPARTMENT WISE

19
20

SELECT DEPTNO AS DNO,SUM(SAL) AS TOTSAL FROM EMP GROUP BY DEPTNO

DISPLAY THE AVERAGE SALARY FROM EMPLOYEE TABLE

SELECT AVG(SAL) AS AVERAGE FROM EMP

DISPLAY THE MAX SALARY FROM EMPLOYEE TABLE

SELECT MAX(SAL) AS MAXIMUM FROM EMP

DISPLAY THE MINIMUM SALARY FROM EMPLOYEE TABLE

SELECT MIN(SAL) AS MINIMUM FROM EMP

DISPLAY THE NO OF ROWS OF EMPLOYEE TABLE

SELECT COUNT(*) AS COUNT1 FROM EMP

DISPLAY THE JOB, TOTAL AVERAGE MAXM MINM SALARY NO OF ROWS FROM
EMPLOYEE TABLE JOB WISE

SELECT JOB AS JOB1,SUM(SAL) AS TOTSAL,AVG(SAL) AS AVERAGE,MAX(SAL) AS


MAXM,MIN(SAL) AS MINM, COUNT(*) AS COUNT1 FROM EMP GROUP BY JOB

HAVING CLAUSE MUST BE SPECIFIED WITH THE GROUP BY CLAUSE

DISPLAY THE JOB, TOTAL AVERAGE MAXM MINM SALARY NO OF ROWS FROM
EMPLOYEE TABLE JOB WISE

HAVING AVERAGE SALARY IS MORE THAN 300

SELECT JOB AS JOB1,SUM(SAL) AS TOTSAL,AVG(SAL) AS AVERAGE,MAX(SAL) AS


MAXM,MIN(SAL) AS MINM, COUNT(*) AS COUNT1 FROM EMP GROUP BY JOB
HAVING AVG(SAL)>3000

2) CHARACTER FUNCTIONS ARE USED TO APPLY ON CHARACTER DATA TYPE


COLUMNS

20
21

ALSO CALLED STRING FUNCTIONS

ASCII STANDS FOR AMERICAN STANDARD CODE FOR INFORMATION


INTERCHANGE

65 - 90 A - Z UPPERCASE LETTERS

97 - 122 a - z LOWERCASE LETTERS

SELECT ASCII('A')

SELECT ASCII('b')

char(n) it returns the character for given ascii value

SELECT CHAR(66)

SELECT CHAR(98)

LOWER(<STRING>) IT CONVERTS THE UPPERCASE INTO LOWERCASE LETTERS

SELECT LOWER('HELLOWORLD')

UPPER(<STRING>) IT CONVERTS THE LOWERCASE INTO UPPERCASE LETTERS

SELECT UPPER('helloworld')

DISPLAY EMPLOYEE NAME AND CONVERT EMPLOYEE NAME INTO LOWERCASE


LETTERS

SELECT ENAME,LOWER(ENAME) AS LOWERENAME FROM EMP

DISPLAY EMPLOYEE NAME AND CONVERT EMPLOYEE NAME INTO UPPERCASE


LETTERS

SELECT ENAME,UPPER(ENAME) AS UPPERENAME FROM EMP

LEN(STRING) IT RETURNS THE LENGTH OF GIVEN STRING

SELECT LEN('HELLO') AS LENGTH

SELECT ENAME,LEN(ENAME) AS LENGTH FROM EMP

REVERSE(STRING) IT WILL REVERSE OF THE GIVEN STRING

SELECT REVERSE('BHARGAVA') AS REVERSESTRING

21
22

SELECT ENAME,REVERSE(ENAME) AS REVENAME FROM EMP

REPLACE(<STRING/COLUMNNAME>,'SEARCHINGSTRING','REPLACINGSTRING')

IT WILL REPLACE A SUB STRING IN A STRING WITH A GIVEN STRING

SELECT REPLACE('HELLOWORLD','LOW','BHARGAVA') AS REPLACESTRING

SELECT ENAME,REPLACE(ENAME,'MIT','VGREDDY') AS REPLACEENAME FROM EMP

SUBSTRING(STRING,'STARTINGPOSITION','NO OF CHARACTERS REQUIRED')

IT WILL EXTRACT A SUBSTRING FLOW MAIN STRING

SELECT SUBSTRING('VGREDDYS',2,3) AS SUBSTR1

SELECT ENAME,SUBSTRING(ENAME,2,3) AS SUBSTRENAME FROM EMP

3) DATE FUNCTIONS ARE USED TO APPLY ON DATE AND TIME FUNCTIONS

GETDATE() IT RETURNS THE CURRENT DATE AND TIME

SELECT GETDATE() AS GETDATE1

DATEADD(DATEPART,NUMBER,DATE) IT RETURNS THE DATE ACCORDING TO DATE


PART

YOU CAN ADD DAY MONTH YEAR

YY YEAR

MM MONTH

DD DAY

SELECT DATEADD(MM,1,'2013/01/26') AS DATEADD1

SELECT DATEADD(DAY,1,'2013/01/26') AS DATEADD1

22
23

DATEDIFF(DATEPART,DATE1,DATE2) IT RETURNS THE DIFFERENCE BETWEEN THE


DATES ACCORDING TO THE DATE PART

SELECT DATEDIFF(YEAR,'2012/01/26','2013/01/26') AS DATEDIFFERNCE

4) ARITHMETIC FUNCTIONS are useful in mathematical functions

SELECT ABS(-15.87) AS ABSOLUTE

SELECT ABS(15.87) AS ABSOLUTE1

POWER(M,N) IT RETURNS M TO THE POWER OF N

SELECT POWER(5,3) AS POWER1

SELECT POWER(2,3) AS POWER2

SQRT(N) IT RETURNS THE SQUARE ROOT OF THE GIVEN NUMBER N

SELECT SQRT(3) AS SQUARE1

SELECT SQRT(2) AS SQUARE2

ROUND(M,N) IT WILL ROUND THE VALUE OF M TO NEAREST WHOLE NUMBER OR


IT WILL ROUND

SELECT ROUND(15.143) AS ROUND1

CEILING(N) IT RETURNS THE SMALLEST INTEGER GREATER THAN N

SELECT CEILING(15.13) AS CEIL1

FLOOR(N) IT RETURNS THE LARGEST INTEGER LESS THAN N

SELECT FLOOR(15.13) AS FLOOR1

5) GENERAL FUNCTIONS

DISPLAY THE EMPNO,SAL ,SALARY AS PER MONTH AND SALARY PER YEAR FOR ALL
EMPLOYEES

SELECT EMPNO,SAL AS 'SALARY PER MONTH',SAL*12 AS 'SAL PER YEAR' FROM


EMP

23
24

SELECT EMPNO,SAL,SAL*.45 HRA, SAL*.35 DA,SAL*.15 PF,


(SAL+SAL*.45+SAL*.35)-SAL*.15 GROSS FROM EMP

JOINS
ARE USED TO QUERY DATA FROM MORE THAN ONE TABLE.

THERE ARE FIVE TYPES OF JOINING METHODS

1) EQUI JOINS 2)OUTER JOINS 3) SELF JOINS 4) CROSS JOINS 5) SET


OPERATORS

1) EQUI JOINS ALSO CALLED INNER JOINS

THE RELATIONSHIP BETWEEN MASTER TABLE AND CHILD TABLE IS CALLED EQUI
JOINS. MASTER TABLE COLUMN VALUES MUST MATCH CORRESPONDING COLUMN
VALUES IN THE CHILD TABLE AND BOTH THE TABLES MATCHING COLUMN VALUES.

SYNTAX:-

MASTERTABLE.PRIMARY KEY COLUMN=CHILD TABLE.FOREIGN KEY COLUMN

DISPLAY THE DEPTNO,DNAME,EMPNO,ENAME,SAL,DEPTNO FROM DEPT,EMP TABLE


USING EQUI JOINS

SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT,EMP WHERE DEPT.DEPTNO=EMP.DEPTNO;

USING ORDER BY DEPTNO

SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT,EMP

WHERE DEPT.DEPTNO=EMP.DEPTNO ORDER BY DEPT.DEPTNO

2) OUTER JOINS ARE USED TO DISPLAY ROWS WHICH DO NOT MATCH FROM
ONE TABLE TO OTHER TABLE.

THERE ARE THREE TYPES OF OUTER JINS

i) LEFT OUTER JOIN:- MASTER TABLE SIDE ROWS ARE EXISTING WHICH DO
NOT MATCH CORRESPONDING ROWS OR COLUMN VALUES IN THE CHILD TABLE
AND BOTH THE TABLES MATCHING COLUMN VALUES.

24
25

SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT LEFT OUTER JOIN EMP ON DEPT.DEPTNO=EMP.DEPTNO ORDER BY
DEPT.DEPTNO

ii) RIGHT OUTER JOIN:- CHILD TABLE SIDE ROWS ARE EXISTING WHICH DO
NOT MATCH CORRESPONDING ROWS OR COLUMN VALUES IN THE MASTER TABLE
AND BOTH THE TABLES MATCHING COLUMN VALUES.

SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT RIGHT OUTER JOIN EMP

ON DEPT.DEPTNO=EMP.DEPTNO ORDER BY DEPT.DEPTNO

iii) FULL OUTER JOIN:- BOTH THE TABLES MATCHING ROWS OR COLUMN
VALUES AND BOTH THE WHICH ARE INOT MATCHING COLUMN VALUES. IT IS A
COMBINATION OF EQUI JOIN ,LEFT OUTER AND RIGHT OUTER JOIN.

SELECT DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.JOB,EMP.SAL,EMP.DEPTNO
FROM DEPT FULL OUTER JOIN EMP

ON DEPT.DEPTNO=EMP.DEPTNO ORDER BY DEPT.DEPTNO

3) SELF JOINS :- JOINING THE TABLE TO ITSELF. JOIN CONDITION IS USED.

DISPLAY EMPNOS,MGRNO ,JOBS FROM EMPLOYEE TABLE WHO IS REPORTING TO


WHOM

SELECT WORKER.EMPNO,MANAGER.EMPNO,WORKER.JOB,MANAGER.JOB FROM


EMP WORKER,EMP MANAGER

WHERE MANAGER.EMPNO=WORKER.MGR

4) CROSS JOINS:- join condition is not used. all the rows in the first table
are joined to all the rows in the second table.

25
26

SELECT * FROM EMP,DEPT

5) SET OPERATORS :- ONE OR MORE QUERIES PRODUCING SINGLE RESULT


SAME DATATYPE.

i) UNION ALL :- THE ROWS OF THE FIRST QUERY + THE ROWS OF THE SECOND
QUERY

SELECT JOB FROM EMP WHERE DEPTNO=20


UNION ALL
SELECT JOB FROM EMP WHERE DEPTNO=30

ii) UNION:- THE ROWS OF THE FIRST QUERY + THE ROWS OF THE SECOND QUERY
eliminates or deletes the repeating column values

SELECT JOB FROM EMP WHERE DEPTNO=20

UNION

SELECT JOB FROM EMP WHERE DEPTNO=30

iii) INTERSECT :- COMMON ROWS OF THE TWO QUERIES

SELECT JOB FROM EMP WHERE DEPTNO=20


INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=30

iv) EXCEPT :- ROWS UNIQUE TO THE FIRST QUERY

SELECT JOB FROM EMP WHERE DEPTNO=20


EXCEPT
SELECT JOB FROM EMP WHERE DEPTNO=30

mgr number(5) constraint fkmgr references emp(empno),

SUB QUERIES
QUERY WITHIN A QUERY IS CALLED SUB QUERY

SUB QUERIES ARE CLASSIFIED INTO TWO WAYS

26
27

i) single row subquery :- queries that executes only one row from the in.ner
select statement is called single row sub query. single row comparison operators
are used in single row sub query.

ii) multiple row subquery :- queries that executes more than one row from the
inner select statement is called multiple row sub query. multiple row comparison
operators are used in multiple row sub query.

comparison operators are classified into two ways

i) single row comparison operator < <= > >= = != (or) <>

ii) multiple row comparison operators in any all exists

i) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS MORE


THAN THE SALARY OF EMPNO 7566

SELECT * FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE EMPNO=7566)

ii) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS MORE
THAN all average salaries of employee table DEPARTMENTWISE

SELECT * FROM EMP WHERE SAL>ALL(SELECT AVG(SAL) FROM EMP GROUP BY


DEPTNO)

iii) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE MAX SALARIES
OF EMPLOYEE table DEPARTMENTWISE

SELECT * FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP GROUP BY
DEPTNO)

iv) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS LESS
THAN ANY HIGHEST SALARY OF THE CLERK

SELECT * FROM EMP WHERE SAL<ANY (SELECT SAL FROM EMP WHERE
JOB='CLERK')

27
28

v) DISPLAY THE EMPLOYEE DETAILS OF EMPLOYEE TABLE WHOSE SALARY IS


MORE THAN ANY LOWEST SALARY OF THE CLERK

SELECT * FROM EMP WHERE SAL>ANY (SELECT SAL FROM EMP WHERE
JOB='CLERK')

CORELATED SUB QUERY:- PARENT QUERY VALUES MUST CHECK IN THE CHILD
QUERY THEN IT EXECUTES THE PARENT QUERY

DISPLAY THE DEPT DETAILS EXISTS IN THE EMPLOYEE TABLE

SELECT * FROM DEPT WHERE EXISTS (SELECT * FROM EMP WHERE


DEPT.DEPTNO=EMP.DEPTNO)

DISPLAY THE TOP 2 EARNERS (OR) 2 HIGHEST SALARIES FROM EMPLOYEE TABLE

SELECT * FROM EMP WHERE 2>(SELECT COUNT(*) FROM EMP E WHERE


E.SAL>EMP.SAL)

VIEWS

VIEW IS DERIVED FROM THE DATABASE TABLE. VIEW IS A VIRTUAL TABLE. IF


YOU DO SOME CHANGES IN THE VIEW IT WILL CHANGE IN THE VIEW AND
DATABASE TABLE ALSO CHANGED.

THERE ARE TWO TYPES OF VIEWS

1) SIMPLEX VIEWS

IT IS DERIVED FROM ONLY ONE TABLE

2) COMPLEX VIEWS

IT IS DERIVED MORE THAN ONE TABLE. JOIN CONDITION IS USED. DML


STATEMENTS BUT NOT ALWAYS.

HOW TO CREATE SIMPLEX VIEW

SYNTAX:-

CREATE VIEW <VIEWNAME> AS SELECT <COLUMNNAMES> FROM <TABLENAME>


WHERE <CONDITION>

EXAMPLE:-

CREATE VIEW V1 AS SELECT * FROM EMP WHERE DEPTNO=20

28
29

SELECT * FROM V1

UPDATE V1 SET SAL=987 WHERE EMPNO=7369

SELECT * FROM V1

SELECT * FROM EMP

DROP VIEW V1

HOW TO CREATE COMPLEX VIEW

SYNTAX:-

CREATE VIEW <VIEWNAME> AS SELECT <COLUMNNAMES> FROM <TABLENAME>


WHERE <JOIN CONDITION>

EXAMPLE:-

CREATE VIEW V2 AS SELECT


DEPT.DEPTNO,DEPT.DNAME,EMP.EMPNO,EMP.ENAME,EMP.SAL FROM DEPT,EMP
WHERE DEPT.DEPTNO=EMP.DEPTNO

SELECT * FROM V2

UPDATE V2 SET SAL=987 WHERE EMPNO=7369

SELECT * FROM V1

SELECT * FROM EMP

DROP VIEW V1

SYNONYMS:- IS SIMILAR TO THE DATABASE TABLE. IT IS DERIVED FROM THE


DATABASE TABLE. IF YOU DO SOME CHANGES IN THE SYNONYM IT WILL CHANGE
IN THE SYNONYM AND DATABASE TABLE ALSO CHANGED.

SYNTAX:-

CREATE SYNONYM <SYNONYMNAME> FOR <TABLENAME>;

EXAMPLE:-

CREATE SYONYM BHARGAV FOR EMP

SELECT * FROM BHARGAV

SELECT *FROM EMP

29
30

UPDATE EMP SET SAL=4352 WHERE EMPNO=777

SELECT * FROM EMP

HOW TO DROP THE SYNONYM

SYNTAX:-

DROP SYNONYM <SYNONYMNAME>;

DROP SYNONYM BHARGAV

INDEXES

ARE USED TO QUERY FAST ACCESS. SEARCHING, RETRIEVAL INFORMATION


EFFECTIVELY AND EFFICIENTLY. INDEXES ARE PREFERABLE IF THE TABLE IS TOO
LARGE. INDEXES ARE USED TO PERFORMANCE OF THE QUERY

INDEXES CANNOT BE CREATED THE FOLLOWING COLUMNSB WHERE CLAUSE

2) COLUMNS CONTAINING THE DUPLICATE AND NULL VALUES

3) COLUMNS CONTAINING IMAGES, BINARY INFO, AND TEXT INFORMATION

TYPES OF INDEXES

i) CLUSTERED INDEXES ii) NON CLUSTERED INDEX

i) CLUSTERED INDEX:- ONLY ONE CLUSTERED INDEX IS ADDED FOR A TABLE. THE
ORDER OF VALUES IN A TABLE. ORDER OF VALUES IN INDEX IS ALSO SAME WHEN
CLUSTERED INDEX IS CREATED ON TABLE . DATA IS ARRANGED IN ASCENDING

ORDER CLUSTERED INDEX WILL OCCUPY 5% OF THE TABLE.

HOW TO CREATE CLUSTERED INDEX

SYNTAX:-

CREATE CLUSTERED INDEX <INDEXNAME> ON


<TABLENAME>(<COLUMNNAME>)

EXAMPLE:-

IF ALREADY PRIMARY KEY IS THERE ON THE TABLE YOU CAN'T CREATE


CLUSTERED INDEX

CREATE CLUSTERED INDEX VENKAT6 ON EMP(JOB)

30
31

SELECT * FROM EMP WHERE JOB='MANAGER'

UNIQUE INDEX:- AN INDEX WITH UNIQUE CONSTRAINT IT WILL NOT ALLOW


DUPLICATE VALUES. THIS IS SIMILAR TO NON CLUSTERED INDEX.DUPLICATE
VALUES SHOULD NOT BE THERE IN THE COLUMN.

CREATE UNIQUE INDEX VENKAT1 ON EMP(JOB)

HOW TO CREATE SIMPLE INDEX

CREATE INDEX VENKAT2 ON EMP(JOB)

HOW TO DROP THE INDEX

EXAMPLE

DROP INDEX VENKAT2 ON EMP

HOW TO CREATE NON CLUSTERED INDEX

CLUSTER INDEX IS FASTER THAN NON CLUSTERED INDEX

SYNTAX

CREATE NONCLUSTERED INDEX <INDEXNAME> ON <TABLENAME>

CREATE NONCLUSTERED INDEX VENKAT7 ON EMP(JOB,SAL)

SELECT * FROM EMP WHERE JOB='MANAGER'

TCL(ROLLBACK,COMMIT)

ROLLBACK MEANS UNDO

BEGIN TRAN

UPDATE EMP SET SAL=3988 WHERE EMPNO=7698

SELECT * FROM EMP WHERE EMPNO=7698

ROLLBACK TRAN

SELECT * FROM EMP WHERE EMPNO=7698

COMMIT MEANS IT MAKES TRANSACTION PERMANENT TO THE DATABASE TABLE.


YOU CAN'T ROLLBACK.

IMPLICIT TRANSACTION:- WHEN SET IMPLICIT TRANSACTIONS IS AN


AUTOMATICALLY AFTER THAT THE DML OPERATIONS PERFORMED BY USER CAN BE
COMMIT OR ROLLBACK.

31
32

SET IMPLICIT_TRANSACTIONS ON

UPDATE EMP SET SAL=6544 WHERE EMPNO=7698

COMMIT

SAVE POINTS

SAVE POINTS ARE LIKE PAPER MARKS USED TO MARK THE TRANSACTIONS.

SYNTAX:- SAVE TRAN <TRANSACTION NAME>

YOU CAN CREATE SAVE POINTS FOR EACH TRANSACTION LATER YOU CAN
ROLLBACK ONLY ONE PARTICULAR TRASANCTION (OR) ALL THE TRASACTIONS AT
A TIME.

BEGIN TRAN

UPDATE EMP SET SAL=976 WHERE EMPNO=7369

SAVE TRAN A
BEGIN TRAN
UPDATE EMP SET SAL=1814 WHERE EMPNO=7499
SAVE TRAN B
BEGIN TRAN
UPDATE EMP SET SAL=1564 WHERE EMPNO=7521
SAVE TRAN C

ROLLBACK TRAN B
SELECT * FROM EMP

DCL (GRANT,REVOKE)

USER IS CREATED BY DBA (DATABASE ADMINISTRATOR)


GRANT COMMAND IS USED GRANTING THE PERMISSIONS TO THE USERS.
REVOKE COMMAND IS USED REMOVING(OR) TAKEOUT THE PERMISSIONS FROM THE USERS.

HOW TO CREATE THE USER


SYNTAX:-
CREATE USER <USERNAME> IDENTIFIED BY <PASSWORD>
EXAMPLE:-
CREATE USER VENKAT IDENTIFIED BY BHARGAV
GRANT ALL ON EMP TO VENKAT
(OR)
GRANT SELECT,INSERT ON EMP TO VENKAT

32
33

CONNECT VENKAT/BHARGAV
REVOKE ALL ON EMP FROM VENKAT
REVOKE SELECT,INSERT ON EMP FROM VENKAT

HOW TO DROP THE USER

SYNTAX
DROP USER <USERNAME>
EXAMPLE:-
DROP USER VENKAT

PLSQL

PL STANDS FOR PROCEDURAL LANGUAGE

SQL STANDS FOR STRUTURED QUERY LANGUAGE

non procedural language

the sequence of instructions are used to produce specific desired result is known as
procedural language

example:- c,c++ ,plsql

in non procedural language one single statement that must be terminated with
semicolon.

example:- sql

in pl/sql the procedural extension to non procedural sql statements.

Variables are declared in the body of a batch or procedure with the DECLARE
statement and are assigned values by using either a SET or SELECT statement.
Cursor variables can be declared with this statement and used with other cursor-
related statements. After declaration, all variables are initialized as NULL, unless a
value is provided as part of the declaration.

@ local_variable

Is the name of a variable. Variable names must begin with an at (@) sign

declare @a int, @b int, @c int

set @a=10

set @b=5

33
34

set @c=@a+@b

print ' SUM OF THE TWO NUMBERS IS ' + convert(varchar,@c)

declare the variables


initialize the values (or) assigning the values
then apply the condition
to print values on the screen
print function is used to print values on the screen

declare @p int,@n decimal(5,2), @r decimal(5,2),@si decimal(9,2)

set @p=10000

set @n=15

set @r=7.5

set @si=(@p * @n * @r)/100

print ' SIMPLE INTEREST IS ' + CONVERT(VARCHAR,@si)

declare @a int,@b int, @c int


set @a=25
set @b=15
set @c=@a
set @a=@b
set @b=@c
print 'a= : ' + convert(varchar, @a)
print 'b= : ' + convert(varchar, @b)

control flow statements also conditional control

for applying the conditions or checking the values at the time of inserting from the
keyboard

there are three types of statements

1) if else statement 2) begin end 3) while statement

1) if else statement:- it is used to execute the statements based on condition

syntax:-

if <condition is true>
<statement1>
else

34
35

<statement2>

example:-

declare @a int, @b int


set @a=5
set @b=4
if (@a > @b)
print 'LARGEST NUMBER ' + CONVERT(VARCHAR, @a)
else
PRINT 'LARGEST NUMBER IS ' + CONVERT(VARCHAR,@b)

declare @a int
select @a=COUNT(*) from emp
if (@a > 6)
print 'TABLE HAVA RECORDS ' + CONVERT(VARCHAR, @a)
else
PRINT 'NO RECORDS IN THE TABLE '

WHILE STATEMENT
SYNTAX
INITIALIZATION
WHILE(<CONDITION>)
BEGIN
<STATEMENTS>
-----------------
END

display numbers from 1 to 10 using while statement

DECLARE @n int
set @n=1
while(@n<=10)
begin
print @n
set @n=@n+1
end

35
36

DISPLAY EVEN NUMBERS 2 4 6 8 10

DECLARE @n int
set @n=1
while(@n<=10)
begin
if(@n%2=0)
print @n
set @n=@n+1
end

CURSORS

Cursor Is A Database Used To Process The Set Of Records Individually, One Record
At A Time.

RESULTSET:- SELECT STATEMENT RETURNS ALL THE ROWS, WHICH SN ATISFIED


THE CONDITION IN WHERE CLAUSE THE ROWS RETURNED BY THE SELECT.
STATMENTS ARE CALLED RESULTSET.

TYPES OF CURSORS
1) STATIC CURSORs
2) DYNAMIC CURSOR
3) FORWARD ONLY
4) KEY SET CURSORS

NECESSARY STEPS TO PROCESS CURSOR

1) DECLARE CURSOR
2) OPEN CURSOR
3) FETCH RECORD FROM THE CURSOR
4) CLOSE CURSOR
5) DEALLOCATE CURSOR

KEYWORDS

i) FIRST - > USED TO FETECH THE FIRST RECORD

ii) NEXT - > used to fetch the record next to the previously fetched record

iii) LAST - > USED TO FETCH THE PREVIOUS RECORD FROM THE RESULTSET

iv) PRIOR - > USED TO FETCH THE PREVIOUS RECORD FROM CURRENT POSITION

36
37

V) ABSOLUTE n -> if n is positive, it fetches nth record from the beginning. if n is


negative is fetches nth record from the last if n=0, no records will be fetched

Vi) RELATIVE n -> if n is positive, it fetches 10th record from the previously fetched
record. if n is negative is fetches nth record before the previously fetched record. if
n=0, same record will be fetched

DECLARE dept3 CURSOR FOR SELECT DEPTNO,DNAME FROM DEPT


DECLARE @dno int, @name varchar(20)
OPEN DEPT3
FETCH NEXT FROM DEPT3 into @dno, @name
while(@@FETCH_STATUS=0)
BEGIN
PRINT @DNO
PRINT @NAME
FETCH NEXT FROM DEPT3 INTO @dno,@name
end
CLOSE DEPT3

DECLARE dept4 CURSOR DYNAMIC FOR SELECT DEPTNO,DNAME FROM DEPT


DECLARE @dno int, @name varchar(20)
OPEN DEPT4
FETCH FIRST FROM DEPT4 into @dno, @name
PRINT @DNO
PRINT @NAME
CLOSE dept4

DECLARE dept5 CURSOR DYNAMIC FOR SELECT DEPTNO,DNAME FROM DEPT


DECLARE @dno int, @name varchar(20)
OPEN DEPT5
FETCH LAST FROM DEPT5 into @dno, @name
PRINT @DNO
PRINT @NAME
CLOSE dept5

DECLARE dept6 CURSOR DYNAMIC FOR SELECT DEPTNO,DNAME FROM DEPT


DECLARE @dno int, @name varchar(20)
OPEN DEPT6
FETCH LAST FROM DEPT6 into @dno, @name
PRINT @DNO
PRINT @NAME
FETCH PRIOR FROM DEPT6 into @dno, @name
PRINT @DNO

37
38

PRINT @NAME
CLOSE dept6

DESTROYING THE CURSOR

DEALLOCATE <CURSORNAME>
DEALLOCATE DEPT6

DECLARE dept7 CURSOR DYNAMIC FOR SELECT DEPTNO,DNAME FROM DEPT

DECLARE @dno int, @name varchar(20)

OPEN DEPT7

FETCH ABSOLUTE 5 FROM DEPT7 into @dno, @name

PRINT @DNO

PRINT @NAME

FETCH RELATIVE 2 FROM DEPT7 into @dno, @name

PRINT @DNO

PRINT @NAME

CLOSE dept7

DECLARE dept7 CURSOR DYNAMIC FOR SELECT DEPTNO,DNAME FROM DEPT


DECLARE @dno int, @name varchar(20)
OPEN DEPT7
FETCH ABSOLUTE 5 FROM DEPT7 into @dno, @name
PRINT @DNO
PRINT @NAME
FETCH RELATIVE 2 FROM DEPT7 into @dno, @name
PRINT @DNO
PRINT @NAME
CLOSE dept7

PROCEDURES ALSO CALLED STORED PROCEDURE

38
39

ARE USED TO PERFORM SOME TASK. PROCEDURE DO NOT HAVE RETURN CLAUSE.
A STORED PROCEDURE IS AN ALREADY WRITTEN SQL STATEMENT THAT IS SAVED
IN THE DATABASE.

HOW TO CREATE USER DEFINED PROCEDURES

THE PROCEDURES CREATED BY THE USER ARE CALLED USER DEFINED STORED
PROCEDURES

SYNTAX:-

CREATE / ALTER PROCEDURE <PROCEDURENAME> (@PARA1 DATATYPE SIZE,....)


WITH RECOMPILE ENCRYPTION

<STATEMENTS>

AS

BEGIN

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

END

EXAMPLE:-

CREATE PROCEDURE VENKAT1 AS SELECT * FROM DEPT

HOW TO EXECUTE THE PROCEDURE


SYNTAX:-
EXEC <PROCEDURENAME>
EXAMPLE:-
EXEC VENKAT1

CREATE PROCEDURE ADDNUM AS DECLARE @a int, @b int, @c int


set @a=10
set @b=5
set @c=@a+@b
print 'THE SUM IS ' + CONVERT(VARCHAR,@c)

exec addnum

CREATE PROCEDURE ADDNUM @a int , @b int


as
begin
declare @c int

39
40

set @c=@a+@b
print 'THE SUM IS ' + CONVERT(VARCHAR,@c)
end

exec addnum 25,15

create procedure emp12 @vno int


as
select * from emp where empno=@vno

exec emp12 7788

HOW TO DROP THE PROCEDURE


SYNTAX:-
DROP PROCEDURE VENKAT1

FUNCTIONS:- ARE USED TO COMPUTE THE VALUES. FUNCTION CAN RETURN


ENTIRE TABLE TO THE CALLING ENVIRONMENT. FUNCTION DO HAVE RETURN
CLAUSE.

SYNTAX:-

CREATE FUNCTION <FUNCTIONNAME>(@PARA1 <DATATYPE><SIZE>,........)

RETURN TABLE AS

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

BEGIN

<FUNCTION BODY>

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

RETURN (SELECT STATEMENT)

END

40
41

display the ENAME, dname from department,EMPLOYEE details

Stored procedures are a powerful part of SQL Server. They can assist programmers and administrators
greatly in working with the database configuration and its data.

A stored procedure is a precompiled group of Transact-SQL statements, and is saved to the database (under
the "Stored Procedures" node). Programmers and administrators can execute stored procedures either from
the SQL Server Management Studio or from within an application as required.

Transact-SQL, which is based on SQL (Structured Query Language), is the programming language used to
interface between applications and their databases. Transact-SQL is a relatively easy language to learn and I
highly recommend becoming familiar with it.

enefit Explanation of benefit

Modular programming You can write a stored procedure once, then call it from
multiple places in your application.

Performance Stored procedures provide faster code execution and reduce


network traffic.

 Faster execution: Stored procedures are parsed and


optimized as soon as they are created and the stored
procedure is stored in memory. This means that it will
execute a lot faster than sending many lines of SQL
code from your application to the SQL Server. Doing
that requires SQL Server to compile and optimze your
SQL code every time it runs.
 Reduced network traffic: If you send many lines of
SQL code over the network to your SQL Server, this
will impact on network performance. This is
especially true if you have hundreds of lines of SQL
code and/or you have lots of activity on your
application. Running the code on the SQL Server (as a
stored procedure) eliminates the need to send this
code over the network. The only network traffic will
be the parameters supplied and the results of any
query.

Security Users can execute a stored procedure without needing to

41
42

execute any of the statements directly. Therefore, a stored


procedure can provide advanced database functionality for
users who wouldn't normally have access to these tasks, but
this functionality is made available in a tightly controlled
way.

Creates a user-defined function in SQL Server 2012. A user-defined function is a Transact-SQL or common language
runtime (CLR) routine that accepts parameters, performs an action, such as a complex calculation, and returns the
result of that action as a value. The return value can either be a scalar (single) value or a table. Use this statement to
create a reusable routine that can be used in these ways:
 In Transact-SQL statements such as SELECT
 In applications calling the function
 In the definition of another user-defined function
 To parameterize a view or improve the functionality of an indexed view
 To define a column in a table
 To define a CHECK constraint on a column
 To replace a stored procedure
 SELECT * FROM dbo.MyTable WHERE col1 = dbo.MyFunction(col2)

 Where MyFunction is declared as:
 CREATE FUNCTION MyFunction (@someValue INTEGER) RETURNS INTEGER
 AS
 BEGIN
 DECLARE @retval INTEGER

 SELECT localValue
 FROM dbo.localToNationalMapTable
 WHERE nationalValue = @someValue

 RETURN @retval
 END

The difference between SP and UDF is listed below:

42
43

DIFFERENCE BETWEEN STORED PROCEDURES AND FUNCTIONS

SQL Server user-defined functions and stored procedures offer similar functionality. Both allow you to create bundles of SQL
statements that are stored on the server for future use. This offers you a tremendous efficiency benefit, as you can save
programming time by:
 Reusing code from one program to another, cutting down on program development time
 Hiding the SQL details, allowing database developers to worry about SQL and application developers to deal only in higher-
level languages
 Centralize maintenance, allowing you to make business logic changes in a single place that automatically affect all dependent
applications
At first glance, functions and stored procedures seem identical. However, there are several subtle, yet important differences
between the two:
 Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL
statement.
 Stored procedure allow you to enhance application security by granting users and applications permission to use stored
procedures, rather than permission to access the underlying tables. Stored procedures provide the ability to restrict user
actions at a much more granular level than standard SQL Server permissions. For example, if you have an inventory table that
cashiers must update each time an item is sold (to decrement the inventory for that item by 1 unit), you can grant cashiers
permission to use a decrement_item stored procedure, rather than allowing them to make arbitrary changes to the inventory
table.
 Functions must always return a value (either a scalar value or a table). Stored procedures may return a scalar value, a table
value or nothing at all.
Overall, stored procedures are one of the greatest treasures available to SQL Server developers. I use them heavily in my
databases and encourage you to do the same. The efficiency and security benefits you’ll reap are well worth the upfront
investment in time.

A Parameterized Function
To create a function that takes a parameter, specify a name and the type of value of the
parameter(s) in its parentheses. Here is an example:

CREATE FUNCTION Addition(@Number1 Decimal(6,2))

43
44

When a function takes a parameter, in the body of the function, you can use the
parameter as if you knew its value, as long as you respect the type of that value. Here is
an example:

CREATE FUNCTION Addition(@Number1 Decimal(6,2))


RETURNS Decimal(6,2)
BEGIN
RETURN @Number1 + 1450
END

A Function With Various Arguments


Instead of only one parameter, you can also create a function that takes more than one
parameter. In this case, separate the arguments in the parentheses of the function with a
comma. Here is an example:

CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2))

Once again, in the body of the function, you can use the parameters as if you already
knew their value. You can also declare local variables and involve them with parameters
as you see fit. Here is an example:

CREATE FUNCTION Addition(@Number1 Decimal(6,2),


@Number2 Decimal(6,2))
RETURNS Decimal(6,2)
BEGIN
DECLARE @Result Decimal(6,2)
SET @Result = @Number1 + @Number2
RETURN @Result
END;
GO

PRINT Variables1.dbo.Addition(1450, 228);

You can also pass the names of already declared and initialized variables. Here is an
example that calls the above function:

DECLARE @Nbr1 Decimal(6,2),


@Nbr2 Decimal(6,2)
SET @Nbr1 = 4268.55
SET @Nbr2 =26.83
SELECT @Nbr1 As First,
@Nbr2 As Second,
Variables1.dbo.Addition(@Nbr1, @Nbr2) AS Result

QL Server’s own list of functions is limited as far as what is available for database
developers to use in their applications. Starting with SQL Server 2000, database developers
were given the ability to create their own routines that accept parameters, perform custom
actions and return results.

SQL Server's own list of available functions is not enough for database developers to use in
their applications, especially when it comes to business logic, complex algorithmic
calculations and custom actions. In this light, beginning with SQL 2000, SQL Server allows

44
45

database developers to create their own routines, which can accept parameters, perform
custom actions and return results. These routines are called user-defined functions.

Initially SQL Server only allowed user-defined functions in T-SQL. Following CLR integration
in the SQL Server engine, the later versions of SQL Server (including SQL Server 2008 R2)
allow users to create user-defined functions (called UDFs from here on) in a managed code,
in addition to T-SQL.

With UDFs, database developers can express their business logic in a form they know best
and get their business logic executing in the SQL engine from where it can be called in their
SQL queries.

Benefits of User-defined Functions

Below are the most visible benefits of user-defined functions.

 Extend programming richness via user code - Your database can now do more
than only process data. With UDFs, databases can now also validate business logic
and do custom actions.
 Faster performance than T-SQL functions for computational logic - T-SQL
functions are great at processing data. When it comes to business logic and custom
algorithms, UDFs can do a much better job. UDFs work akin to stored procedures.
 Optimizes network traffic - UDFs allow data manipulation such that you don't
need a lot of talking to the database and you can optimize your results based on
your business logic within the database. This reduces network bandwidth utilization.
 Reusable code, which can be called akin to stored procedures with business logic.

Limitations of User-defined Functions

When called in SQL queries, UDFs are only executed in a single thread. They follow serial
execution plan. Hence, if the business logic inside UDFs would work better in a multi-
threaded environment, it would be better to not implement it as a user-defined function,
since it would lead to over-all performance degradation.

UDFs cannot change database state so there might be usage constraints if you are
attempting to change the database information inside your business logic.

Where are User Defined Functions Used

The following is a list of most common usage area of UDFs.

 In T-SQL statements, such as select


 Inside the definition of another User-defined function
 As a replacement of stored procedures
 For defining automatic values for a column in a table

Structure of User-defined Function

UDFs are composed of two parts:

45
46

1. Header
2. Function body

The header contains the function name, input parameter info (name and type), and return
parameter info (name and type). The function body contains the logic. It contains one or
more T-SQL statements that contain the logic and it can also contain a reference to a .NET
assembly (in case of a CLR UDF).

Types of User-defined Functions

Based on the return type, UDFs can be classified as scalar functions and table-value
functions.

Scalar Functions

Scalar functions are UDFs, which return a single value.

There is no function body in the case of an inline scalar function, and the scalar value (the
return value) is the result of a single statement.

CREATE FUNCTION EmployeeContactID(@Empid int)


RETURNS int
AS
BEGIN

Declare @returnvalue int


Select @returnvalue=Employee.ContactID from Employee where
Employee.EmployeeID=@Empid
RETURN @returnvalue
END

Execution:
select dbo.EmployeeContactID(1)

1 CREATE FUNCTION dbo.GetEmployeeFunction(@empid int)


2 RETURNS TABLE
3 AS
4 RETURN SELECT *
5 FROM employee where employee.EmployeeID=@empid
6
7 Execution:
8
9 select * from dbo.GetEmployeeFunction(1)
1) Table valued Functions ( multiple operations, complex

46
47

CREATE FUNCTION dbo.multi_test(@empid int)


RETURNS @Result TABLE
(
name varchar(20)
)
AS
BEGIN
INSERT INTO @Result
(name)
SELECT [name] from employee where EmployeeID=1

UPDATE @Result
SET name = 'N'

RETURN
END

Exectution :
Select * from dbo.multi_test(1)
Difference between Stored procedures and User defined functions:

i)A stored procedure is pre compiled while a User defined function is compiled and
executed at runtime.

ii)A Stored procedure is more flexible than user defined function like you can write
complex logic (for example exceptional handling using try catch block is possible in
stored procedures which is not possible in user defined functions)

iii) A stored procedure can call another stored procedure or user defined function inside
it but a user defined function can’t call stored procedure inside it.

iv)A stored procedure can return non deterministic values but a user defined function
can’t return a non deterministic values like Get Date () function.

v) A user defined functions does not support DML operations like insertion, deletion and
update on the base table but it is possible via stored procedure.

vi) A user defined function is easier to execute and can be used inside selection and
even for joins but stored procedure can’t be used inside selection queries and it can’t be
used to join with other tables.

47
48

CREATE FUNCTION EMP_DEPT()


RETURNS TABLE
AS
BEGIN
RETURN (SELECT ENAME,DNAME FROM EMP,DEPT WHERE DEPT.DEPTNO=EMP.DEPTNO)
END

CREATE FUNCTION DEPTTAB()


RETURNS TABLE
AS
BEGIN
RETURN (SELECT * FROM DEPT)
END

ELECT * FROM DBO.DEPTTAB()

CREATE FUNCTION Addition(@Number1 Decimal(6,2),


@Number2 Decimal(6,2))
RETURNS Decimal(6,2)
BEGIN
DECLARE @Result Decimal(6,2)
SET @Result = @Number1 + @Number2
RETURN @Result
END;
GO

drop function addition

PRINT dbo.Addition(1450, 228);

CREATE FUNCTION dbo.GetEmployeeFunction(@empid int)


RETURNS TABLE
AS
RETURN SELECT * FROM emp where emp.empno=@empid

select * from dbo.GetEmployeeFunction(7788)

TRIGGERS
Are Special Types Of Stored Procedures That Are Defined To Execute Automatically In Place Of
Or After Data Modifications. They Can Be Executed Automatically On The Insert, Delete And
Update Triggering Actions.
There Are Two Different Types Of Triggers In Sql Server. They Are Dml Triggers And Ddl Triggers

48
49

Under Dml Triggers We Have Two Types They Are Instead Of Triggers And After Triggers.
These Triggers Differ From Each Other In Terms Of Their Purpose And When They Are Fixed.
Trigger Is One Type Of Stored Procedure, Executed Implicitly When User Performs A Dml Or Ddl
Operation On The Table.
It Will Not Accept Parameters. It Is Permanently Stored In Database.

TYPES OF TRIGGERS

1) INSERT TRIGGER 2) DELETE TRIGGER 3) UPDATE TRIGGER 4) INSTEAD OF


TRIGGER

SYNTAX:-

CREATE TRIGGER <TRIGGERNAME> ON <TABLENAME> FOR /AFTER


INSERT/UPDATE/DELETE AS

BEGIN

<STATEMENTS>

END

INSERT TRIGGER:- This Trigger Fires When User Performs Insert Operation On
The Table. When User Insert A Record Into The Table The Temporary Table Called
Inserted Is Created In The Temporary Memory.

EXAMPLE:-

CREATE TRIGGER T1 ON DEPT FOR INSERT


AS
BEGIN
PRINT ' TRIGGER T1 TO FIRE'
END

INSTEAD OF TRIGGERS YOU CAN CREATE ONLY ON VIEWS

SYNTAX:-

CREATE TRIGGER <TRIGGERNAME> ON <VIEWNAME> INSTEAD OF INSERT/UPDATE/DELETE AS


BEGIN

49
50

<STATEMENTS>
END

CREATE VIEW V12 AS SELECT * FROM EMP WHERE DEPTNO=20

SELECT * FROM V12

CREATE VIEW V12 AS SELECT * FROM EMP WHERE DEPTNO=20

SELECT * FROM V12

CREATE TRIGGER T12 ON V12 INSTEAD OF INSERT AS


BEGIN
INSERT INTO V12(EMPNO,ENAME,JOB)VALUES(8819,'BHARGAV','MANAGER')
END

DROP TRIGGER T12

DDL TRIGGERS

THESE TRIGGERS ARE FIRED WHEN DDL TRASACTIONS ARE PERFORMED

SYNTAX:-

CREATE TRIGGER <TRIGGELERNAME> ON DATABASENAME FOR


CREATE/ALTER/DROP
AS
BEGIN
<STATEMENTS>
END

EXAMPLE:-

CREATE TRIGGER TV1 ON DATABASE FOR CREATE_TABLE


AS
BEGIN
ROLLBACK
PRINT 'U CANNOT CREATE TABLE'
END

CREATE TABLE COURSE1


(CRNO INT,
CRNAME VARCHAR(20),
CRFEES DECIMAL(7,2))

50
51

A TRIGGER CREATED WITH INSERT/UPDATE/DELETE/CREATE/ALTER/DROP CANNOT HAVE SAME


STATEMENT ON THE SAME DATABASE.

DROP TRIGGER TV1 ON DATABASE

TSQL PLSQL FAQS

1. Which TCP/IP port does SQL Server run on? How can it be changed?

SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties.

2. What are the difference between clustered and a non-clustered index?

1. A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index. The leaf nodes of a
clustered index contain the data pages.
2. A non clustered index is a special type of index in which the logical order of the index
does not match the physical stored order of the rows on disk. The leaf node of a non
clustered index does not consist of the data pages. Instead, the leaf nodes contain index
rows.

3. What are the different index configurations a table can have?

A table can have one of the following index configurations:

1. No indexes
2. A clustered index
3. A clustered index and many nonclustered indexes
4. A nonclustered index
5. Many nonclustered indexes

4. What are different types of Collation Sensitivity?

1. Case sensitivity - A and a, B and b, etc.


2. Accent sensitivity
3. Kana Sensitivity - When Japanese kana characters Hiragana and Katakana are treated
differently, it is called Kana sensitive.
4. Width sensitivity - A single-byte character (half-width) and the same character
represented as a double-byte character (full-width) are treated differently than it is width
sensitive.

5. What is OLTP (Online Transaction Processing)?

51
52

In OLTP - online transaction processing systems relational database design use the discipline of
data modeling and generally follow the Codd rules of data normalization in order to ensure
absolute data integrity. Using these rules complex information is broken down into its most
simple structures (a table) where all of the individual atomic level elements relate to each other
and satisfy the normalization rules.

6. What's the difference between a primary key and a unique key?

Both primary key and unique key enforces uniqueness of the column on which they are defined.
But by default primary key creates a clustered index on the column, where are unique creates a
nonclustered index by default. Another major difference is that, primary key doesn't allow
NULLs, but unique key allows one NULL only.

7. What is difference between DELETE and TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a
WHERE clause. Truncate will actually remove all the rows from a table and there will be no data
in the table after we run the truncate command.

1. TRUNCATE:
1. TRUNCATE is faster and uses fewer system and transaction log resources than
DELETE.
2. TRUNCATE removes the data by deallocating the data pages used to store the
table's data, and only the page deallocations are recorded in the transaction log.
3. TRUNCATE removes all rows from a table, but the table structure, its columns,
constraints, indexes and so on, remains. The counter used by an identity for new
rows is reset to the seed for the column.
4. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY
constraint. Because TRUNCATE TABLE is not logged, it cannot activate a
trigger.
5. TRUNCATE cannot be rolled back.
6. TRUNCATE is DDL Command.
7. TRUNCATE Resets identity of the table
2. DELETE:
1. DELETE removes rows one at a time and records an entry in the transaction log
for each deleted row.
2. If you want to retain the identity counter, use DELETE instead. If you want to
remove table definition and its data, use the DROP TABLE statement.
3. DELETE Can be used with or without a WHERE clause
4. DELETE Activates Triggers.
5. DELETE can be rolled back.
6. DELETE is DML Command.
7. DELETE does not reset identity of the table.

8. When is the use of UPDATE_STATISTICS command?

52
53

This command is basically used when a large processing of data has occurred. If a large amount
of deletions any modification or Bulk Copy into the tables has occurred, it has to update the
indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on
these tables accordingly.

9. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?

They specify a search condition for a group or an aggregate. But the difference is that HAVING
can be used only with the SELECT statement. HAVING is typically used in a GROUP BY
clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause
is basically used only with the GROUP BY function in a query whereas WHERE Clause is
applied to each row before they are part of the GROUP BY function in a query.

10. What are the properties and different Types of Sub-Queries?

1. Properties of Sub-Query
1. A sub-query must be enclosed in the parenthesis.
2. A sub-query must be put in the right hand of the comparison operator, and
3. A sub-query cannot contain an ORDER-BY clause.
4. A query can contain more than one sub-query.
2. Types of Sub-Query
1. Single-row sub-query, where the sub-query returns only one row.
2. Multiple-row sub-query, where the sub-query returns multiple rows,. and
3. Multiple column sub-query, where the sub-query returns multiple columns

11. What is SQL Profiler?

SQL Profiler is a graphical tool that allows system administrators to monitor events in an
instance of Microsoft SQL Server. You can capture and save data about each event to a file or
SQL Server table to analyze later. For example, you can monitor a production environment to
see which stored procedures are hampering performances by executing too slowly.

Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming
too large, you can filter them based on the information you want, so that only a subset of the
event data is collected. Monitoring too many events adds overhead to the server and the
monitoring process and can cause the trace file or trace table to grow very large, especially when
the monitoring process takes place over a long period of time.

12. What are the authentication modes in SQL Server? How can it be changed?

Windows mode and Mixed Mode - SQL and Windows. To change authentication mode in SQL
Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run
SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then
from the Tools menu select SQL Server Configuration Properties, and choose the Security page.

53
54

13. Which command using Query Analyzer will give you the version of SQL server and
operating system?

SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'),


SERVERPROPERTY ('edition').

14. What is SQL Server Agent?

SQL Server agent plays an important role in the day-to-day tasks of a database administrator
(DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose
is to ease the implementation of tasks for the DBA, with its full- function scheduling engine,
which allows you to schedule your own jobs and scripts.

15. Can a stored procedure call itself or recursive stored procedure? How much level SP nesting
is possible?

Yes. Because Transact-SQL supports recursion, you can write stored procedures that call
themselves. Recursion can be defined as a method of problem solving wherein the solution is
arrived at by repetitively applying it to subsets of the problem. A common application of
recursive logic is to perform numeric computations that lend themselves to repetitive evaluation
by the same processing steps. Stored procedures are nested when one stored procedure calls
another or executes managed code by referencing a CLR routine, type, or aggregate. You can
nest stored procedures and managed code references up to 32 levels.

16. What is Log Shipping?

Log shipping is the process of automating the backup of database and transaction log files on a
production SQL server, and then restoring them onto a standby server. Enterprise Editions only
supports log shipping. In log shipping the transactional log file from one server is automatically
updated into the backup database on the other server. If one server fails, the other server will
have the same db and can be used this as the Disaster Recovery plan. The key feature of log
shipping is that it will automatically backup transaction logs throughout the day and
automatically restore them on the standby server at defined interval.

17. Name 3 ways to get an accurate count of the number of records in a table?

SELECT * FROM table1


SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

18. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of
having it OFF?

When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation


marks, and literals must be delimited by single quotation marks. When SET
QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL
rules for identifiers.

54
55

19. What is the difference between a Local and a Global temporary table?

1. A local temporary table exists only for the duration of a connection or, if defined inside
a compound statement, for the duration of the compound statement.
2. A global temporary table remains in the database permanently, but the rows exist only
within a given connection. When connection is closed, the data in the global temporary
table disappears. However, the table definition remains with the database for access when
database is opened next time.

20. What is the STUFF function and how does it differ from the REPLACE function?

STUFF function is used to overwrite existing characters. Using this syntax, STUFF
(string_expression, start, length, replacement_characters), string_expression is the string that will
have characters substituted, start is the starting position, length is the number of characters in the
string that are substituted, and replacement_characters are the new characters interjected into the
string. REPLACE function to replace existing characters of all occurrences. Using the syntax
REPLACE (string_expression, search_string, replacement_string), where every incidence of
search_string found in the string_expression will be replaced with replacement_string.

21. What is PRIMARY KEY?

A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table
should have a primary key constraint to uniquely identify each row and only one primary key
constraint can be created for each table. The primary key constraints are used to enforce entity
integrity.

22. What is UNIQUE KEY constraint?

A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate
values are entered. The unique key constraints are used to enforce entity integrity as the primary
key constraints.

23. What is FOREIGN KEY?

A FOREIGN KEY constraint prevents any actions that would destroy links between tables with
the corresponding data values. A foreign key in one table points to a primary key in another
table. Foreign keys prevent actions that would leave rows with foreign key values when there are
no primary keys with that value. The foreign key constraints are used to enforce referential
integrity.

24. What is CHECK Constraint?

A CHECK constraint is used to limit the values that can be placed in a column. The check
constraints are used to enforce domain integrity.

25. What is NOT NULL Constraint?

55
56

A NOT NULL constraint enforces that the column will not accept null values. The not null
constraints are used to enforce domain integrity, as the check constraints.

26. How to get @@ERROR and @@ROWCOUNT at the same time?

If @@Rowcount is checked after Error checking statement then it will have 0 as the value of
@@Recordcount as it would have been reset. And if @@Recordcount is checked before the
error-checking statement then @@Error would get reset. To get @@error and @@rowcount at
the same time do both in same statement and store them in local variable.

SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

27. What is a Scheduled Jobs or What is a Scheduled Tasks?

Scheduled tasks let user automate processes that run on regular or predictable cycles. User can
schedule administrative tasks, such as cube processing, to run during times of slow business
activity. User can also determine the order in which tasks run by creating job steps within a SQL
Server Agent job. E.g. back up database, Update Stats of Tables. Job steps give user control over
flow of execution. If one job fails, user can configure SQL Server Agent to continue to run the
remaining tasks or to stop execution.

28. What are the advantages of using Stored Procedures?

1. Stored procedure can reduced network traffic and latency, boosting application
performance.
2. Stored procedure execution plans can be reused, staying cached in SQL Server's memory,
reducing server overhead.
3. Stored procedures help promote code reuse.
4. Stored procedures can encapsulate logic. You can change stored procedure code without
affecting clients.
5. Stored procedures provide better security to your data.

29. What is a table called, if it has neither Cluster nor Non-cluster Index? What is it used for?

Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A
heap is a table that does not have a clustered index and, therefore, the pages are not linked by
pointers. The IAM pages are the only structures that link the pages in a table together. Unindexed
tables are good for fast storing of data. Many times it is better to drop all indexes from table and
then do bulk of inserts and to restore those indexes after that.

30. Can SQL Servers linked to other servers like Oracle?

SQL Server can be linked to any server provided it has OLE-DB provider from Microsoft to
allow a link. E.g. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as
linked server to SQL Server group.

56
57

31. What is BCP? When does it used?

BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy
the structures same as source to destination. BULK INSERT command helps to import a data file
into a database table or view in a user-specified format.

32. How to implement one-to-one, one-to-many and many-to-many relationships while designing
tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with
primary and foreign key relationships. One-to-Many relationships are implemented by splitting
the data into two tables with primary key and foreign key relationships. Many-to-Many
relationships are implemented using a junction table with the keys from both the tables forming
the composite primary key of the junction table.

33. What is an execution plan? When would you use it? How would you view the execution
plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval
methods chosen by the SQL Server query optimizer for a stored procedure or ad- hoc query and
is a very useful tool for a developer to understand the performance characteristics of a query or
stored procedure since the plan is the one that SQL Server will place in its cache and use to
execute the stored procedure or query. From within Query Analyzer is an option called "Show
Execution Plan" (located on the Query drop-down menu). If this option is turned on it will
display query execution plan in separate window when query is ran again.

57
58

58
59

59
60

LIKE

PL/SQL

60

You might also like