Professional Documents
Culture Documents
SQLSERVER
DEVELOPEMENT
TSQ
SQLSERVER 2008 R2 SOFTWARE LINK:
http://care.dlservice.microsoft.com/download/D/8/0/D808E432-5AC6-4DA5-A087-
21947AC4AC5F/1033/SQLFULL_ENU.iso?lcid=1033
INDEX:
TOPIC NAME PAGE NUMBER
INTRODUCTION TO DBMS AND RDBMS 3
SQLSERVER 2008 R2 INTRODUCTION 6
MANAGEMENT STUDIO (SSMS) 8
SYSTEM AND USER DATABASES 10
SQLSERVER DATATYPES 11
TABLES FOR PRACTICALS 13
TSQL SUB LANGUAGES (DDL,DML,DRL,TCL,DCL) 14
OPERATORS (ARITHMETIC,ASSIGNMENT,LOGICAL AND SQL) 22
FUNCTIONS (NUMERIC,CHARACTER,DATETIME,AGGREGATE) 25
SET OPERATORS 30
CLAUSES (GROUP BY,HAVING,ORDER BY) 31
JOINS 32
SUB QUERIES 34
COPY TABLE CONCEPT 36
CONSTRAINTS 36
NORMALIZATION 39
VIEWS 42
INDEXES 44
SYNONYMS 46
SQLSERVER LOCKS 46
DEFAULTS AND RULES 47
Email: cm.bolla@gmail.com
SQL Material
2
INTRODUCTION TO PROGRAMS 49
CURSORS 52
STORED PROCEDURES 57
USER DEFINED FUNCTION 61
TRIGGERS 64
DIFFERENCE BETWEEN SQLSERVER AND ORACLE 68
TSQL ENHANCEMENTS IN SQLSERVER 2008 74
QUERIES 77
NEW FEATURES OF SQLSERVER 2012
Data: Data is the most important component in any work that we do; Data means collection of
information or collection of raw facts.
Ex:
1. Text files
2. Facts
3. Figures (photos)
4. Audios
5. Videos etc...
Data Base Management System is the management system or maintenance system on databases.
(Or)
It is a suit of software program for creating, maintaining & manipulating the data in database.
(Or)
It allows the users to insert the data, to retrieve the data, to modify the data and to delete the
data.
Properties:
1. Create
2. Insert
3. Update
4. Delete
5. Select (query)
Email: cm.bolla@gmail.com
SQL Material
3
Note: basic property of file system is independent and individual, means each and every file is
unique AND relation is not possible between data files
Table: It is collection of columns and rows, X axis directions are rows and Y axis directions are
columns
Ex of RDBMS:
1. Sqlserver
2. Oracle
3. Db2 (Database 2000, IBM)
4. Mysql (open source)
5. ms-access
6. Postgresql (open source)
7. Sybase
8. Tera data
Etc.....
Terminology:
Email: cm.bolla@gmail.com
SQL Material
4
1. Table -- Entity
2. Column (field) -- Attribute
3. Row (record) -- Tupple
4. Duplicate data (Repeated data) – Data Redundancy
Data models:
Relation
Perfect solution for duplicate data and null values
Normalization
EF CODD RULES:
Foundation Rule
A relational database management system must manage its stored data using only its relational
capabilities.
Information Rule
All information in the database should be represented in one and only one way - as values in a
table.
Email: cm.bolla@gmail.com
SQL Material
5
Integrity Independence
Integrity constraints specific to a particular relational database must be definable in the relational
data sublanguage and storable in the catalog, not in the application programs.
Distribution Independence
The data manipulation sublanguage of a relational DBMS must enable application programs and
terminal activities to remain logically unimpaired whether and whenever data are physically
centralized or distributed.
Email: cm.bolla@gmail.com
SQL Material
6
Nonsubversion Rule
If a relational system has or supports a low-level (single-record-at-a-time) language, that low-
level language cannot be used to subvert or bypass the integrity rules or constraints expressed in
the higher-level (multiple-records-at-a-time) relational language.
SQLSERVER 2012
1. It is RDBMS database
2. It is a product of Microsoft
3. It is case insensitive
4. It is platform dependant-- it is compatible for windows OS
5. User friendly
Sqlserver 4.0
Sqlserver 5.0
Sqlserver 6.0 (SQL 95)
Sqlserver 6.5 (HYDRA)
Sqlserver 7.0 (SPHINX)
Sqlserver 8.0(2000) (SHILOH)
Sqlserver 9.0(2005) (YUKON)
Sqlserver 10.0(2008) (KALMAI)
Sqlserver 10.5(2008 R2) (KILIMANJARO)
Sqlserver 11.0(2012) (DENALI)
Editions (Flavors):
1. Enterprise edition
2. Standard edition
3. Developer edition
4. Mobile edition
5. Compact Edition
6. Personal edition (Express Edition) free
Software Requirements:
1. OS
Email: cm.bolla@gmail.com
SQL Material
7
Hardware requirements:
1. Processor:
Ex:
2. Hard disk:
1 GB
3. Ram:
1 GB
Tool:
Email: cm.bolla@gmail.com
SQL Material
8
A. Windows’s authentication
B. Sqlserver authentication
Things to Observe:
1. While writing the Queries using T-SQL in SQL Server Management Studio we need not
to follow any particular case. Because T-SQL is case insensitive language.
2. After writing the Query, we need to select that query using either mouse or keyboard.
3. Now Press F5 (Execute Key).
4. Then the results are displayed in a separate window called Result window or Result
Pane.
5. Use Ctrl+R to Hide/Show the Result window or Result Pane.
6. Use F8 for Object Explorer
Databases:
1. System databases:
Email: cm.bolla@gmail.com
SQL Material
9
A. master
B. model
C. msdb
D. tempdb
E. MS resources
Description
master Records all the system-level information for an instance of SQL Server.
Database
msdb It is used by SQL Server Agent for scheduling alerts and jobs.
Database
model
Database Template database
Resource It is a read-only database that contains system objects that are included with
Database SQL Server 2005. System objects are physically persisted in the Resource
database, but they logically appear in the sys schema of every database.
2. User databases:
Ex:
(NAME=suresh,
FILENAME="C:\MSSQL\vadde\suresh.mdf",
SIZE=100,
MAXSIZE=200,
FILEGROWTH=25%)
Log on
(
NAME=suresh_log,
Email: cm.bolla@gmail.com
SQL Material
10
FILENAME="C:\MSSQL\vadde\suresh_log.ldf",
SIZE=100,
MAXSIZE=200,
FILEGROWTH=25%)
Character strings:
Unicode strings:
Binary types:
Number types:
Email: cm.bolla@gmail.com
SQL Material
11
bytes
Allows numbers from -10^38 +1 to 10^38 –1.
Date types:
Email: cm.bolla@gmail.com
SQL Material
12
clock and does not correspond to real time. Each table may have
only one timestamp variable
DATA:
Email: cm.bolla@gmail.com
SQL Material
13
DATA:
Email: cm.bolla@gmail.com
SQL Material
14
SQL
This is a 4th generated intermediate language between user and SQL Server. Whenever
user wants to interact with SQL Server, he has to interact with SQL Server through T-SQL. It
includes the following Sub Languages
Sublanguages:
1. DDL:
Commands:
1. Create
2. Truncate
3. Drop
4. Alter
Ex: create table T1 (id int, ename varchar (20), DOB datetime)
Note:
Max length of a table name and column name is 30; it may include alphabets, digits 0 to
9 and special character '_' (Underscore).
It is known as "naming conventions".
Max of 1024 columns can be included into a table.
2. Truncate: used to delete entire data from a table and its not possible to delete selected or
specific rows from a table by using truncate command.
Ex:
Email: cm.bolla@gmail.com
SQL Material
15
4. Alter:
Ex: alter table T1 add sal numeric (7, 2), comm Numeric (5, 2), address varchar (50)
Alter+alter: used change the data type and length of data type of a column
Miscellaneous:
System stored procedures: Directly we can execute them when ever required
Ex: sp_help T1
Email: cm.bolla@gmail.com
SQL Material
16
Syn: sp_tables
Ex: sp_tables
Syn: sp_databases
DML:
Commands:
1. Insert
2. Update
3. Delete
Note: while working with char and date time data we should use single quotes
Student table contains 5 columns; now insert null value into comm column
Email: cm.bolla@gmail.com
SQL Material
17
2. Update: used to update (replace) old data with new data, it is two types they are
3. Delete: used to delete entire data and selected data from a table
DRL:
Commands:
1. Retrieving entire data (all columns and all rows) from a table
Ex: select*from T3
Email: cm.bolla@gmail.com
SQL Material
18
Constraints:
Adv:
Note: We can create a constraint along with table creation this is of two types:
Types:
1. Primary key
Email: cm.bolla@gmail.com
SQL Material
19
2. Unique constraint
3. Check constraint
4. Not null
5. Foreign key (Referential integrity)
1. Primary key:
Properties:
It is unique
It is not null
Syn: create table <TN> (col1 DT (l) constraint con_name primary key, col2 DT (l), col3 DT (l))
Ex: create table t1 (id int constraint p_key primary key, name varchar (20), DOB datetime)
syn: create table <tn>(col1 dt(l),col2 dt(l),col3 dt(l), constraint con_name primary key(col1,col2))
Ex: create table t2 (id int, name varchar (20), DOB datetime, constraint p_key3 primary key (id,
name))
2. Unique constraint:
Properties:
Unique
It accepts single null value
Syn: create table <TN> (col1 DT (l) constraint con_name unique, col2 DT (l), col3 DT (l))
Ex: create table t3 (id int constraint u_con unique, dname varchar (20), loc varchar (20))
Email: cm.bolla@gmail.com
SQL Material
20
Syn: create table <tn>(col1 dt(l),col2 dt(l) constraint con_name check(condition),col3 dt(l))
Ex: create table t4 (id int, sal numeric (7, 2) constraint check_con check (sal>3000), commission
numeric (5, 2))
Syn: create table <TN> (col1 DT (l) constraint con_name not null)
5. Foreign key:
It always references values from either primary key or unique constraint and there are no
properties for foreign key.
We can create primary key and foreign key in single table, that is known as "self
referential integrity"
Note:
1. Primary key and foreign key columns data types must be same.
2. If the value existing in primary key then only we can insert same value into foreign key.
3. Foreign key accepts null values when it is referencing from unique constraint
syn: create table <tn>(col1 dt(l),col2 dt(l),col3 dt(l), constraint con_name foreign
key(col1)references <tn2>(col1))
Ex: create table t6 (id int, address varchar (50), job varchar (20), constraint f_key foreign key (id)
references t1 (id))
Email: cm.bolla@gmail.com
SQL Material
21
Dropping constraint:
Ex: sp_helpconstraint t1
Normalization:
Normalization is process of splitting the base table into multiple tables based on the theory of
Functional Dependency.
OR
Normalization is repetitive process in order to identify the functional dependencies among the
columns and to remove them. If any functional dependency is occurred after the normalization
process again we have to start the same process until all functional dependencies have been
removed.
Un-Normalized Table
EMPNO and PROJNO are Primary Keys called ‘COMPOSITE PRIMARY KEY’
Email: cm.bolla@gmail.com
SQL Material
22
FIRST NORMAL FORM (1NF): According to first normal form table should contain only single
values columns. But in the above un-normalized table the columns PROJNO and PNAME contains
multiple values.
To make the table into first normal form we should have to split the multiple values into single
values.
EMPNO PROJNO ENAME PNAME SAL BUD DEPTNO DNAME LOC
11 P1 ---- Pn1 ----- ----- 10 -------- -----
11 P2 ---- Pn2 ----- ----- 10 -------- -----
22 P2 ---- Pn2 ----- ----- 10 -------- -----
22 P3 ---- Pn3 ----- ----- 10 -------- -----
33 P1 ---- Pn1 ----- ----- 20 -------- -----
33 P3 ---- Pn3 ----- ----- 20 -------- -----
In the above table DEPTNO non-key column dependent part of the Primary key column i.e.
EMPNO. It means there existed Partial functional dependency.
To make the table into second normal form we have to divide the table into multiple tables.
PROJ-INFO
PROJNO PNAME BUD
P1 Pn1 ------
P2 Pn2 ------
P3 Pn3 ------
EMP-INFO
EMPNO ENAME SAL DEPTNO DNAME LOC
11 ---- ---- 10 ------ -----
22 ---- ---- 10 ------ -----
33 ---- ---- 20 ------ -----
Email: cm.bolla@gmail.com
SQL Material
23
In the above EMP-INFO table non-key column DNAME dependent part on the other non- key
column i.e.DEPTNO. It means there existed Transitive functional dependency.
To make the table into third normal form we have to divide the table into multiple tables.
PROJ-INFO
PROJNO PNAME BUD
P1 Pn1 ------
P2 Pn2 ------
P3 Pn3 ------
EMP-INFO DEPT-INFO
EMPNO ENAME SAL DEPTNO DNAME LOC
11 ---- ---- 10 ------ -----
22 ---- ---- 20 ------ -----
33 ---- ----
DCL: It is used to control the data between different user accounts. It includes the following
statements.
1. GRANT Statement
2. REVOKE Statement
Grant Statement: This statement is used to grant the permissions (INSERT, SELECT, UPDATE,
DELETE) on a specific table to different user accounts.
Syntax:
WITH GRANT OPTION: When any user got the permissions on a specific table from other user
with this option, then that user can grant the permissions on that same table to another user
account. At that time sub user acts as owner.
Email: cm.bolla@gmail.com
SQL Material
24
Ex:
From the above statement RAMESH user account got all permissions on EMP table from SA user
account. Mean time RAMESH can give the permissions on EMP to another user account because
he got the permissions WITH GRANT OPTION.
Ex:
Now SURESH can perform select and insert operations on EMP table.
But SURESH cannot perform update and delete operations on EMP table because he does not
have the corresponding permissions.
Revoke Statement: This statement is used to revoke the permissions (INSERT, SELECT, UPDATE,
DELETE) on a specific table from different user accounts.
Syntax:
CASCADE: Using this option we can destroy the communication link between user accounts more
over from the main user it self we can revoke the permissions from all sub users.
Ex:
The above statement revokes the permissions on EMP table from RAMESH and SURESH.
Now RAMESH and SURESH users cannot access EMP table.
TCL:
Transaction is nothing but a unit of work. We can control these transactions using the following
statements
ROLLBACK Statement
COMMIT Statement
SAVE TRAN [SACTION]
Email: cm.bolla@gmail.com
SQL Material
25
Ex:
SET IMPLICIT_TRANSATIONS ON
SELECT * FROM EMP
DELETE FROM EMP
SELECT * FROM EMP
ROLLBACK
SELECT * FROM EMP
ROLLBACK TRAN
Ex:
BEGIN TRAN
INSERT INTO DEPT VALUES (50,’TRA’,’AUS’)
GO
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=11
GO
DELETE FROM STUDENT WHERE SNO=101
ROLLBACK TRAN
The ROLLBACK statement cancels INSERT on Dept, UPDATE on EMP and DELETE on Student
tables.
Email: cm.bolla@gmail.com
SQL Material
26
COMMIT Statement: This statement makes a transaction permanent. It is not possible to rollback
the committed transaction.
Ex:
The COMMIT statement deletes the data from EMP permanently. It is not possible to ROLLBACK
the delete operation.
Ex:
BEGIN TRAN
INSERT INTO DEPT VALUES (50,’TRA’,’AUS’)
GO
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=11
GO
DELETE FROM STUDENT WHERE SNO=101
COMMIT TRAN
The above COMMIT TRAN makes all three transactions permanent. We cannot ROLLBACK the
transactions.
BEGIN TRAN
SAVE TRAN A
INSERT INTO DEPT VALUES (50,’TRA’,’AUS’)
SAVE TRAN B
UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=11
SAVE TRAN C
DELETE FROM STUDENT WHERE SNO=101
Operators:
Email: cm.bolla@gmail.com
SQL Material
27
1. +:
2.-:
3.*:
4. /:
=, <> or ! =,>,>=,<,<=
1. =:
2. <> or! =:
3.>:
4.>=:
5. <:
6. <=:
Email: cm.bolla@gmail.com
SQL Material
28
1. And:
2. Or:
Not between:
Ex: select*from EMP where sal not between 2000 and 5000
Not in:
Email: cm.bolla@gmail.com
SQL Material
29
Alias:
Alias is temporary
Ex:
Inbuilt functions:
1. Sum ():
2. Average ():
3. Max ():
4. Min ():
Email: cm.bolla@gmail.com
SQL Material
30
Note:
1. Count Function doesn’t consider null as a value.
2. COUNT function does not count the rows of the column whose data type is BIGINT, In
such situations we have to use COUNT_BIG function
7. Variance ():
DISTINCT ( ): This function displays the different values available for a specific column. It
considers one NULL value.
DIFF_VALUES
10
20
NO_OF_ROWS
2
2. Numeric functions:
1. Absolute:
O/p: 9.5
2. Ceiling:
O/p: 10
3. Floor:
Email: cm.bolla@gmail.com
SQL Material
31
O/p: 9
4. Square root:
O/p: 12
5. Power:
O/p: 27(3*3*3)
6. Square:
O/p: 9(3*3)
7. Pi ():
Select pi ()
O/p: 3.14(22/7)
8. Log:
O/p: 0.693147180559945
9. Exp:
O/p: 7.38905609893065
15
Email: cm.bolla@gmail.com
SQL Material
32
16
SELECT ROUND (16.816)
17
SELECT ROUND (21.132,1)
21.1
SELECT ROUND (25.143)
25
1. Length:
O/p: 9
2. Upper:
O/p: HYDERABAD
3. Lower:
O/P: hyderabad
4. Reverse:
O/p: Malayalam
O/p: loohcs
5. Replace:
Email: cm.bolla@gmail.com
SQL Material
33
O/p: cyberabad
6. Substring:
O/p: derab
O/p: 65
O/p: 97
O/p: b
1. Getdate ():
Select getdate ()
2. Getutcdate ():
Select getutcdate ()
3. Dateadd:
4. Datediff:
Email: cm.bolla@gmail.com
SQL Material
34
O/p: 73
5. Date part:
O/p: 2010
O/p: 4
O/p: 20
6. Date name:
O/p: Tuesday
Set operators:
a= {1, 2, 3}
b= {3, 4, 5}
1. A union B= {1, 2, 3, 4, 5}
3. A intersect B= {3}
1. Union:
Email: cm.bolla@gmail.com
SQL Material
35
2. Union all:
3. Intersect:
4. Except:
Group by clause:
Used to divide the table into number of subgroups based on a specific column.
If column contains similar data then only we can use it into group by clause
Display max and min salaries of employees who are working in different deptno's of EMP
table
Ex 2: SELECT DEPTNO, MAX (SAL) AS HISAL, MIN (SAL) AS LOSAL, SUM (SAL) AS TOTSAL, AVG
(SAL) AS AVGSAL FROM EMP
GROUP BY DEPTNO
Having clause:
Email: cm.bolla@gmail.com
SQL Material
36
It is an arithmetical expression
It can be used as an extension of group by clause and we can’t use where clause after
group by clause
This clause is used to evaluate a condition with group by clause. Generally for evaluating
conditions we will use WHERE clause, but where clause does not support by group by
clause.
Order by clause:
Ascending:
Descending:
Clause precedence:
1. Where clause
2. Group by clause
3. Having clause
4. order by clause
Joins:
Email: cm.bolla@gmail.com
SQL Material
37
Two tables are there, they are EMP and DEPT am creating joins between them
Both tables contains a common column i.e. deptno, so that we can create Joins between
EMP, DEPT tables
Types of JOINS:
Ex:
It retrieves condition satisfies and non satisfied data from left side table of the condition i.e. EMP,
it retrieves only condition satisfied data from right side table of the condition i.e. DEPT
It retrieves condition satisfied from left side table of the condition i.e. EMP, it retrieves condition
satisfied data and non satisfied data from right side table of the condition i.e. DEPT
Email: cm.bolla@gmail.com
SQL Material
38
It retrieves condition satisfied and non satisfied data from both tables.
3. Non-equi join: EMP table contains a column sal, in SALGRADE table, we got two columns losal
and hisal so that we can define a join condition.
a= (1, 2, 3)
b= (4, 5, 6)
A*B=3*3=9
Ex:
SUB-QUERIES:
Syn:
Types:
Email: cm.bolla@gmail.com
SQL Material
39
Select max (sal) from EMP where sal< (select max (sal) from EMP)
Select max (sal) from EMP where sal< (select max (sal) from EMP where
Sal< (select max (sal) from EMP))
Ex:
Select max (sal) from EMP e where n= (select count (distinct (sal)) from EMP b
where e.sal<b.sal)
n=n-1
Select min (sal) from EMP e where n= (select count (distinct (sal)) from
EMP b where e.sal>b.sal)
Email: cm.bolla@gmail.com
SQL Material
40
I want to retrieve deptno 20 data from EMP table, for that I want Satisfy the condition in dept
table
Ex:
Select*from EMP where deptno= (select deptno from DEPT where dname='accounting')
Note: If a sub query sends multiple values to its nearest main query then we have to use IN
operator between Main query and Sub query.
Ex: WAQ to display employee details, who are working under RAM dept.
SELECT * FROM EMP WHERE DEPTNO= (SELECT DEPTNO FROM EMP WHERE ENAME=’RAM’)
Ex: WAQ To display employee details, whose salary is greater than highest salary of 10 th
department
SELECT * FROM EMP WHERE SAL> (SELECT MAX (SAL) FROM EMP WHERE DEPTNO=10)
Ex: WAQ To display employee details, whose salary is greater than average salary of RAM
department
SELECT * FROM EMP WHERE SAL> (SELECT AVG (SAL) FROM EMP WHERE DEPTNO=
SELECT DEPTNO FROM EMP WHERE ENAME=’RAM’)
Syn:
Ex:
Ex: (Oracle)
Syn:
Email: cm.bolla@gmail.com
SQL Material
41
Ex:
Views:
A View is nothing but an image table or virtual table, which is created for a base table. A view can
be created by taking all values from the base table or by taking only selected values from base
table. There are two types’ views available in SQL Server.
1. Simple Views
2. Complex Views
Note: If we perform any modifications in base table, then those modifications automatically
effected in view and vice-versa.
1. Simple Views: Creating View by taking only one single base table.
Syntax:
Ex:
The above insert statement inserts the values into base table EMP as well as into view V1.
Ex:
The above insert statement inserts the values into base table EMP as well as into view
V2.
Email: cm.bolla@gmail.com
SQL Material
42
The above insert statement inserts the values into only base table EMP but not into view
V2 because according to the definition of V2 user supplied values are invalid values. It means
invalid values are inserting into base table EMP. To stop this kind of operations we have to create
the view with ‘WITH CHECK OPTION’.
Ex:
The above insert statement cannot insert the values into base table EMP as well as into view V3.
SP_HELPTEXT: This stored procedure is used to display the definition of a specific view.
Syntax:
SP_HELPTEXT VIEWNAME
Ex: SP_HELPTEXT V1
WITH ENCRYPTION: Once we create any view with ‘WITH ENCRYPTION’ then we cannot find the
definition of that particular view using SP_HELPTEXT stored procedure because this encryption
option hides the definition.
Ex:
SP_HELPTEXT V4
Ex:
Email: cm.bolla@gmail.com
SQL Material
43
SP_HELPTEXT V4
2. Complex Views:
Ex:
SQL SERVER enables users to create views based on another view. We can create view based on
another view up to 32 levels
Syntax:
Ex:
Indexes:
Indexes in SQL server is similar to index in text book... Indexes are used to improve the
performance of queries.
Email: cm.bolla@gmail.com
SQL Material
44
1. The columns which are not used frequently used in where clause.
2. Columns containing the duplicate and null values
3. Columns containing images, binary information, and text
information.
TYPES OF INDEXES:
CLUSTERED INDEX
NON-CLUSTERED INDEX
CLUSTERED INDEX: only one clustered index is allowed per table. The order of values in a table
order of values in index is also same. When cluster index is created on table data is arranged in
ascending order cluster index will occupy 5% of the table.
Syntax:
Ex:
CREATE CLUSTERED INDEX CI ON EMP (EMPNO)
Note: If we want to maintain unique values in clustered/non clustered indexed column then
specify UNIQUE keyword along with CLUSTERED INDEX/NONCLUSTERD INDEX
NONCLUSTERED INDEX: It is the default index created by the server the physical order of the
data in the table is different from the order of the values in index. Max no. Of non-clustered
indexed allowed for table is 249
Syntax:
CREATE [UNIQUE] NONCLUSTERED INDEX INDEXNAME
ON TABLENAME (COLUMN1…)
Ex:
CREATE NONCLUSTERED INDEX NCI ON EMP (ENAME, SAL)
Ex:
CREATE UNIQUE NONCLUSTERED INDEX UI ON DEPT (DNAME)
COMPOSITE INDEX: If a Unique NonClustered index is created on more than one column then
that concept is called composite index.
Email: cm.bolla@gmail.com
SQL Material
45
DEPTNO DNAME
10 SALES
20 HR
30 IR
10 HR (Accepted)
20 SALES (Accepted)
30 IR (Repeated, Not accepted)
SP_HELPINDEX: This stored procedure is used to display the list of indexes, which have been
placed on different columns of a specific table.
Ex:
Synonym:
It is a database object
It will not occupies any space, just it is a second name of the table
Trough synonyms we can impose securities i.e. we can hide actual table names
Retrieving data:
Dropping:
SQLSERVER LOCKS:
Email: cm.bolla@gmail.com
SQL Material
46
1. Intent
Intent lock shows the future intention of SQL Server's lock manager to acquire locks on a specific
unit of data for a particular transaction. SQL Server uses intent locks to queue exclusive locks,
thereby ensuring that these locks will be placed on the data elements in the order the
transactions were initiated.
Types: Intent locks are 3 types……
Intent shared (IS): IS locks indicate that the transaction will read some (but not all) the resources
in the table or page by placing shared locks.
Intent exclusive (IX): IX locks indicate that the transaction will modify some (but not all)
resources in the table or page by placing exclusive locks.
Shared with intent exclusive (SIX): SIX locks indicate that the transaction will read all resources,
and modify some (but not all) of them. This will be accomplished by placing the shared locks on
the resources read and exclusive locks on the rows modified. Only one SIX lock is allowed per
resource at one time; therefore, SIX locks prevent other connections from modifying any data in
the resource (page or table), although they do allow reading the data in the same resource.
2. Shared
Shared locks (S) allow transactions to read data with SELECT statements. Other connections are
allowed to read the data at the same time; however, no transactions are allowed to modify data
until the shared locks are released.
3. Update
Update locks (U) are acquired just prior to modifying the data. If a transaction modifies a row,
then the update lock is escalated to an exclusive lock; otherwise, it is converted to a shared lock.
Only one transaction can acquire update locks to a resource at one time. Using update locks
prevents multiple connections from having a shared lock that want to eventually modify a
resource using an exclusive lock. Shared locks are compatible with other shared locks, but are not
compatible with Update locks.
4. Exclusive
Exclusive locks (X) completely lock the resource from any type of access including reads. They are
issued when data is being modified through INSERT, UPDATE and DELETE statements.
5. Schema
Schema modification locks (Sch-M) are acquired when data definition language statements, such
as CREATE TABLE, CREATE INDEX, ALTER TABLE, and so on are being executed. Schema stability
locks (Sch-S) are acquired when store procedures are being compiled.
6. Bulk Update
Bulk update locks (BU) are used when performing a bulk-copy of data into a table with TABLOCK
hint. These locks improve performance while bulk copying data into a table; however, they reduce
concurrency by effectively disabling any other connections to read or modify data in the table
CREATING DEFAULT: Default is one of the database objects used to declare default values
globally.
Syntax:
Email: cm.bolla@gmail.com
SQL Material
47
Ex:
Syntax:
Ex:
Syntax:
SP_UNBINDEFAULT ‘TABLENAME...COLUMN’
SP_UNBINDEFAULT ‘ DEPT.LOC’
SP_UNBINDEFAULT ‘ EMP.ENAME’
Syntax:
DROP DEFAULT D1
CREATING RULES: Rule is just check constraint but it is placed on columns globally.
Email: cm.bolla@gmail.com
SQL Material
48
Syntax:
Ex:
ERROR
DROP RULE R1
TSQL Programs:
Types:
1. Local variable: once we declared local variable then it can be used into single program
Ex: @x int
2. Global variable: once we declared global variable then it can be used into many no. of
programs
Email: cm.bolla@gmail.com
SQL Material
49
Ex: 1, 2,3,4,5
Note: tsql programs also known as tsql batches, these are two types
1. Named batches
2. Unnamed batches
Structure:
Declare
Declaration and initiation of variables
Begin
Body of the program
End
1. Declare:
User can declare variables according to the requirement of the batch and can assign initial
values to variables
2. Begin:
Logic
Exceptions
Conditional statements
Output
Begin
Print 'welcome to database'
End
Email: cm.bolla@gmail.com
SQL Material
50
Declare @x int
Set @x=20
Declare @y int
Set @y=10
Declare @z int
Begin
Set @z=@x+@y
Print @z
End
Conditional Statements:
1. If. Else:
Syn:
Declare
Variable declaration and initiation
Begin
If condition
Output
Else
Output
End
Declare @x int
Set @x=20
Declare @y int
Set @y=10
Begin
If @x>@y
Print 'x is greatest'
Else
Print 'y is greatest'
End
Syn:
Declare
Email: cm.bolla@gmail.com
SQL Material
51
Declare @x int
Set @x=20
Declare @y int
Set @y=10
Declare @z int
Set @z=5
Begin
If @x>@y and @x>@z
Print 'x is greatest'
Else if @y>@x and @y>@z
Print 'y is greatest'
Else
Print 'z is greatest'
End
3. While:
Syn:
Declare
Variable declaration and initiation
While condition
Begin
Body of the program
End
Email: cm.bolla@gmail.com
SQL Material
52
Cursors:
Cursor is a logical area, which is used to retrieve a particular nth record. Selecting a particular nth
record is not possible through physical area (Table). In such situations one logical area (Cursor) we
can create and then we can select a particular nth record. Cursors are used to store transaction
information temporarily.
Types of Cursors:
1. STATIC CURSOR
2. DYNAMIC CURSOR
3. KEYSET CURSOR
4. FORWARD_ONLY CURSOR
DEPT_TABLE:
Syntax:
OPEN CURSORNAME
CLOSE CURSORNAME
DEALLOCATE CURSORNAME
Email: cm.bolla@gmail.com
SQL Material
53
NEXT: Fetches next record from the current position of the cursor
PRIOR: Fetches previous record from the current position of the cursor
ABSOLUTE N: Fetches nth record from the top of the cursor if n is positive fetches the nth record
from bottom of the cursor if n is negative. Where n is an integer
RELATIVE N: Fetches nth next record from current position of the cursor if n is positive fetches
nth previous record from the current position of the cursor if n is negative where n is an integer.
1. STATIC CURSOR:
This is the logical area in which dynamic updations not possible. If we want those updations in
logical area we close the cursor and we need to reopen it.
1.
OPEN SC
CLOSE SC
OPEN SC
Email: cm.bolla@gmail.com
SQL Material
54
40 A/C MUM
CLOSE SC
DEALLOCATE SC
2. DYNAMIC CURSOR:
This is the logical area in which dynamic updations possible. We need to close and reopen the
cursor for the modified values
Ex:
DECLARE DC CURSOR DYNAMIC FOR SELECT * FROM DEPT
OPEN SC
CLOSE DC
DEALLOCATE DC
Note: ABSOLUTE N will not be supported by the dynamic cursor because dynamic updations are
possible.
3. KEYSET CURSOR:
Email: cm.bolla@gmail.com
SQL Material
55
This is the logical area, which is useful only when there is a primary key in the table. This logical
area holds only Primary key column values. Based on the key column values in the logical area
(Cursor) the rest column values are coming from physical area (Table).
Ex:
OPEN KC
CLOSE KC
OPEN KC
CLOSE KC
DEALLOCATE KC
Note: Dynamic updations are not possible on key column of the keyset cursor, we have to close
the cursor and we need to reopen it for the modified values.
4. FORWARD_ONLY CURSOR:
This is the most unused logical area because it supports only NEXT operation.
Ex:
DECLARE FC CURSOR FORWARD_ONLY FOR SELECT * FROM DEPT
OPEN FC
Email: cm.bolla@gmail.com
SQL Material
56
15 SALES HYD
CLOSE SC
DEALLOCATE FC
NOTE:
If the cursor does not found any value in its searching process then it will display the
corresponding column values.
CLOSE SC
DEALLOCATE SC
OUTPUT:
20 HR CHE
Stored Procedures:
It is a database object
After successful compilation it will be stored into a precompiled programming unit
Email: cm.bolla@gmail.com
SQL Material
57
So that with out compilation we can use same stored procedure any number of times
Types:
Ex:
sp_tables
sp_helptable <TN>
sp_helpdb <database name>
sp_rename
sp_addumpdevice
Note: stored procedure can return multiple values through its output parameter
Syntax:
Email: cm.bolla@gmail.com
SQL Material
58
Drop:
Programs:
Execution:
Result:
Select*from dept
Create a stored procedure to update dname, loc according to the given deptno of dept
table
Execution:
Result:
Select*from dept
Note: The number of values supplied through EXEC statement must be equal to the number
parameters.
Email: cm.bolla@gmail.com
SQL Material
59
CREATE PROCEDURE P1
AS
BEGIN
SELECT * FROM EMP
END
EXEC P1
Write a procedure to select the data from EMP table based on user supplied DEPTNO.
EXEC P2 20
EXEC P3
Output: 30
EXEC P3 25, 45
Output: 70
Note: Server will give highest priority to the user supplied values rather than default values.
It is a database object
Email: cm.bolla@gmail.com
SQL Material
60
It is like stored procedure after successful compilation it will stored into database as a pre
compiled programming unit
User’s gets reusability facility i.e. without compilation users can go for execution
1. Scalar valued functions: These functions will return a scalar value to the calling environment
Syntax:
CREATE FUNCTION < FUNCTION_NAME> (@PARA 1 DATA TYPE ,
@ PARA 2 DATATYPE…)
RETURNS <DATATYPE>
AS
BEGIN
DECLARE @VARIABLE DATATYPE
--------
----------
RETURN @VARIABLE
END
Note: The number of values supplied through PRINT/SELECT statement must be equal to the
number parameters.
Email: cm.bolla@gmail.com
SQL Material
61
SET @C = @A * @B
RETURN @C
END
Write function to find the net salary of an employee read EMPNO though parameter and
display the net to return value
PRINT/SELECT DBO.F2(22)
2. Table valued function: These functions will return entire table to the calling environment.
Syntax:
CREATE FUNCTION <FUNCTION_NAME> (PARA 1 DATA TYPE ……….)
RETURNS TABLE
AS
BEGIN
<FUNCTION BODY>
RETURN (SELECT STATEMENT)
END
Email: cm.bolla@gmail.com
SQL Material
62
ENAME DNAME
SMITH RESEARCH
MILLER ACCOUNTING
No
Note: Convert is inbuilt function used to convert data from one data type to another
Email: cm.bolla@gmail.com
SQL Material
63
Drop:
Syn:
TRIGGERS:
DML Triggers:
DML triggers respond to user INSERT, UPDATE, DELETE operations against a table or a view.
When a data modification event occurs, the trigger performs a set of actions defined within the
trigger. Similar to stored procedures, triggers are defined in Transact-SQL and allow a full range
of activities to be performed.
A DML trigger can be defined specifically as FOR UPDATE, FOR INSERT, FOR DELETE, or any
combination of the three. UPDATE triggers respond to modifications against one or more
columns within the table, INSERT triggers respond to new data being added to the database, and
DELETE triggers respond to data being deleted from the database.
There are two types of DML triggers: AFTER and INSTEAD OF.
AFTER triggers are only allowed for tables, and they execute after the data modification has been
completed against the table.
INSTEAD OF triggers execute instead of the original data modification and can be created for
both tables and views.
DML triggers allow you to perform actions in response to data modifications in a table.
For example, you can create a trigger that populates an audit table based on the operation
performed, or perhaps use the trigger to decrement the value of a quantity. Although this ability
to trigger actions automatically is a powerful feature, there are a few things to keep in mind
before your use of triggers proliferates:
• Triggers can often become a hidden and hence forgotten problem. When troubleshooting
Performance or logical issues, DBAs can forget that triggers are executing in the background.
Email: cm.bolla@gmail.com
SQL Material
64
Make sure that your use of triggers is “visible” in your data documentation.
• If you can ensure that all your data modifications flow through a stored procedure, I would
strongly recommend you perform all activities within the stored procedure, rather than use a
Trigger. For example, if you need to update a quantity in a related table, after inserting a sales
record; why not put this logic in the stored procedure instead? The advantages are manageability
(One place to look) and supportability (one place to troubleshoot), when the Procedure needs
modifications or performs unexpected actions.
• Always keep performance in mind and this means writing triggers that execute quickly.
Long-running triggers can significantly slow down data modification operations. Take particular
care in putting triggers into databases with frequent data modifications.
• Non-logged updates do not cause a DML trigger to fire (for example WRITETEXT, TRUNCATE
TABLE and bulk insert operations).
• Constraints usually run faster than a DML trigger, so if your business requirements can be
fulfilled by a constraint, use constraints instead. AFTER triggers run after the data modification
has already occurred, so they cannot be used to prevent a constraint violation.
• Don’t allow result sets from a SELECT statement to be returned within your trigger. Most
applications can’t consume these in an elegant fashion, and embedded queries can hurt the
Trigger’s performance.
Parts of Trigger:
1. Triggering Statement
2. Triggering Restriction
3. Triggering Action
Note: Triggering Action is different from remaining parts, because Trigger fires implicitly
whenever an event occurs against to the Triggering Condition.
Things to Observe:
When user creates an after Trigger on any table for INSERT operation then server
arranges a temporary table “INSERTED” for holding recently inserted values.
When user creates an after Trigger on any table for DELETE operation then server
arranges a temporary table “DELETED” for holding recently deleted values.
When user creates an after Trigger on any table for UPDATE operation then server
arranges two temporary tables “INSERTED, DELETED” for holding old and new values of
UPDATE operation.
Email: cm.bolla@gmail.com
SQL Material
65
Drop:
Result:
Create a trigger for copying data from Temp table to Original table
Email: cm.bolla@gmail.com
SQL Material
66
AS
BEGIN
INSERT INTO orders_archive (order_id, order_date, cust_id)
SELECT order_id, order_date, cust_id FROM DELETED
End
Note:
Ex:
Instead of Trigger:
Ex:
The above trigger fires automatically and shows a message THESE OPERATIONS ARE NOT
ALLOWED, when user try to perform INSERT, UPDATE, DELETE operations on DEPT table.
These triggers are fired when user performs DDL operations in the database and these triggers
belong to database. It means we can define triggers on the current database.
Syntax:
Email: cm.bolla@gmail.com
SQL Material
67
END
1.
USE PUBS
2.
USE PUBS
%TYPE data type No equivalent The %TYPE data type of Oracle lets you create a variable and
have that variable's data type be defined by a table or view
column or a PL/SQL package variable.
Email: cm.bolla@gmail.com
SQL Material
68
DECODE() function CASE expression DECODE can be conveniently simulated using the T-SQL CASE
expression. Here's an example:
SELECT Sport,
CASE Sport
WHEN 'Cricket' THEN 'England'
WHEN 'Hockey' THEN 'India'
WHEN 'Base Ball' THEN 'America'
ELSE NULL
END AS 'Originating Country'
FROM Sports
DESCRIBE sp_help or There are a lot of alternatives for Oracle's DESCRIBE, in SQL
sp_columns Server. You could use the system stored procedure sp_help for
detailed information about a table's columns and other
properties.
DUAL table No equivalent There is no DUAL table in SQL Server. In fact, you don't need
one in SQL Server, as you can have a SELECT statement without
a FROM clause.
SELECT 'Something'
FROM DUAL
Email: cm.bolla@gmail.com
SQL Material
69
SELECT 'Something'
If you are porting some code from Oracle into SQL Server and if
you don't want to remove all references to DUAL table, then just
create a DUAL table in your database using the following
commands:
INTERSECT Not supported Use EXISTS clause to generate the same result.
operator
The following example illustrates the simulation of Oracle's
INTERSECT operator:
MINUS operator Not supported Use NOT EXISTS clause in your SELECT statement to generate
the same result.
Nested tables Not supported Oracle 8i and prior versions didn't support this feature and is
Email: cm.bolla@gmail.com
SQL Material
70
Packages Not supported No equivalent in SQL Server for Oracle's Packages and Package
variables concept
PL/SQL T-SQL Every database product implements and extends the standard
PROGRAMMING SQL. Oracle's implementation of SQL is called PL/SQL, while
Microsoft's is called T-SQL (Transact-SQL)
Row level security No equivalent Though there is no inbuilt support in SQL Server for row level
permissions, you can implement it using view and system
functions.
rownum pseudo No equivalent Though there is no rownum or rowid in SQL Server, there are
column several ways in which a row number can be generated.
Email: cm.bolla@gmail.com
SQL Material
71
SELECT...FOR UPDLOCK hint Use the locking hint UPDLOCK in your SELECT statement.
UPDATE
See SQL Server Books Online for more information.
SQL *Plus Query Analyzer/ For connecting to SQL Server and executing queries and
SSMS modifying data, use the built-in Query Analyzer. It is much more
powerful and friendlier than Oracle's SQL *Plus
START No equivalent Though there's no direct equivalent in T-SQL for Oracle's START
WITH...CONNECT WITH...CONNECT BY, there are several ways and efficient
BY clause techniques for processing and querying hierarcical data.
Synonym Views You can simulate Oracle Synonyms in SQL Server using Views.
For example, the following creates a view that returns the
OrderID and OrderDate from Orders table.
Now you can select data from the view, using the following
SELECT statement:
Email: cm.bolla@gmail.com
SQL Material
72
SELECT table_name
FROM TABS
Every new version of SQL Server comes with several T-SQL features and enhancements.
SQL Server 2008 is no exception. In the newest version of SQL Server, Microsoft has responded to
developer requests in a big way. SQL Server 2008 supports brand new developer convenience
features like single statement declaration and initialization, new data types to manipulate and
query date-based and spatial data, new statements like MERGE that add much needed
functionality to T-SQL and a whole lot more. Once you’ve made the move to SQL Server 2008,
you’ll undoubtedly want to take advantage of the new features and functionality to solve
common problems.
The first of these new features is single statement variable declaration and initialization. In the
past, developers had to declare new variables in one or more DECLARE statements and assign
values to the variables in one or more SET or SELECT statements as shown in below Listing.
With single statement declaration and initialization, you can combine these two steps into a
single step as shown in below Listing
Email: cm.bolla@gmail.com
SQL Material
73
T-SQL has further improved with the addition of several C-Style assignment operators.
Operator Description
+= Addition with assignment, or string
concatenation with assignment
-= Subtraction with assignment
*= Multiplication with assignment
/= Division with assignment
%= Modulo with assignment
Ex:
SYNTAX:
EX:
Like in SQL Server 2005 we need not to write multiple INSERT statements for multiple records.
With in single INSERT statement we can insert multiple records into the table at a time
4. MERGE Statement
Email: cm.bolla@gmail.com
SQL Material
74
Merge Statement is a combination statement that can perform INSERT, UPDATE, DELETE
statements based on whether rows that match the selection criteria exist in the target table or
not.
This Merge statement takes Target and Source Tables, When Source rows are matched with
Target it will update the rows of source table into target table otherwise it will insert the rows
of source table into target table. Always merge statement takes a temp table as its source and
base table as its target table. Using this Merge statement we can combine the rows of a
source table to target table.
Syntax:
SQL Server 2008 provides new data types that support storage, manipulation and querying of
new forms of data. Some, like the date data type which stores a simple date with out the time
component. Others like the geometry data type, which allows storage and querying of spatial
data, have only recently addressed.
SQL Server supports four brand new date and time data types, which includes
1. date
2. time
3. datetime2
4. datetimeoffset
The date data type finally allows us to store date only without the time component. It can
also store a much larger range of dates than datetime and smalldatetime data types.
The date data type can handle dates from January 1, 1 CE (0001-01-01) to December 31,
9999 CE (9999-12-31)
Email: cm.bolla@gmail.com
SQL Material
75
Ex:
In contrast to the date data type, the time data type lets you to store time only data.
The range for the time data type is defined on 24 hour clock, from 00:00:00.0000000
through 23:59:59.9999999 with user defined fractional second precision of up to seven
digits.
Ex:
The cleverly named datetime2 data type is an extension to the standard datetime data
type. The datetime2 combines the benefits of the new date and time data types, giving
you the wide date range of the date data type and the greater fractional second
precision of the time data type.
Ex:
The new datetimeoffset data type builds on datetime2 by adding the ability to store
offsets relative to the International Telecommunication Union(ITU) standard for
Coordinated Universal Time(UTC) with your date and time data type.
The hierarchyid data type offers to represent hierarchical data in the database. This new data
type offers built-in support for representing your hierarchical data using one of the simplest
models available: materialized paths
Email: cm.bolla@gmail.com
SQL Material
76
Method Description
GetAncestor(n) Retrieves the nth ancestor of the hierarchyid
node instance
GetDescendent(n) Retrieves the nth descendent of the hierarchyid
node instance
GetLevel() Gets the level of the hierarchyid node instance
in the hierarchy
GetRoot() Gets the root node of the hierarchyid instance
in the hierarchy
IsDescendent(node) Returns 1 if a specified node is descendent
Parse(String) Converts the given canonical string, in forward
slash- separated format to a hierarchyid path.
Reparent(old_root,new_root) Reparents a node by moving nodes from
old_root to new_root
ToString() Converts a hierarchyid instance to a canonical
forward slash-separated string representation
SQL Server 2008 includes two new data types for storing, querying, and manipulating spatial
data.
Geometry
Geography
QUERIES:
Email: cm.bolla@gmail.com
SQL Material
77
6. Display the names of all employees who are working in department number 10.
Select ename from EMP where deptno=10;
7. Display the names of all employees working as clerks and drawing a salary more than 3000.
select ename from EMP where job=’CLERK’ and sal>3000;
8. Display employee number and names for employees who earn commission.
Select empno, ename from EMP where comm is not null and comm>0;
10. Display the names of employees who are working as clerk, salesman or analyst and drawing
a salary more than 3000.
Select ename from EMP where (job=’CLERK’ or job=’SALESMAN’ or job=’ANALYST’)
and sal>3000;
(Or)
Select ename from EMP where job in (‘CLERK’,’SALESMAN’,’ANALYST’) and sal>3000;
11. Display the names of employees who are working in the company for the past 5 years.
Select ename from EMP where sysdate-hiredate>5*365;
12. Display the list of employees who have joined the company before 30 th June 90 or after 31st
dec 90.
Select * from EMP where hiredate between ‘30-jun-1990’ and ‘31-dec-1990’;
14. Display the names of employees whose name starts with alphabet S.
Select ename from EMP where ename like ‘S%’;
15. Display employee names for employees whose name ends with alphabet.
Select ename from EMP where ename like ‘%S’;
16. Display the names of employees whose names have second alphabet A in their names.
Select ename from EMP where ename like ‘_S%’;
17. Display the names of employees whose name is exactly five characters in length.
Select ename from EMP where length (ename) =5;
(Or)
Select ename from EMP where ename like '_____';
18. Display the names of employees who are not working as SALESMAN or CLERK or ANALYST.
Email: cm.bolla@gmail.com
SQL Material
78
27. Display the names of employees in order of salary i.e. the name of the employee earning
lowest salary should appear first.
Select ename from EMP order by sal;
29. Display the details from EMP table in order of EMP name.
Select ename from EMP order by ename;
30. Display empno, ename, deptno, and sal. Sort the output first based on name and within
name by deptno and within deptno by Sal;
Select * from EMP order by ename, deptno, sal;
31. Display name, Sal, hra, pf, da, total Sal for each employee. The output should be in the
order of total Sal, hra 15% of Sal, da 10% of sal, pf 5% of sal total salary will be (sal*hra*da)-
pf.
select ename,sal,sal*15/100 HRA, sal*5/100 PF, sal*10/100 DA,sal+sal*15/100-
sal*5/100+sal*10/100 TOTAL_SALARY from emp
Email: cm.bolla@gmail.com
SQL Material
79
32. Display dept numbers and total number of employees within each group.
select deptno,count(*) from emp group by deptno;
33. Display the various jobs and total number of employees with each job group.
select job, count(*) from emp group by job;
34. Display department numbers and total salary for each department.
select deptno, sum(sal) from emp group by deptno;
35. Display department numbers and maximum salary for each department.
select deptno, max(sal),min(sal) from emp group by deptno;
36. Display the various jobs and total salary for each job.
select job, sum(sal) from emp group by job;
37. Display each job along with minimum sal being paid in each job group.
select job, min(sal) from emp group by job;
38. Display the department numbers with more than three employees in each dept.
select deptno, count(*) from emp group by deptno having count(*)>3;
39. Display the various jobs along with total sal for each of the jobs where total sal is greater
than 40000.
select job, sum(sal) from emp group by job having sum(sal)>40000;
40. Display the various jobs along with total number of employees in each job. The output
should contain only those jobs with more than three employees.
select job, count(*) from emp group by job having count(*)>3;
42. Display the employee number and name of employee working as CLERK and earning
highest salary among CLERKS.
select empno, ename from emp where job='CLERK' and sal=(select max(sal) from
emp where job='CLERK');
43. Display the names of the salesman who earns a salary more than the highest salary of any
clerk.
select ename from emp where job=’SALESMAN’ and sal >
(select max(sal) from emp where job='CLERK');
44. Display the names of clerks who earn salary more than that of James of that of sal lesser
than that of Scott.
Email: cm.bolla@gmail.com
SQL Material
80
select ename from emp where job='CLERK' and sal<(select sal from emp where
ename='SCOTT') and sal>(select sal from emp where ename='JAMES');
45. Display the names of employees who earn a Sal more than that of James or that of salary
greater than that of Scott.
select ename from emp where sal <
(select sal from emp where ename='SCOTT') and sal >
(select sal from emp where ename='JAMES');
46. Display the names of the employees who earn highest salary in their respective
departments.
select * from emp e where sal =
(select max(sal) from emp where deptno=e.deptno)
47. Display the names of employees who earn highest salaries in their respective job groups.
select * from emp e where sal in
(select max(sal) from emp group by job having e.job=job)
48. Display the employee names who are working in accountings dept.
select ename from emp where deptno =
(select deptno from dept where dname=”ACCOUNTING”);
(or)
select ename from emp where deptno in (select deptno from dept where
dname=”ACCOUNTING”);
50. Display the job groups having total salary greater then the maximum salary for managers.
select job, sum(sal) from emp group by job having sum(sal) >
(select max(sal) from emp where job='MANAGER');
53. Replace every occurrence of alphabet A with B in the string Allen’s (user translate function).
select replace('Allens','A','b') from dual;
54. Display the information from EMP table. Wherever job ‘manager’ is found it should be
displayed as boss(replace function).
select empno, ename, replace(job, 'MANAGER', 'Boss') JOB from emp;
Email: cm.bolla@gmail.com
SQL Material
81
55. Display empno, ename, deptno from EMP table. Instead of display department numbers
display the related department name (use decode function).
select e.empno, e.ename, d.dname from emp e,dept d where
e.deptno = d.deptno;
56. Display the common jobs from department number 10 and 20.
select job from emp where deptno=10 and job in(select job from emp where
deptno=20);
(or)
select job from emp where deptno=10 intersect select job from emp where
deptno=20;
57. Display the jobs found in department number 10 and 20 eliminate duplicate jobs.
select distinct(job) from emp where deptno=10 and job in(select job from emp where
deptno=20);
(or)
select job from emp where deptno=10 intersect select job from emp where
deptno=20;
59. Display the details of those who do not have any person working under them.
select empno from emp where empno not in (select mgr from emp where mgr is not
null);
60. Display the details of employees who are in sales dept and grade is 3.
select * from emp where sal>=(select losal from salgrade where grade=3) and
sal<=(select hisal from salgrade where grade=3) and deptno=(select deptno from
dept where dname='SALES');
61. Display those who are not managers and who are managers any one.
select * from emp where empno in(select mgr from emp) union
select * from emp where empno not in(select mgr from emp where mgr is not null);
62. Display those employees whose name contains not less than 4 chars.
Select * from emp where length(ename)>4;
63. Display those departments whose name start with ‘S’ while location name end with ‘O’.
select * from dept where dname like 'S%' and loc like '%O';
Email: cm.bolla@gmail.com
SQL Material
82
65. Display those employees whose salary is more than 3000 after giving 20% increment.
select * from emp where sal*120/100 > 3000;
(or)
select * from emp where sal+sal*20/100 > 3000;
68. Display employee name, deptname, salary and comm. for those Sal in between 2000 to
5000 while location is Chicago.
select empno,ename,deptno from emp where deptno=(select deptno from dept
where loc='CHICAGO') and sal between 2000 and 5000;
69. Display those employees whose salary greater than his manager salary.
select * from emp e where sal>(select sal from emp where empno=e.mgr);
70. Display those employees who are working in the same dept where his manager is working.
select * from emp e where
deptno = (select deptno from emp where empno=e.mgr);
71. Display those employees who are not working under any manger.
select * from emp where mgr is null or empno=mgr;
72. Display grade and employees name for the dept no 10 or 30 but grade is not 4, while
joined the company before 31-dec-82.
select empno,ename,sal,deptno,hiredate,grade from emp e,salgrade s where
e.sal>=s.losal and e.sal<=s.hisal and deptno in(10,30) and grade<>4 and
hiredate<'01-dec-1981';
73. Update the salary of each employee by 10% increments that are not eligible for
commission.
update emp set sal=sal+(sal*10/100) where comm is null;
74. Delete those employees who joined the company before 31-dec-82 while there dept
location is ‘NEW YORK’ or ‘CHICAGO’.
delete from emp where hiredate<'31-dec-1982' and deptno in
(select deptno from dept where loc in('NEW YORK','CHICAGO'));
75. Display employee name, job, deptname, location for all who are working as managers.
select ename,job,dname,loc from emp e, dept d where e.deptno=d.deptno and
empno in (select mgr from emp);
Email: cm.bolla@gmail.com
SQL Material
83
76. Display those employees whose manager names is Jones, and also display there manager
name.
select e.empno, e.ename, m.ename MANAGER from emp e, emp m
where e.mgr=m.empno and m.ename='JONES';
77. Display name and salary of ford if his Sal is equal to high Sal of his grade.
select ename,sal from emp e where ename='FORD' and sal=(select hisal from
salgrade where grade=(select grade from salgrade where e.sal>=losal and
e.sal<=hisal));
78. Display employee name, his job, his dept name, his manager name, his grade and make out
of an under department wise.
select d.deptno, e.ename, e.job, d.dname, m.ename, s.grade from
emp e, emp m, dept d, salgrade s where e.deptno=d.deptno and e.sal between s.losal
and s.hisal and e.mgr=m.empno order by e.deptno;
79. List out all the employees name, job, and salary grade and department name for every one
in the company except ‘CLERK’. Sort on salary display the highest salary.
select empno, ename, sal, dname, grade from emp e, dept d, salgrade s where
e.deptno=d.deptno and e.sal between s.losal and s.hisal and e.job<>'CLERK' order by
sal;
80. Display employee name, his job and his manager. Display also employees who are without
manager.
select e.ename, e.job, m.ename Manager from emp e,emp m where e.mgr=m.empno
union select ename,job,'no manager' from emp where mgr is null;
82. Display the name of those employees who are getting highest salary.
select empno,ename,sal from emp where sal=(select max(sal) from emp);
83. Display those employees whose salary is equal to average of maximum and minimum.
select * from emp where sal=(select (max(sal)+min(sal))/2 from emp);
84. Display count of employees in each department where count greater than 3.
select deptno, count(*) from emp group by deptno having count(*)>3;
85. Display dname where at least 3 are working and display only dname.
select dname from dept where deptno in
(select deptno from emp group by deptno having count(*)>3);
Email: cm.bolla@gmail.com
SQL Material
84
86. Display name of those managers name whose salary is more than average salary of
company.
select ename, sal from emp where empno in(select mgr from emp) and sal > (select
avg(sal) from emp);
87. Display those managers name whose salary is more than an average salary of his
employees.
select ename, sal from emp e where empno in(select mgr from emp) and e.sal>(select
avg(sal) from emp where mgr=e.empno);
89. Find out the number of employees whose salary is greater than there manager salary?
select count(*) from emp e where sal>(select sal from emp where empno=e.mgr);
90. Display those manager who are not working under president but they are working under
any other manager?
select * from emp e where mgr in(select empno from emp where ename<>'KING');
92. Delete those records from EMP table whose deptno not available in dept table?
delete from emp where deptno not in(select deptno from dept);
93. Display those earners whose salary is out of the grade available in Sal grade table?
select * from emp where sal<(select min(losal) from salgrade) or sal>(select
max(hisal) from salgrade);
94. Display employee name, Sal, comm. and whose net pay is greater than any other in the
company?
Select ename, sal, comm from emp where sal+sal*15/100-sal*5/100 +sal*10/100 =
(select max(sal+sal*15/100-sal*5/100+sal*10/100) from emp);
97. Delete those records where no of employee in a particular department is less than 3?
Email: cm.bolla@gmail.com
SQL Material
85
delete from emp where deptno in(select deptno from emp group by deptno having
count(*)>3);
98. Display the department name the no of characters of which is equal to no of employees in
any other department?
Select dname from dept where len (dname) in (select count(*) from emp group by
deptno);
100. Count the no of employees who are working as manager (use set operation)?
select count(*) from emp where empno in(select mgr from emp);
101. Display the name of then dept those employees who joined the company on the same
date?
select empno,ename,hiredate,deptno from emp e where hiredate in (select hiredate
from emp where empno<>e.empno);
102. Display the manager who is having maximum number of employees working under him?
Select mgr from emp group by mgr having count(*)=(select max(count(mgr)) from
emp group by mgr);
103. Produce the output of the EMP table “EMPLOYEE_AND_JOB” for ename and job?
select * from EMPLOYEE_AND_JOB;
104. Print the details of all the employees who are sub ordinate to Blake.
Select * from emp where mgr=(select empno from emp where ename='BLAKE');
105. Display those who working as manager using co related sub query.
Select * from emp where empno in(select mgr from emp);
106. Display those employees whose manger name is Jones and also with his manager name.
Select * from emp where mgr=(select empno from emp where ename='JONES')
union select * from emp where empno=(select mgr from emp where
ename='JONES');
107. Find out how many mangers are there with out listing them.
Select count (*) from EMP where empno in (select mgr from EMP);
109. List out the lowest paid employees working for each manager, exclude any groups where
min sal is less than 1000 sort the output by sal.
Email: cm.bolla@gmail.com
SQL Material
86
select e.ename,e.mgr,e.sal from emp e where sal in(select min(sal) from emp where
mgr=e.mgr) and e.sal>1000 order by sal;
110. find out the all employees who joined the company before their manager.
Select * from emp e where hiredate<(select hiredate from emp where empno=e.mgr);
111. list out the all employees by name and number along with their manager’s name and
number also display ‘No Manager’ who has no manager.
select e.empno,e.ename,m.empno Manager,m.ename ManagerName from emp
e,emp m where e.mgr=m.empno
union
select empno,ename,mgr,'No Manager' from emp where mgr is null;
112. find out the employees who earned the highest Sal in each job typed sort in descending
Sal order.
select * from emp e where sal =(select max(sal) from emp where job=e.job);
113. find out the employees who earned the min Sal for their job in ascending order.
select * from emp e where sal =(select min(sal) from emp where job=e.job) order by
sal;
114. find out the most recently hired employees in each dept order by hire date
select * from emp order by deptno, hiredate desc;
115. display ename, sal and deptno for each employee who earn a Sal greater than the avg of
their department order by deptno
select ename,sal,deptno from emp e where sal>(select avg(sal) from emp where
deptno=e.deptno) order by deptno;
117. display the dept no with highest annual remuneration bill as compensation.
select deptno,sum(sal) from emp group by deptno having sum(sal) = (select
max(sum(sal)) from emp group by deptno);
119. Write a query of display against the row of the most recently hired employee. display
ename hire date and column max date showing.
select empno,hiredate from emp where hiredate=(select max (hiredate) from emp);
120. display employees who can earn more than lowest Sal in dept no 30
select * from emp where sal>(select min(sal) from emp where deptno=30);
Email: cm.bolla@gmail.com
SQL Material
87
121. find employees who can earn more than every employees in dept no 30
select * from emp where sal>(select max(sal) from emp where deptno=30);
select * from emp where sal>all(select sal from emp where deptno=30);
129. OOPS! I forgot to give the primary key constraint. Add it now.
alter table emp add constraint emp_empno primary key (empno);
132. I want to give a validation saying that sal cannot be greater 10,000(note give a name to this
column).
alter table emp add constraint emp_sal_check check (sal<10000);
134. Oh! This column should be related to empno. Give a command to add this constraint
Alter table emp add constraint emp_mgr foreign key(empno);
Email: cm.bolla@gmail.com
SQL Material
88
136. This dept no column should be related to deptno column of dept table
Alter table emp1 add constraint emp1_deptno foreign key (deptno) references dept
(deptno);
137. Create table called as new emp. Using single command create this table as well as to get
data into this table (use create table as)
Select*into newemp from EMP;
138. Create table called as newemp. This table should contain only empno,ename, dname
create table newemp as select empno,ename,dname from emp e , dept d where
e.deptno=d.deptno;
139. Provide a commission to employees who are not earning any commission.
update emp set comm=300 where comm is null;
140. If any employee has commission his commission should be incremented by 10% of his
salary.
update emp set comm=comm*10/100 where comm is not null;
141. Display employee name and department name for each employee.
select ename,dname from emp e, dept d where e.deptno=d.deptno;
142. Display employee number, name and location of the department in which he is working.
Select empno, ename, loc from emp e, dept d where e.deptno=d.deptno;
144. Display the department name along with total salary in each department.
Select deptno, sum(sal) from emp group by deptno;
145. Display the department name and total number of employees in each department.
select deptno,count(*) from emp group by deptno;
Email: cm.bolla@gmail.com
SQL Material
89
Email: cm.bolla@gmail.com