SQLServer Guide
SQLServer Guide
SQLServer Guide
Introduction 3
Databases 22
Tables 32
Data Types 42
Constraints 47
Joins 61
SubQueries 68
Built-in Functions 74
Operators 80
Views 85
Indexes 90
1
Synonyms 93
Normalization 95
Triggers 113
Transactions 125
Locks 128
Cursors 133
Security 136
2
INTRODUCTION
Client/Server Architecture:
3
While SQL Server is designed to work as a sever in a Client/Server
network, it is also capable of working as a stand-alone database directly on the
client. The scalability and easy-to-use features of SQL Server allow it to work
efficiently on a client without consuming too many resources.
To begin with, a brief overview of the relational database model is
provided as the SQL Server database is based on this model.
4
Entity-Relational Model (E-R Model):
Database design representation will be done using E-R model.
Entity:
An entity is a any object, place, person, concept or activity about which an
enterprise records data.
Ex:
Name Price Description
Keyboard 800 Computer Accessories
Mouse 200 Computer Accessories
Attributes:
An attribute is the characteristic property of an existing entity. Attribute
type is the property of entity type, and attribute instance is the property of entity
instance.
An ellipse always represents the attribute.
Ex:
5
The three different types of relationships recognized among various data
stored in the database are:
One-to-one
One-to-Many( or Many-to-One)
Many-to-Many
One-to-One:
Consider for example a set of students in a class. Each student can have
only one Roll number. Similarly each role number can be associated with on
student. This is the case of a one-to-one relationship.
Many-to-One:
One student can register for only one particular course at a time, whereas
a number of students could register for the same course.
Student1
Student3
6
Many-to-Many:
A vendor can sell a number of items and many vendors can sell a
particular item.
Vendor1 Item1
Vendor2 Item2
Database models:
A database model is a theory or specification describing how a database is
structured and used. Several such models have been suggested.
Common models include:
File Management System model
Hierarchical model
Network model
Relational model
Object-relational model
7
Hierarchical model:
In this model data storage is in the form of a parent-child relationship. The
origin of a data tree is the root. Data located at different levels along a particular
branch from the root is called the node. The last node in the leaf is called the
leaf. This model supports One-to-Many relationship.
Hierarchical structures were widely used in the early mainframe database
management systems, such as the Information Management System (IMS) by
IBM, and now describe the structure of XML documents.
Suppose information is required, say 2.1. It is not necessary for the DBMS
to search the entire file to locate the data. Instead, it first follows the level2
branch and fetches the data.
Disadvantages:
It is not possible to enter a new level into the system. As and when such a
need arises the entire structure has to be revamped. Another disadvantage is
that this model does not support Many-to-Many relationship.
Network model:
The network model (defined by the CODASYL specification) organizes data
using two fundamental constructs, called records and sets. Records contain fields
(which may be organized hierarchically, as in the programming
language COBOL). Sets (not to be confused with mathematical sets) define one-
to-many relationships between records: one owner, many members. A record
may be an owner in any number of sets, and a member in any number of sets.
8
The network model is a variation on the hierarchical model, to the extent
that it is built on the concept of multiple branches (lower-level structures)
emanating from one or more nodes (higher-level structures), while the model
differs from the hierarchical model in that branches can be connected to multiple
nodes. The network model is able to represent redundancy in data more
efficiently than in the hierarchical model.
The operations of the network model are navigational in style: a program
maintains a current position, and navigates from one record to another by
following the relationships in which the record participates. Records can also be
located by supplying key values.
Although it is not an essential feature of the model, network databases
generally implement the set relationships by means of pointers that directly
address the location of a record on disk. This gives excellent retrieval
performance, at the expense of operations such as database loading and
reorganization.
Disadvantages:
9
Relational model:
The relational model was introduced by E.F.Codd in 1970 as a way to
make database management systems more independent of any particular
application. It is a mathematical model defined in terms of predicate logic and set
theory.
The products that are generally referred to as relational databases in fact
implement a model that is only an approximation to the mathematical model
defined by Codd.
Three key terms are used extensively in relational database
models: relations, attributes, and domains.
A relation is a table with columns and rows. The named columns of the
relation are called attributes, and the domain is the set of values the attributes
are allowed to take.
The basic data structure of the relational model is the table, where
information about a particular entity (say, an employee) is represented in rows
(also called tuples) and columns. Thus, the "relation" in "relational database"
refers to the various tables in the database; a relation is a set of tuples. The
columns enumerate the various attributes of the entity (the employee's name,
address or phone number, for example), and a row is an actual instance of the
entity (a specific employee) that is represented by the relation. As a result, each
tuple of the employee table represents various attributes of a single employee.
All relations (and, thus, tables) in a relational database have to
adhere to some basic rules to qualify as relations. First, the ordering of
columns is immaterial in a table. Second, there can't be identical tuples
or rows in a table. And third, each tuple will contain a single value for
each of its attributes.
A relational database contains multiple tables, each similar to the one in
the "flat" database model. One of the strengths of the relational model is that, in
principle, any value occurring in two different records (belonging to the same
table or to different tables), implies a relationship among those two records. Yet,
in order to enforce explicit integrity constraints, relationships between records in
tables can also be defined explicitly, by identifying or non-identifying parent-child
relationships characterized by assigning cardinality (1:1, (0)1:M, M:M). Tables
can also have a designated single attribute or a set of attributes that can act as a
"key", which can be used to uniquely identify each tuple in the table.
A key that can be used to uniquely identify a row in a table is called a
primary key. Keys are commonly used to join or combine data from two or more
tables. For example, an Employee table may contain a column
named Location which contains a value that matches the key of a Location table.
Keys are also critical in the creation of indexes, which facilitate fast retrieval of
data from large tables. Any column can be a key, or multiple columns can be
10
grouped together into a compound key. It is not necessary to define all the keys
in advance; a column can be used as a key even if it was not originally intended
to be one.
Object-Relational Model:
An object-relational database (ORD), or object-relational database
management system (ORDBMS), is a database management system (DBMS)
similar to a relational database, but with an object-oriented database model:
objects, classes and inheritance are directly supported in database schemas and
in the query language. In addition, it supports extension of the data model with
custom data-types and methods.
11
SQL SERVER 2008
12
SQL Server 2008 R2:
SQL Server 2008 R2 (formerly codenamed SQL Server "Kilimanjaro") was
announced at TechEd 2009, and was released to manufacturing on April 21,
2010. SQL Server 2008 R2 adds certain features to SQL Server 2008
including master data management system branded as Master Data Services,
a centralized console to manage multiple SQL Server instances, and support for
more than 64 logical processors.
SQL Server 2008 R2 boasts a number of new services, including
PowerPivot for Excel and SharePoint, Master Data Services, StreamInsight,
ReportBuilder 3.0, Reporting Services Add-in for SharePoint, a Data-tier function
in Visual Studio that enables packaging of tiered databases as part of an
application, and a SQL Server Utility named UC (Utility Control POint), part of
AMSM (Application and Multi-Server Management) that is used to manage
multiple SQL Servers.
13
SQL Server Fast Track:
SQL Server Fast Track is specifically for enterprise-scale data warehousing
storage and business intelligence processing, and runs on reference-
architecture hardware that is optimized for Fast Track.
14
Tools:
SQLCMD:
SQLCMD is a command line application that comes with Microsoft SQL
Server, and exposes the management features of SQL Server. It allows SQL
queries to be written and executed from the command prompt. It can also act as
a scripting language to create and run a set of SQL statements as a script. Such
scripts are stored as a .sql file, and are used either for management of databases
or to create the database schema during the deployment of a database.
SQLCMD was introduced with SQL Server 2005 and this continues with
SQL Server 2008. Its predecessor for earlier versions was OSQL and ISQL, which
is functionally equivalent as it pertains to TSQL execution, and many of the
command line parameters are identical, although SQLCMD adds extra versatility.
Visual Studio:
Microsoft Visual Studio includes native support for data programming with
Microsoft SQL Server. It can be used to write and debug code to be executed by
SQL CLR. It also includes a data designer that can be used to graphically create,
view or edit database schemas. Queries can be created either visually or using
code. SSMS 2008 onwards, provides intellisense for SQL queries as well.
15
indexes, or analyze performance. It includes the query windows which provide a
GUI based interface to write and execute queries.
Business Intelligence Development Studio:
Business Intelligence Development Studio (BIDS) is the IDE from Microsoft used
for developing data analysis and Business Intelligence solutions utilizing the
Microsoft SQL Server Analysis Services, Reporting Services and Integration
Services. It is based on the Microsoft Visual Studio development environment but
customizes with the SQL Server services-specific extensions and project types,
including tools, controls and projects for reports (using Reporting
Services), Cubes and data mining structures (using Analysis Services).
Service Broker:
Used inside an instance, it is used to provide an asynchronous
programming environment. For cross instance applications, Service Broker
communicates The Service Broker, which runs as a part of the database engine,
provides a reliable messaging and message queuing platform for SQL Server
applications.
Replication Services:
SQL Server Replication Services are used by SQL Server to replicate and
synchronize database objects, either in entirety or a subset of the objects
present, across replication agents, which might be other database servers across
the network, or database caches on the client side. Replication follows a
publisher/subscriber model, i.e., the changes are sent out by one database server
("publisher") and are received by others ("subscribers"). SQL Server supports
three different types of replication:
Transaction replication
Each transaction made to the publisher database (master
database) is synced out to subscribers, who update their databases with
16
the transaction. Transactional replication synchronizes databases in near
real time.
Merge replication
Changes made at both the publisher and subscriber databases are
tracked, and periodically the changes are synchronized bi-directionally
between the publisher and the subscribers. If the same data has been
modified differently in both the publisher and the subscriber databases,
synchronization will result in a conflict which has to be resolved - either
manually or by using pre-defined policies.
Snapshot replication
Snapshot replication published a copy of the entire database (the
then-snapshot of the data) and replicates out to the subscribers. Further
changes to the snapshot are not tracked.
Analysis Services:
SQL Server Analysis Services adds OLAP and data mining capabilities for SQL
Server databases. The OLAP engine supports MOLAP, ROLAP and HOLAP storage
modes for data. Analysis Services supports the XML for Analysis standard as the
underlying communication protocol. The cube data can be accessed
using MDX queries. Data mining specific functionality is exposed via
the DMX query language.
Reporting Services:
SQL Server Reporting Services is a report generation environment for data
gathered from SQL Server databases. It is administered via a web interface.
Reporting services features a web services interface to support the development
of custom reporting applications. Reports are created as RDL files.
Reports can be designed using recent versions of Microsoft Visual
Studio (Visual Studio.NET 2003, 2005, and 2008) with Business Intelligence
Development Studio, installed or with the included Report Builder. Once created,
RDL files can be rendered in a variety of formats including
Excel, PDF, CSV, XML, TIFF (and other image formats), and HTML Web Archive.
Notification Services:
Originally introduced as a post-release add-on for SQL Server
2000, Notification Services was bundled as part of the Microsoft SQL Server
platform for the first and only time with SQL Server 2005. With Sql Server 2005,
SQL Server Notification Services is a mechanism for generating data-driven
17
notifications, which are sent to Notification Services subscribers. A subscriber
registers for a specific event or transaction (which is registered on the database
server as a trigger); when the event occurs, Notification Services can use one of
three methods to send a message to the subscriber informing about the
occurrence of the event. These methods include SMTP, SOAP, or by writing to a
file in the file system. Notification Services was discontinued by Microsoft with the
release of SQL Server 2008 in August 2008, and is no longer an officially
supported component of the SQL Server database platform.
Integration Services:
SQL Server Integration Services is used to integrate data from different
data sources. It is used for the ETL capabilities for SQL Server for data
warehousing needs. Integration Services includes GUI tools to build data
extraction workflows integration various functionality such as extracting data
from various sources, querying data, transforming data including aggregating,
duplication and merging data, and then loading the transformed data onto other
sources, or sending e-mails detailing the status of the operation as defined by the
user.
18
Programmability:
T-SQL:
T-SQL (Transact-SQL) is the primary means of programming and
managing SQL Server. It exposes keywords for the operations that can be
performed on SQL Server, including creating and altering database schemas,
entering and editing data in the database as well as monitoring and managing the
server itself. Client applications, both which consume data or manage the server,
leverage SQL Server functionality by sending T-SQL queries and statements
which are then processed by the server and results (or errors) returned to the
client application. SQL Server allows it to be managed using T-SQL. For this it
exposes read only tables from which server statistics can be read. Management
functionality is exposed via system-defined stored procedures which can be
invoked from T-SQL queries to perform the management operation. It is also
possible to create linked Server using T-SQL. Linked server allows operation to
multiple server as one query.
19
STRUCTURED QUERY LANGUAGE
SQL is a standard that every database should follow. That means all the
SQL commands should work in all databases. Based on the type of operations we
are performing on the database, SQL is divided into the following types:
Note: DDL commands are AUTO COMMIT. i.e., with the execution of these
commands, the results will be stored directly into the database.
20
Transaction Control Language:
Database Buffer
Commit
Commit
Query Editor
DDL
DML
L
21
DATABASES
Database Architecture:
Microsoft SQL Server 2000 data is stored in databases. The data in a
database is organized into the logical components visible to users. A database is
also physically implemented as two or more files on disk.
When using a database, you work primarily with the logical components
such as tables, views, procedures, and users. The physical implementation of files
is largely transparent. Typically, only the database administrator needs to work
with the physical implementation.
22
Each instance of SQL Server has four system databases (master, model,
tempdb, and msdb) and one or more user databases. Some organizations have
only one user database, containing all the data for their organization. Some
organizations have different databases for each group in their organization, and
sometimes a database used by a single application. For example, an organization
could have one database for sales, one for payroll, one for a document
management application, and so on. Sometimes an application uses only one
database; other applications may access several databases.
Types of Databases:
SQL Server provides two types of Databases.
System Databases
User Defined Databases
23
System Databases:
Along with the installation of SQL Server FOUR databases will be created
automatically called as system databases. They can be used by any user
anywhere from SQL Server.
The System Databases are:
master
The master database records all of the system level information for a SQL
Server system. It records all login accounts and all system configuration
settings. master is the database that records the existence of all other
databases, including the location of the database files. master records the
initialization information for SQL Server; always have a recent backup of
master available.
model
The model database is used as the template for all databases created on
a system. When a CREATE DATABASE statement is issued, the first part of
the database is created by copying in the contents of the model database,
then the remainder of the new database is filled with empty pages.
Because tempdb is created every time SQL Server is started, the model
database must always exist on a SQL Server system.
msdb
The msdb database is used by SQL Server Agent for scheduling alerts and
jobs, and recording operators.
tempdb
tempdb holds all temporary tables and temporary stored procedures. It
also fills any other temporary storage needs such as work tables
generated by SQL Server. tempdb is a global resource; the temporary
tables and stored procedures for all users connected to the system are
stored there. tempdb is re-created every time SQL Server is started so
the system starts with a clean copy of the database
24
Files and Filegroups:
Microsoft® SQL Server™ 2000 maps a database using a set of operating-system
files. All data and objects in the database, such as tables, stored procedures,
triggers, and views, are stored within these operating-system files:
Primary Data File (.mdf)
This file contains the startup information for the database and is used to
store data. Every database has one primary data file.
Secondary Data File (.ndf)
These files hold all of the data that does not fit in the primary data file. If
the primary file can hold all of the data in the database, databases do not
need to have secondary data files. Some databases may be large enough
to need multiple secondary data files or to use secondary files on separate
disk drives to spread data across multiple disks.
Transaction Log File (.ldf)
These files hold the log information used to recover the database. There
must be at least one log file for each database.
Filegroups allow files to be grouped together for administrative and data
allocation/placement purposes. For example, three files (Data1.ndf, Data2.ndf,
and Data3.ndf) can be created on three disk drives, respectively, and assigned to
the filegroup fgroup1. A table can then be created specifically on the filegroup
fgroup1. Queries for data from the table will be spread across the three disks,
thereby improving performance. Files and filegroups, however, allow you to easily
add new files on new disks. Additionally, if your database exceeds the maximum
size for a single Microsoft Windows NT® file, you can use secondary data files to
allow your database to continue to grow.
Creating a Database:
To create a database, determine the name of the database, its owner (the
user who creates the database), its size, and the files and filegroups used to
store it.
Before creating a database, consider that:
Permission to create a database defaults to members of the sysadmin
and dbcreator fixed server roles.
The user who creates the database becomes the owner of the database.
A maximum of 32,767 databases can be created on a server.
The name of the database must follow the rules for identifiers.
25
Creating Database using Navigation:
1. Open the 'Management Studio’ tool and connect to the required
instance of SQL Server with desired authentication.
26
3. Right Click on the ‘Databases’ item and select ‘New Database’ option.
4. Provide a name to the Database and specify the details of primary and log file
and ‘Database Files’ section.
27
Creating a Database Using a Query:
Once the Query Analyzer is opened, in the command window we can write
any command that has to be executed.
Syntax:
Note: ‘Logicalfilename’ is used to identity the file for further modifications and
‘os-filename’ refers the original location where the file is stored in the hard disk.
A maximum size should be specified using the MAXSIZE parameter of the ALTER
DATABASE statement. This prevents the file from growing until the disk space is
exhausted.
Syntax:
Example:
29
To add a file group:
NOTE: The sp_helpdb system stored procedure without a database name reports
Example:
information
sp_helpdbabout
empall the databases in the system.
30
Different options that can be set to database are:
Dbuseonly – only owner of the database can use it.
Example:
Example:
TABLES
DROP DATABASE dbSample
31
TABLES
Tables are database objects that contain all the data in a database. A table
definition is a collection of columns. In tables, data is organized in a row-and-
column format similar to a spreadsheet. Each row represents a unique record,
and each column represents a field within the record.
After you have designed the database, the tables that will store the data
in the database can be created. The data is usually stored in permanent tables.
Tables are stored in the database files until they are deleted and are available to
any user who has the appropriate permissions.
Types of Tables:
Corresponding to the type of data we are storing inside the tables, they
are divided into the following ways:
System Tables
User Tables
Temporary Tables
System Tables:
These are the tables that will come along with the SQL Server database
installation. All these tables will be stored under Master database. They will
provide System level information. Ex: sysobjects, sysusers etc.,
User Tables:
These are the tables that are created by a user. The user who creates the
table will be the owner for that table. In order to get an access to that table,
other users must get corresponding permission from the owner of the table.
Temporary Tables
You can also create temporary tables. Temporary tables are similar to permanent
tables, except temporary tables are stored in tempdb and are deleted
automatically when no longer in use. They will be identified by “#” symbol.
Table Properties
You can define up to 1,024 columns per table. Table and column names must
follow the rules for identifiers; they must be unique within a given table, but you
can use the same column name in different tables in the same database. You
must also define a data type for each column.
Although table names must be unique for each owner within a database, you can
create multiple tables with the same name if you specify different owners for
each.
32
Creating a Table using Navigation:
1. Open the ‘Management Studio’ tool and navigate up to the database
where we want to create the table.
2. Expand ‘Tables’ item that displays list of existing tables.
3. Right click on ‘Tables’ item and select ‘New Table’ option.
4. In the ‘Data Grid’ displayed enter the details of columns such as – column
name, data type, size.
33
Creating a Table using Query:
We can make use of the following syntax to create a table:
34
Example:
Syntax:
Modifying Tables:
After a table is created, you can change many of the options that were defined
for the table when it was originally created, including:
Columns can be added, modified, or deleted. For example, the column
name, length, data type, precision, scale, and nullability can all be
changed, although some restrictions exist. For more information.
PRIMARY KEY and FOREIGN KEY constraints can be added or deleted.
UNIQUE and CHECK constraints and DEFAULT definitions (and objects) can
be added or deleted.
An identifier column can be added or deleted using the IDENTITY or
ROWGUIDCOL property.
35
Renaming a Table:
Syntax:
SP_RENAME <old_tableName>,<new_tableName>
Example:
SP_RENAME employee.emp
Renaming a Column:
Syntax:
SP_RENAME <’ tableName.columnname’>,<’newcolName’>
Example:
SP_RENAME ‘emp.basic_salary’,’sal’
Examples:
Changing datatype
Changing NULLs
36
Adding Columns
Sp_help:
This System Stored Procedure is used to provide description about the
table structure.
Example:
SP_HELP emp
Syntax:
Example:
37
Retrieving Table Data:
The SELECT statement is used to retrieve the data from the table. It is
possible to retrieve all the table data or particular column data. In order to
retrieve complex data from the tables, we can add extra optional clauses to the
select statement.
Note: A maximum of 4096 columns can be specified in a select statement.
Syn:
Ex:
WHERE Clause:
It is used to provide a condition in the select statement. Only those
records that satisfy the condition will be displayed as output. The condition can
be specified based on any column of the table.
Ex:
Output:
Empid ename sal dno
1 E1 25000 20
38
GROUP BY Clause:
It is used to group the table data based on a column. After grouping the
table data, we can able to apply an aggregate function on each group
independently. The aggregations include: COUNT, MIN, MAX, AVG and SUM.
Ex:
Q.1: Get the no.of employees in each department.
Sol:
SELECT dno,count(*) from emp
GROUP BY dno
Output:
HAVING Clause:
Like a ‘Where’ clause, HAVING clause is also used to provide condition
based on the grouped data. The difference between them is :
With WHERE clause, condition can be specified on entire column data at a
time. i.e., before grouping the table data. Whereas, with HAVING clause the
condition can be specified after grouping the table data on each group
independently.
When to use which clause depends on the criteria of the query. If the
criteria doesn’t require grouping, use where clause other wise use having clause.
39
Examples:
Output:
Q.2: Get the department which are having more than one
employee
Sol:
SELECT dno,Count(*) NoOfEmployees from emp
GROUP BY dno HAVING count(dno)>1
Output:
Example: the employee name Samuel with the emp_no “E001” was wrongly
entered as ‘A’ in the table. To correct it, the following statement is used.
UPDATE emp
SET ename=’Samuel’
WHERE empid=1
40
Deleting data from a Table:
To remove rows from a table, DELETE or TRUNCATE statements can be used.
To delete a particular row from the table we have to use DELETE command.
Syntax:
DELETE FROM tablename WHERE condition
Example:
DELETE FROM emp WHERE emp_no=’E002’
To delete all rows from the table, TRUNCATE command can also be
used.
Syntax:
TRUNCATE TABLE tablename
Example:
TRUNCATE TABLE emp
Syntax:
DROP TABLE tablename
Example:
DROP TABLE dept1
41
DATATYPES
The choice of the datatype determines the kind of data that can be stored
in the column and the maximum length of data that can be stored in the column.
SQL Server provides different categories of data types. They are:
Exact numerics Unicode character strings
Approximate numerics Binary strings
Date and time Other data types
Character strings
In SQL Server, based on their storage characteristics, some data types are
designated as belonging to the following groups:
Large value data types: varchar(max), nvarchar(max), and
varbinary(max)
Large object data types: text, ntext, image, varchar(max),
nvarchar(max), varbinary(max), and xml
42
p (precision)
The maximum total number of decimal digits that can be stored, both to
the left and to the right of the decimal point. The precision must be a
value from 1 through the maximum precision of 38. The default precision
is 18.
s (scale)
The maximum number of decimal digits that can be stored to the right of
the decimal point. Scale must be a value from 0 through p. Scale can be
specified only if precision is specified. The default scale is 0; therefore, 0
<= s <= p. Maximum storage sizes vary, based on the precision.
Precision Storage bytes
1-9 5
10-19 9
20-28 13
29-38 17
Character Datatype:
There are three valid datatypes for storing strings. They are:
Char: this is used for storing fixed-length strings. Columns defined as char will
store blanks to fill out a fixed number of characters. The maximum length of a
character column is 8000 bytes.
Varchar: this is used for storing variable length strings. Columns defined as
varchar will truncate blanks to save space.
Text: this is used for storing of virtually unlimited size(upto 2 gigabytes of text
per row.
Binary Datatypes:
These datatypes store strings consisting of binary values.i.e, haxadecima
numbers instead of characters. They are:
Binary: Stores binary data of fixed lengh with a maximum lengh of 8,000 bytes
Varbinary: Stores variable lengh binary data with a maximum length of 8,000
bytes
Image: SQL Server provides a mechanism for storing binary data more than
8000 bytes using image datatypes. For Example, the photograph of the
employees can be stored.
43
DateTime Datatype:
SQL Server enables to store date and time values. Columns using
datetime or smalldatetime will store both date and time.
Unicode Datatype:
Unicode standard includes all the characters that are defined in the
various character sets. Using Unicode data types, a column can store any
character that is defined by the Unicode standard. Unicode data is stored using
nchar, nvarchar, ntext datatypes.
Special DataTypes:
Cursor:
This data type is used for variables or stored procedure OUTPUT parameters that
contain a reference to a cursor. Any variables created with the cursor data type
are nullable.
The operations that can reference variables and parameters having a cursor data
type are:
The DECLARE @local_variable and SET @local_variable statements.
The OPEN, FETCH, CLOSE, and DEALLOCATE cursor statements.
Stored procedure output parameters.
The CURSOR_STATUS function.
The sp_cursor_list, sp_describe_cursor,
sp_describe_cursor_tables, and sp_describe_cursor_columns system
stored procedures.
NOTE: The cursor data type cannot be used for a column in a CREATE TABLE
statement
Sql_variant :.
sql_variant can be used in columns, parameters, variables, and the
return values of user-defined functions. sql_variant enables these database
objects to support values of other data types.
A column of type sql_variant may contain rows of different data types. For
example, a column defined as sql_variant can store int, binary, and char
values. The following table lists the types of values that cannot be stored by
using sql_variant:
44
varchar(max) varbinary(max)
nvarchar(max) xml
text ntext
image timestamp
sql_variant User-defined types
hierarchyid
sql_variant can have a maximum length of 8016 bytes. This includes both the
base type information and the base type value. The maximum length of the
actual base type value is 8,000 bytes.
A sql_variant data type must first be cast to its base data type value before
participating in operations such as addition and subtraction.
sql_variant can be assigned a default value. This data type can also have NULL
as its underlying value, but the NULL values will not have an associated base
type. Also, sql_variant cannot have another sql_variant as its base type.
A unique, primary, or foreign key may include columns of type sql_variant, but
the total length of the data values that make up the key of a specific row should
not be more than the maximum length of an index. This is 900 bytes.
A table can have any number of sql_variant columns.
Table:
Is a special data type that can be used to store a result set for processing
at a later time. table is primarily used is for temporary storage of a set of rows
returned as the result set of a table-valued function.
table variables provide the following benefits:
A table variable behaves like a local variable. It has a well-defined scope.
This is the function, stored procedure, or batch that it is declared in.
Within its scope, a table variable can be used like a regular table. It may be
applied anywhere a table or table expression is used in SELECT, INSERT,
UPDATE, and DELETE statements. However, table cannot be used in the
following statement:
45
CHECK constraints, DEFAULT values and computed columns in the table
type declaration cannot call user-defined functions.
table variables used in stored procedures cause fewer recompilations of
the stored procedures than when temporary tables are used.
Transactions involving table variables last only for the duration of an
update on the table variable. Therefore, table variables require less locking
and logging resources.
46
CONSTRAINTS
47
A constraint can be created using either of the following statements:
CREATE TABLE statement.
ALTER TABLE statement.
CHECK CONSTRAINT:
A CHECK constraint enforces domain integrity by restricting the values to
be inserted in a column. It allows only valid values in a column.
It is possible to define multiple CHECK constraints on a single column.
Syntax:
48
Example:
Ex:
1. create table dept
(dno int,dname char(10),
Dsize int constraint ck_dept_dsize check(dsize>20))
49
Examples:
UNIQUE CONSTRAINT:
Syntax:
50
Examples:
It does not allow two rows to have the same non-null values in a table.
It gets enforced automatically when a UNIQUE index is created.
Multiple UNIQUE constraints can be placed on a table.
51
PRIMARY KEY constraint:
A primary key constraint is defined on a column or a set of columns whose
values uniquely identify the rows in a table. These columns are referred to as
primary key columns. A primary key column cannot contain NULL values since it
is used to uniquely identify rows in a table.
While defining a PK constraint, you need to specify a name for the
constraint. If no name is specified, SQL Server automatically assigns a unique
name to the constraint.
Any column or set of columns that uniquely identifies a row in a table can
be a candidate for the primary key. These set of columns are referred to as
candidate keys. One of the candidate keys is chosen to be the primary key, based
on familiarity and greater usage. The other key, which is not chosen as the
primary key is called as alternate key.
A table should contain only one primary key.
Creating a primary key is very much similar to the unique constraint. In
the syntax of unique, simply replace the keyword unique with a primary key.
Syntax:
OR
52
Example:
53
Composite Primary Key:
In some tables it is not possible to provide the primary key on any single
column of the table. Then check the table data to identify any column
combination, by using which, we can identify different records and other data of
the table. If it is found, make that column as the primary key called as
‘Composite Primary Key’. A maximum of 16 columns can be combined using this
constraint.
Ex:
CREATE TABLE OrderDetails
(ordid int, ino char(2),orddate datetime, cno int, ,
Quantity int, constraint pk_od_ordid_ino
Primary Key(ordid,ino))
Syntax:
54
Example:
The rules regarding the creation of a FOREIGN KEY constraint are as follows:
The no.of columns specified in the foreign key statement must match the
no.of columns in the references clause and must be specified in the same
order.
The foreign key can reference the primary key or a UNIQUE constraint of
another table.
The foreign key constraint that is created using the WITH NOCHECK option
will prevent the foreign key constraint from validating existing data.
ON DELETE CASCADE:
55
Adding a Foreign key:
Syn:
Ex:
CONSTRAINTS vs TRIGGERS:
Each category of data integrity is best enforced through the following
constraints.
Entity integrity is best enforced through the PRIMARY KEY constraint, UNIQUE
constraint and the IDENTITY property.
The IDENTITY property creates an identity column in the table. An identity
column is a primary key column for which numeric values are generated
automatically. Each generated value is different from the previous value, thus
ensuring uniqueness of data in each row at the table. The IDENTITY property also
ensures that while inserting data, the user need not explicitly insert a value for
the identity column.
Domain integrity is best enforced through the DEFAULT constraint, CHECK
constraint and the FOREIGH KEY constraint.
56
RULES AND DEFAULTS
Rules and defaults are objects, which help enforce the data integrity.
These objects are bound to columns or user defined data types to ensure that
only valid values are allowed to insert into the tables.
RULES:
A rule provides a mechanism for enforcing domain constraints for columns
or user defined data types. The rule is applied before any modification is to be
done on the table. In other words, a rule specifies the restriction on the values
for a column or a user defined data type.
Syn:
CREATE RULE rule_name
AS conditional_expression.
example:
CREATE RULE type_rule
AS @typerule IN(‘business’,’mod_cook’, ‘trad_cook’,
‘popular_comp’, ‘psychology’)
More Examples:
57
Information on a rule can be obtained using the sp_help system stored
procedure. The text of a rule can be displayed using the sp_helptext system
stored procedure with the name of the rule as its parameter.
Binding Rules:-
A rule can be bound using the sp_bindrule system stored procedure.
Syntax:
For example:
Sp_bindrule type_rule, ‘titles.type’
Binds the rule, type_rule,to the type column of the titles table
The restrictions on the use of the rules are as follows:
Unbinding Rules:
A rule can be unbound from a column or user-defined datatype using the
sp_unbindrule system stored procedure.
Sp_unbindrule object_name
For example:
Sp_unbindingrule ‘titles.type’
58
DEFAULTS:
Default is a constant value assigned to a column, into which the user need
not insert values.A default can be bound to a column or a user-defined datatype.
Syn:
CREATE DEFAULT default_name
As constant_expression
Binding Defaults
The sp_bindefault system stored procedure is used for binding a default.
The syntax of sp_bindefault is:
For example:
1.CREATE DEFAULT city_default AS ‘Oakland’
2. Sp_default city_default, ‘authors.city’
Creates a default, city_default, and binds the default value, Oakland, to city
column of the authors table.
The statement
59
Unbinding Defaults:
Defaults can be unbound from a column or user defined datatype using
the sp_unbindefault system stored procedure.
The syntax of sp_unbindefault is:
Sp_unbindefault object_name
For example:
Sp_unbindefault ‘authors.city’
Unbinds the default specified on the city column of the authors table.
The sp_rename system stored procedure can be used for renaming rules
and defaults.
The DROP RULE and DROP DEFAULT statement can be used to drop a rule
and default respectively. A rule or default must be unbound from the column or
the user-defined data type before it is dropped.
60
JOINS
By using joins, you can retrieve data from two or more tables based on
logical relationships between the tables. Joins indicate how Microsoft SQL Server
should use data from one table to select the rows in another table.
A join condition defines the way two tables are related in a query by:
Specifying the column from each table to be used for the join. A typical
join condition specifies a foreign key from one table and its associated key
in the other table.
Specifying a logical operator (=, <>, and so on) to be used in comparing
values from the columns.
Joins can be specified in either the FROM or WHERE clauses. The join
conditions combine with the WHERE and HAVING search conditions to control the
rows that are selected from the base tables referenced in the FROM clause.
Specifying the join conditions in the FROM clause helps separate them from
any other search conditions that may be specified in a WHERE clause, and is the
recommended method for specifying joins. A simplified SQL-92 FROM clause join
Syntax:
SELECT columnList
FROM first_table join_type second_table [ON (join_condition)]
Join_type specifies what kind of join is performed: an inner, outer, or cross join.
join_condition defines the predicate to be evaluated for each pair of joined rows.
This is an example of a FROM clause join specification:
Although join conditions usually have equality comparisons (=), other
comparison or relational operators can be specified, as can other predicates
When SQL Server processes joins, the query engine chooses the most
efficient method (out of several possibilities) of processing the join. Although the
physical execution of various joins uses many different optimizations, the logical
sequence is:
The join conditions in the FROM clause are applied.
The join conditions and search conditions from the WHERE clause are
applied.
The search conditions from the HAVING clause are applied.
61
Types of Joins:
Join conditions can be specified in either the FROM or WHERE clauses;
specifying them in the FROM clause is recommended. WHERE and HAVING
clauses can also contain search conditions to further filter the rows selected by
the join conditions.
Based on the way the select statements are provided and the records they
return, joins are categorized into the following ways.
1. Inner Join
2. Outer Join
Left Outer Join
Right Outer Join
Full Outer Join
3. Cross Join
4. Self Join
Inner Join:
This join returns only the matching data between the tables. It is mainly
used to retrieve the related data between the tables.
Ex:Get the details of the students along with the class names from the following
student and class tables.
Class: Student:
62
Sol:
Output:
sid sname stdCID clsCID cname
1 A 101 101 MTECH
2 B 100 100 MCA
3 C 101 101 MTECH
4 D 102 102 BTECH
Outer Joins:
This join returns the unmatched records between the tables. Which tables
unmatched data to be displayed, depends on the type of outer join we are using.
Sometimes the unmatched data will be displayed along with matched data and
some other times the unmatched data will be displayed alone.
63
Output:
b. Get the details of students who are not assigned to any class.
Sol:
SELECT sid,sname
FROM Student s LEFT OUTER JOIN Class c
ON s.cid=c.cid WHERE c.cid IS NULL
Output:
sid sname
5 E
Sol:
64
Output:
SELECT c.cid,cname
FROM Student s RIGHT OUTER JOIN Class c
ON s.cid=c.cid WHERE s.cid IS NULL
Output:
cid cname
103 BCA
Cross Join:
A join without common column criteria is called as a cross join. This join is
used to find the different combinations of data between the tables. The output
will be the product of number of records between the tables.
Ex:Get the different possibilities how a student can be assigned to a class only
when they are having more than 200 marks
Sol:
Select sid,sname,c.cid,cname
From student s cross join class c
where marks>200
65
NOTE:
In case of ORACLE database, Inner join is called as EQUI/NATURAL Join
and Outer Join is called as Non-EQUI Join.
Self Join:
Joining a table to it is called as a self-join. In a self-join, since we are
using the same table twice, to distinguish the two copies of the table, we will
create to table aliases.
In the syntax of self join we never use the keyword ‘self’. Internally, we
perform an inner join only.
Ex: Get the employee details along with manager names from the EMP table. In
this table one the employee will be the manager for other employee.
Sol:
Output:
66
Internal Execution Process:
Ex: Get the full details of the orders made by the customers.
select cu.customerid,companyname,o.orderid,orderdate,
od.productid,productname,od.unitprice,quantity
from customers cu inner join orders o
on cu.customerid=o.customerid
inner join [order details] od
on o.orderid=od.orderid
inner join products p
on od.productid=p.productid
67
SUBQUERIES
Types Of SubQueries:
Based on the way the Select statements are provided and the way they
will execute, SQL Server provides the following types of subqueries.
Simple SubQuery
Nested SubQuery
Multiple SubQuery
Correlated SubQuery
Simple SubQuery:
Ex: Get the Second maximum salary from the following EMP
table.
Sol:
SELECT max(Sal) FROM EMP
WHER sal<(SELECT max(Sal) FROM EMP)
Output: 39000
68
Neseted SubQueries:
A Nested SubQuery is a select statement, containing another select
statement, which contains another select statement and so on. Such type of
nesting nature of select statements is called as a nested subquery. In these
subqueries, at first, the innermost query will be executed and based on the result
next higher query will be executed and so on. A maximum of 32 select
statements can be combined in these nested subqueries.
Ex: Get the Third maximum salary from the emp table
Output: 38000
Multiple SubQueries:
It is select statement containing different select statements at different
places.
Ex: List out the employees who are having salary less than
the maximum salary and also having hiredate greater than
the hiredate of an employee who is having the maximum
salary.
Sol:
SELECT empid,ename,sal,hiredate FROM EMP
WHERE sal<(SELECT max(sal) FROM EMP) AND
hiredate>(SELECT hiredate FROM EMP
WHERE sal=(SELECT max(Sal) FROM EMP))
Output:
69
Correlated SubQueries:
In a normal subquery, at first, the inner query will be executed and only
once. Based on the result next higher query will be executed.
Whereas in a correlated subquery, the inner query will be executed for
each record of the parent statement table. The internal execution process of this
subquery will be as follows:
1. A record value from the parent table will be passed to the inner query.
2. The inner query execution will be done based on that value.
3. The result of the inner query will be sent back to the parent statement.
4. The parent statement finishes the processing for that record.
The above 4 steps will be executed for each record of the parent table.
Examples:
Note: The above query is to calculate 3rd maximum salary. To calculate nth
maximum salary specify the number “n-1” in place of “2”.
2. Get the Top 3 maximum salaries from emp table.
Sol:
Output:
70
3. Get the details of employees who are not the managers
Sol:
Output:
Empid Ename
102 Avinash
106 vivek
4. Get the details of employees who are the managers for more than one
employee
Sol:
Output:
Empid Ename
103 Sumit
More Examples:
SELECT au_id
FROM titleauthor
WHERE title_id IN (SELECT title_id FROM sales)
71
SQL Server returns a list of all title IDs to the main query then lists all the
authors, whose books are sold, in the result set.
Consider the following example where the server returns a list of publisher
IDs to the main query, and then determines whether each publisher’s pub_id is in
that list:
SELECT publisher=pub_name
FROM publishers
WHERE pub_id IN ( SELECT pub_id FROM titles WHERE
type=’business’)
The inner query is evaluated first and then the result set is sent to the outer
query.
The inner query is evaluated first and then the result set is sent to the outer
query.
The NOT IN clause is used in the same way as the IN clause. Consider the
following example.
72
Sub Queries with EXISTS:
The subquery, when used with the EXISTS clause, always returns data in
terms of TRUE OR FALSE and passes the status to the outer query to produce the
results set. The subquery returns a TRUE value if the result set contains any
rows.
The query introduced with the EXISTS keyword differs from other queries.
The EXISTS keyword is not preceded by any column name, constant or there
expression and it contains an asterisk (*) in the SELECT list.
1. SELECT pub_name
FROM publishers
WHERE EXISTS (SELECT * FROM titles WHERE type=’business’)
2. SELECT pub_name
FROM publishers
Aggregate functions
WHERE EXISTScan(SELECT
also be * used
FROMin publishers
subqueries. Consider
WHERE the following
City=’Paris’)
example which displays the titles of all those books for which the advance is more
than the average advance of business related books.
SELECT Title=title
FROM titles
WHERE advance>(SELECT AVG (advance) from titles
WHERE type=’business’)
Subquery Restrictions:
The restrictions imposed are:
The column list of the select statement of a subquery introduced with the
comparison operator can include only one column.
The column used in the WHERE clause of the outer query should be
compatible with the column used in the select list of the inner query.
The DISTINCT keyword cannot be used with the subqueries that include
the GROUP BY clause.
The ORDER BY clause, GROUP BY clause and INTO keyword cannot be
used in a subquery, because a subquery cannot manipulate its result
internally.
Do not specify more than one column name in the subquery introduced
with the EXISTS keyword.
A view created with a subquery cannot be updated.
73
BUILT IN FUNCTIONS
Aggregate Functions:
Aggregate functions are used to produce summary data using tables.
74
expression.
NUMERIC FUNCTIONS:
75
d. ROUND: Used to round a floating point number to the required no.of
decimal places
f. FLOOR:Returns the nearest smaller integer value for the given number
76
c. DATENAME: It Returns the name of the corresponding datepart. If the
specified datepart is not having a name, this function will return
that value directly.
Syn: DATENAME(datepart,date)
Ex:
1. select datename(dw,getdate()) --Friday
2. select datename(mm,getdate()) --June
3. select datename(dd,getdate()) --10
4. select datename(dw,'10/21/77') --Friday
5. calculate how many employees joined in each
weekday from the emp table
select datename(dw,hiredate),count(*) from emp
group by datename(dw,hiredate)
Syn: DATEADD(datepart,n,date)
Ex:
1. select dateadd(dd,3,getdate()) --2010-06-13
77
e. DATEDIFF: Returns the difference between two given dates. The output
will be the subtraction of date1 from date2. The difference can be in days
or months or years etc., based on the interval specified.
Ex: Get the experience of each employee from the employee table.
The CONVERT function is used to change data from one type to another when
SQL server cannot implicitly perform a conversion. Using the CONVERT
function, data can be modified in variety of styles.
CONVERT(datatype[(length), expression[,style])
Ex:
1. SELECT Ytd_Sales=CONVERT(char(10),ytd_sales)
FROM titles.
78
STRING FUNCTIONS:
FUNCTION DESCRIPTION
CHARINDEX(‘pattern’, expression) Returns the starting position of
the specified pattern.
LOWER (character_expression) Converts two string and
evaluates the similarity between
them on a scale of 1 to 4.
LTRIM(character_expression) Returns the data without leading
brackets
REPLICATE(char_expression, Repeats a character expression a
integer_expression specified number of times.
REVERSE(character_expression) Returns the reverse of character
expression.
RIGHT(character_expression, Returns the part of the character
integer_expression) string from the right.
RTRIM(character_expression) Returns the data without tailing
blanks.
SPACE(numeric_expression) Returns a string of repeated
spaces. The number of spaces is
equal to the integer expression.
79
OPERATORS
Arithmetic operators:
+ for addition
- for subtraction
/ for division
* for multiplication
% for modulo
The modulo arithmetic operator is used to obtain the remainder of two divisible
numeric integer values. It cannot be used with money data type columns.
All the arithmetic operators can be used in the SELECT list with the column
names and numeric constants in a combination.
Example:
80
When any arithmetic operation is performed on a NULL value, the result is
always NULL because NULL values have no explicitly assigned values. Arithmetic
operations can be performed on more than one column at a time. Consider the
following query code:
The above query computes the product of ytd_sales and price from the titles
table and displays the output with the user-defined headings.
Comparison Operators:
The command syntax is:
SELECT column_list FROM table_name WHERE expression1
comparison_operator expression2
81
Examples:
Range Operator:
Examples:
List Operator
The syntax is:
Examples:
82
LIKE Operator:
Example Description
SELECT title FROM titles WHERE Returns all titles from titles table where first
type LIKE ‘bus%’ three characters of the column type are
‘bus’
SELECT * FROM publishers Returns all rows from publishers table where
WHERE country LIKE ‘US_’ country name is three characters long and
starts with US where the third character can
be anything.
SELECT title_id, price FROM titles Returns all columns from the titles table
WHERE title_id LIKE ‘P[SC]]%’ where title_id starts with the character P and
contains S or C in the second position
followed by any number of characters.
SELECT title_id, price FROM titles Returns all title_id and price from the titles
WHERE title_id, LIKE ‘P[^C]%’ table where title_id starts with P and does
not contain and S as the second character
and the third position onwards can contain
any characters.
83
Unknown Values:
Unknown values refer to the data entered in the form of the NULL
keyword. In SQL server terms, NULL is an unknown value or the value for which
data is not available. The rows containing the NULL values can be retrieved by
using the IS NULL keyword in the WHERE clause.
Example Description
SELECT * FROM publishers WHERE Returns all the rows specific to the
city=’Boston’ OR city=’Paris’ conditions, even if any one of the
conditions is true.
SELECT publishers WHERE Returns all the rows specific to the
city=’Boston’ AND city=’MA’ conditions, when both the conditions
are true.
SELECT * FROM publishers WHERE Returns all the rows specific to the
city=’Boston’ OR NOT city=’Paris’ conditions, except the rows specified
with the condition after NOT operator.
84
VIEWS
85
The restrictions imposed on views are as follows:
A view can be created only in the current database.
A view can be created only if there is the SELECT permission on its base
table.
The SELECT INTO statement cannot be used in a view declaration
statement.
A view cannot derive its data from temporary tables.
Example:
USE NORTHWIND
GO
The above statements create a view named custview, which contains the
custoemerid, companyname and the phone columns of the customer table.
The following statement can be used to execute a view:
86
Altering a view:
A view can be modified without dropping it. It ensures that the
permissions on the view are not lost. A view can be altered without affecting its
dependent objects, such as, triggers and stores procedures.
Example:
ALTER VIEW custview
AS
SELECT customerid, companyname, phone, fax
From customers
The statement generates the results:
87
Renaming a View:
A view can be renamed without dropping it. This also ensures that the
permissions on the view are not lost.
The guidelines to be followed for renaming a view as follows.
The view must be in the current database.
The new name for the view must follow the rules for renaming
identifiers.
Only the owner of the view and the database in which view is
created can rename a view.
A view can be renamed by using the sp_rename system stored procedure.
The syntax of sp_rename is
Example:
sp_rename custview,customerView
Note: All view are not modifiable. If the modification to the view is affecting
multiple base tables, then we can’t perform such modifications. If the
modification to the view is affecting a single base table, then we can perform that
modification
With Encryption:
Without this option in the view, the view design can be viewed by anybody
who have access on the view. In order to stop this we can encrypt the view with
this option. Once we encrypted the view we can’t decrypt again. So, it is
important to maintain a copy of the script.
Ex:
88
With SchemaBinding: (Materialized Views)
With CheckOption:
In general even the modification on the view affects the view criteria,
we can perform that modification. To stop this we can use ‘WITH CHECK
OPTION’.
89
INDEXES
Most books contain one general index of words, names, places, and so on.
Databases contain individual indexes for selected types or columns of data: this is
similar to a book that contains one index for names of people and another index
for places. When you create a database and tune it for performance, you should
create indexes for the columns used in queries to find data.
When SQL Server executes a statement to find data in the employee table
based on a specified emp_id value, it recognizes the index for the emp_id
column and uses the index to find the data. If the index is not present, it
performs a full table scan starting at the beginning of the table and stepping
through each row, searching for the specified emp_id value.
90
time to maintain the indexes. When you design and create indexes, you should
ensure that the performance benefits outweigh the extra cost in storage space
and processing resources.
Table Indexes
Microsoft® SQL Server™ 2000 supports indexes defined on any column in a
table, including computed columns.
If a table is created with no indexes, the data rows are not stored in any
particular order. This structure is called a heap.
91
Indexes can be unique, which means no two rows can have the same value for
the index key. Otherwise, the index is not unique and multiple rows can share the
same key value.
There are two ways to define indexes in SQL Server. The CREATE INDEX
statement creates and names an index. The CREATE TABLE statement supports
the following constraints that create indexes:
PRIMARY KEY creates a unique index to enforce the primary key.
UNIQUE creates a unique index.
CLUSTERED creates a clustered index.
NONCLUSTERED creates a nonclustered index.
This example shows the Transact-SQL syntax for creating indexes on a table.
USE pubs
GO
CREATE TABLE emp_sample
(emp_id int PRIMARY KEY,
emp_name char(50),
emp_address char(50),
emp_title char(25) UNIQUE )
GO
92
SYNONYMS
Creating a Synonym:
Syn:
93
Creating a synonym for a local object:
The following example first creates a synonym for the base object, Product in the
AdventureWorks database, and then queries the synonym.
USE tempdb;
GO
-- Create a synonym for the Product table in AdventureWorks.
CREATE SYNONYM MyProduct
FOR AdventureWorks.Production.Product;
GO
94
NORMALIZATION
Case Study:
There is a consulting company which acts a consultant for property owners
and clients who require property for rent.
95
ClinetRental
Tony
PG36 2 Manor Rd, 10-Oct- 1-Dec-01 370 CO93
Shaw
00
Glasgow
Tony
PG16 5 Novar Dr, 1-Aug-03 450 CO93 Shaw
1-Nov-02
Glasgow
Definition of 1NF
First Normal Form is a relation in which the intersection of each row and
column contains one and only one value.
There are two approaches to removing repeating groups from unnormalized
tables:
1.Removes the repeating groups by entering appropriate data in the empty
columns of rows containing the repeating data.
2. Removes the repeating group by placing the repeating data, along with a
copy of the original key attribute(s), in a separate relation. A primary key is
identified for the new relation
96
1NF ClientRental relation with the first approach
With the first approach, we remove the repeating group (property rented details)
by entering the appropriate client data into each row.
97
1NF ClientRental relation with the second approach
With the second approach, we remove the repeating group (property rented
details) by placing the repeating data along with a copy of the original key
attribute (clientNo) in a separte relation.
Client
ClientNo cName
CR76 PG4
CR76 PG16
PropertyRentalOwner
ClientNo ProperyNo PAddress RentStart RentFinish Rent OwnerNo oName
98
Second Normal Form (2NF)
Second normal form (2NF) is a relation that is in first normal form and
every non-primary-key attribute is fully functionally dependent on the primary
key.
The normalization of 1NF relations to 2NF involves the removal of partial
dependencies. If a partial dependency exists, we remove the function dependent
attributes from the relation by placing them in a new relation along with a copy of
their determinant.
99
Client
ClientNo cName
CR76 PG4
CR76 PG16
Rental
ClientNo Propery No RentStart RentFinish
Property Owner
Propery No PAddress Rent OwnerNo oName
100
Third Normal Form (3NF)
A Relation that is in first and second noraml form, and in which no non-
primary key attribute is Transitively dependent on the primary key
The functional dependencies for the Client, Rental and PropertyOwner relations
are as follows:
Client
fd2 clientNo cName (Primary Key)
Rental
fd1 clientNo, propertyNo & rentStart, rentFinish (Primary Key)
fd5 clientNo, rentStart & propertyNo, rentFinish (Candidate key)
fd6 propertyNo, rentStart & clientNo, rentFinish (Candidate key)
PropertyOwner
fd3 propertyNo & pAddress, rent, ownerNo, oName (Primary Key)
fd4 ownerNo & oName (Transitive Dependency)
101
Client Owner
ClientNo cName OwnerNo OName
Rental
ClientNo Propery RentStart RentFinish
No
Property Owner
Propery No PAddress Rent OwnerNo oName
102
T-SQL Programming
Syn:
DECLARE
<Varible Declarations>
BEGIN
------
<Executable Statements>
-----
END
Local Variables:
A local variable can be created by using the DECLARE statement. An initial value
can be assigned to the variable with the help of the SELECT statement and can be
used within the trigger or procedure where it is created or assigned the value.
Global Variables:
Global variables are pre-defined and maintained by the system. The server
to track server-wide and session-specific information uses them. They cannot be
explicitly set or declared. Global variables cannot be defined by users and are not
used to pass information across processors by applications. Many of the global
variables report on system activity since the last time SQL server was started,
other report information about a connection.
103
Some common global variables are:
Global Description
Variable
@@rowcount Returns the number of rows processed by preceding
command.
@@error Returns the error number of the last error generated.
@@trancount Returns the transaction nesting level status.
@@servername Returns the name of the local SQL server.
@@version Returns the version of the SQL server using.
@@spid Returns the current process ID.
@@identity Returns the last identity value used in an insert.
@@nestlevel Returns the number of level nested in a stored
procedure/trigger.
@@fetch_status Returns a value corresponding to the status of the previous
fetch statement in a cursor
Declaring Variables:
Ex:
1. Declare @i int
2. Declare @i,@j int --Error
3. Declare @i int,@j int
Initializing Variables:
Syntax:
104
Example:
PRINT Statement
The PRINT statement is used to pass a message to the client program’s message
handler. It is used to display user-defined messages.
CONTROL-OF-FLOW LANGUAGE:
BEGIN…END
BEGIN
{sql_statement | statement_block}
END
105
IF…ELSE Block
IF Boolean_expression
{sql_staement | statement_block}
[ELSE Boolean_expression
{sql_statement | statement_block}]
USE pubs
IF (SELECT SUM(price) FROM titles WHERE type='business') < 600
BEGIN
PRINT ' The sum of the following BUSINESS books is
less than 600
Dollars :'
PRINT ‘’
Select * FROM titles WHERE type='business'
END
CASE CONSTRUCT
SQL Server provides a CASE statement where you need a large number of
IF statements. The CASE statement enables multiple possible conditions to be
managed within a SELECT statement.
CASE
WHEN Boolean_expression THEN expression1
[[WHEN Boolean_expression THEN expression][..]
[ELSE expression]
END
106
Example:
SELECT
CASE
WHEN type='BUSINESS' THEN 'BUSINESS BOOK'
WHEN type='mod_cook' THEN 'MODERN COOKING'
WHEN type='trad_cook' THEN 'TRADITIONAL COOKING'
WHEN type='psychology' THEN 'PSYCHOLOGY BOOK'
ELSE 'No category assigned as yet'
END
FROM titles
WHERE title_id LIKE 'bu%' OR title_id LIKE 'MC%' OR
title_id LIKE 'PC%' OR title_id LIKE 'PS%' group by type
WHILE CONSTRUCT
WHILE Boolean_expression
{sql_statement | statement_block}
[BREAK]
{sql_statement | statement_block}
[CONTINUE]
Example:
107
STORED PROCEDURES
108
Temporary Stored Procedures
These are dynamic link libraries (DLLs) that SQL Server can dynamically
load and execute. These procedures run directly in the address space of SQL
Server and are programmed using the SQL Server Open Data Services API. They
are identified by the xp_prefix.
109
Types of Parameters:
SQL Server provides two types of parameters.
Input parameters
Output parameters
Input parameters will be used to pass a value using the procedure call.
Based on this value, the procedure execution will be done.
Output parameters will be used to assign a value inside the procedure
definition which can be used by the calling program. Before execution of the
stored procedure, output parameter doesn’t contain any value. Once the
procedure execution completes, now the output parameter gets some value.
110
Ex: using output parameters
Write a program to calculating the following details for a given employee
number.
Basic Salary
Benefits(Commission percentage on salary)
Net Salary
Solution:
1. Creating a procedure to calculate Benefits
Execution:
Exec emp_netsalary 100
Output:
111
Error Handling in Stored Procedures:
In order to not get any runtime errors it is important to handle errors in
the stored procedure. Using a ‘Begin Try’ and ‘Begin Catch’ blocks error handling
can be done in SQL Server.
Syn:
Example:
112
TRIGGERS
113
You can use the FOR clause to specify when a trigger is executed:
AFTER
The trigger executes after the statement that triggered it completes. If the
statement fails with an error, such as a constraint violation or syntax
error, the trigger is not executed. AFTER triggers cannot be specified for
views, they can only be specified for tables. You can specify multiple
AFTER triggers for each triggering action (INSERT, UPDATE, or DELETE). If
you have multiple AFTER triggers for a table, you can use
sp_settriggerorder to define which AFTER trigger fires first and which
fires last. All other AFTER triggers besides the first and last fire in an
undefined order which you cannot control.
AFTER is the default in SQL Server 2000. You could not specify AFTER or
INSTEAD OF in SQL Server version 7.0 or earlier, all triggers in those
versions operated as AFTER triggers.
INSTEAD OF
The trigger executes in place of the triggering action. INSTEAD OF triggers
can be specified on both tables and views. You can define only one
INSTEAD OF trigger for each triggering action (INSERT, UPDATE, and
DELETE). INSTEAD OF triggers can be used to perform enhance integrity
checks on the data values supplied in INSERT and UPDATE statements.
INSTEAD OF triggers also let you specify actions that allow views, which
would normally not support updates, to be updatable.
Triggers Compared to Constraints
Constraints and triggers each have benefits that make them useful in special
situations. The primary benefit of triggers is that they can contain complex
processing logic that uses Transact-SQL code. Therefore, triggers can support all
of the functionality of constraints; however, triggers are not always the best
method for a given feature.
Entity integrity should always be enforced at the lowest level by indexes that are
part of PRIMARY KEY and UNIQUE constraints or are created independently of
constraints. Domain integrity should be enforced through CHECK constraints, and
referential integrity (RI) should be enforced through FOREIGN KEY constraints,
assuming their features meet the functional needs of the application.
Triggers are most useful when the features supported by constraints cannot meet
the functional needs of the application. For example:
FOREIGN KEY constraints can validate a column value only with an exact
match to a value in another column, unless the REFERENCES clause
defines a cascading referential action.
114
A CHECK constraint can validate a column value only against a logical
expression or another column in the same table. If your application
requires that a column value be validated against a column in another
table, you must use a trigger.
Constraints can communicate about errors only through standardized
system error messages. If your application requires (or can benefit from)
customized messages and more complex error handling, you must use a
trigger.
Triggers can cascade changes through related tables in the database; however,
these changes can be executed more efficiently through cascading referential
integrity constraints.
Triggers can disallow or roll back changes that violate referential integrity,
thereby canceling the attempted data modification. Such a trigger might
go into effect when you change a foreign key and the new value does not
match its primary key.
If constraints exist on the trigger table, they are checked after the
INSTEAD OF trigger execution but prior to the AFTER trigger execution. If
the constraints are violated, the INSTEAD OF trigger actions are rolled
back and the AFTER trigger is not executed.
Example:
While entering the details of a new employee, the salary has to be entered
according to the grade. If the grade it changed, the basic salary should also be
changed accordingly. Instead of manually doing this, the HR manager wanted the
basic salary of the employees to be entered automatically whenever an employee
is added or grade is changed.
115
Now, create the emp table as follows:
CREATE TABLE emp(emp_no int,emp_name varchar(10),dept_no int,
grade char(1),bsal numeric(18,0),doj datetime)
An insert/update is written for the table emp. Whenever a new record is inserted
or updated, the new grade is obtained from the inserted table. The corresponding
basic salary is obtained from the table sal_info and the basic salary in the emp
table is set to this value.
This trigger can be checked by inserting a record with a null value for the field
bsal. When a select statement is given, the value for bsal will also be present.
116
Programming DDL Triggers:
Syntax:
Example:
The following example illustrates how a DDL trigger can be used to prevent any
table in a database from being modified or dropped:
Altering a Trigger:
The definition of an existing trigger can be altered without dropping it. The
altered definition replaces the definition of the existing trigger with the new
definition.
Syntax
117
Example:
This example creates a trigger that prints a user-defined message to the
client when a user tries to add or change data in the emp table. Then, the trigger
is altered using ALTER TRIGGER to apply the trigger only on INSERT activates.
This trigger is helpful because it reminds the user who updates or inserts rows
into this table.
Dropping a Trigger:
A trigger can be dropped by using, DROP TRIGGER statement. A trigger
gets dropped automatically when its associated table is dropped. Permissions to
drop a trigger defaults to the table owner. But the members of the system
administrators(sysadmin) and the database owner(db_owner) can drop any
object by specifying the owner in the DROP TRIGGER statement.
Syntax:
Example:
1. Setting the order of DML triggers
USE AdventureWorks;
GO
sp_settriggerorder @triggername= 'Sales.uSalesOrderHeader',
@order='First', @stmttype = 'UPDATE';
119
USER DEFINED FUNCTIONS
Types of UDF’s:
120
UDFs Returning a Scalar Value:
Much like SQL Server’s own built-in functions, they will return a scalar
value to the calling script or procedure. One of the truly great things about a UDF
is that you are not limited to an integer for a return value – instead, it can be of
any valid SQL Server data type, except for BLOBs, cursors, and timestamps. Even
if you wanted to return an integer, a UDF should be advantage to you for two
different reasons:
1. Unlike Stored Procedures, the whole purpose of the return value is to
serve a meaningful piece of data – for Stored Procedures, a return value
is meant as an indication of success or failure, and, in the event of failure,
to provide some specific information about the nature of that failure.
2. You can perform functions in-line to your queries (for instances, include it
as part of your SELECT statement) – you can’t do that with a Stored
Procedure.
Case study:
Let’s create a table called ORDERS with 3 columns named as OrderID, CustID and
OrderDate as follows
Lets insert some data into the table with the use of a simple T-SQL program.
SET @Counter =1
WHILE @Counter <= 10
BEGIN
INSERT INTO Orders
VALUES(1,1,DATEADD(mi, @Counter, GETDATE()))
SET @Counter = @Counter + 1
END
121
So, this gets us 10 rows inserted, with each row being inserted with
today’s date, but one minute apart from each other.
So, now we’re ready to run a simple query to see what orders we have
today. We might try something like:
SELECT *
FROM Orders
WHERE orderdate=GETDATE()
Unfortunately, this query will not get us anything back at all. This is
because GETDATE() gets the current time not just the day.
The solution is to convert the date to a string and back in order to
truncate the time information, then perform comparison.
SELECT *
FROM Orders
WHERE CONVERT(varchar(12), orderdate,
101)=CONVERT(varchar(12), GETDATE(),101)
This time, we will get back every row with today’s date in the OrderDate
column – regardless of what time of day the order was taken. Unfortunately, this
isn’t exactly the most readable code. Imagine you had a large series of dates you
needed to perform such comparisons against – it can get very ugly indeed.
So now let’s look at doing the same thing with a simple user-defined
function. First, we’ll need to create the actual function. This is done with the new
CREATE FUNCTION command, and it’s formatted much like a Stored Procedure.
For example, we might code this function like this:
122
Whether the date returned from GETDATE() is passed in as the parameter
and the task of converting the date is included in the function body and the
truncated date is returned.
To see this function in action, let’s reformat our query as follows:
SELECT *
FROM Orders
WHERE dbo.DateOnly(OrderDate) = dbo.DateOnly(GETDATE())
We get back the same set as with the stand-alone query. Even for a
simple query like this one, the new code is quite a bit more readable. There is,
however, one requirement for this type. The owner name is required in the
function call. SQL Server will, for some reason, not resolve functions the way it
does with other objects.
USE pubs
GO
123
This function returns a table of SELECTEed records and does a little
formatting: joining the last and first names, separating them with a comma, and
concatenating the three components to fill the address2 column.
At this point, we’re ready to use our function just as we would use a table
– the only exception is that as was discussed with scalar functions, we must use
the two-part naming convention:
SELECT *
FROM dbo.fnListOfAuthors()
124
TRANSACTIONS
125
Starting Transactions
You can start transactions in Microsoft® SQL Server™ as explicit, autocommit, or
implicit transactions.
Explicit transactions
Explicitly start a transaction by issuing a BEGIN TRANSACTION statement.
Autocommit transactions
This is the default mode for SQL Server. These transactions will contain only one
statement. Each individual Transact-SQL statement is committed when it
completes. You do not have to specify any statements to control transactions.
Implicit transactions
Set implicit transaction mode on through either an API function or the Transact-
SQL SET IMPLICIT_TRANSACTIONS ON statement. When that transaction is
completed either by using COMMIT / ROLLBACK, the next Transact-SQL
statement starts a new transaction.
Ending Transactions
You can end transactions with either a COMMIT or ROLLBACK statement.
COMMIT
If a transaction is successful, commit it. A COMMIT statement guarantees all of
the transaction's modifications are made a permanent part of the database. A
COMMIT also frees resources, such as locks, used by the transaction.
Syntax:
ROLLBACK
If an error occurs in a transaction, or if the user decides to cancel the transaction,
then roll the transaction back. A ROLLBACK statement backs out all modifications
made in the transaction by returning the data to the state it was in at the start of
the transaction. A ROLLBACK also frees resources held by the transaction.
Syntax:
126
Savepoints
Savepoints offer a mechanism to roll back portions of transactions. You create a
savepoint using the SAVE TRANSACTION savepoint_name statement, and then
later execute a ROLLBACK TRANSACTION savepoint_name statement to roll back
to the savepoint instead of rolling back to the start of a transaction.
Example: Let us suppose emp table contains the following data.
Empid Ename Sal
100 Anil 1500
101 Balu 2000
102 Vivek 3500
1. BEGIN TRAN
2. SELECT * FROM emp
3. DELETE FROM emp WHERE empid=102
4. SELECT * FROM emp
5. SAVE TRAN sp1
6. UPDATE emp SET sal=4000 WHERE empid=101
7. SELECT * FROM emp
8. ROLLBACK TRAN sp1
9. SELECT
Output: The *result
FROMforemp
the above program is as given below. each block is the
10. of
result ROLLBACK TRAN
select statement.
11.SELECT * FROM emp
100 Anil 1500
101 Balu 2000
102 Vivek 3500
100 Anil 1500
101 Balu 2000
100 Anil 1500
101 Balu 4000
100 Anil 1500
101 Balu 2000
100 Anil 1500
101 Balu 2000
102 Vivek 3500
127
LOCKS
Microsoft® SQL Server™ 2000 has locking that allows different types of resources
to be locked by a transaction. To minimize the cost of locking, SQL Server locks
resources automatically at a level appropriate to the task. Locking at a smaller
granularity, such as rows, increases concurrency, but has a higher overhead
because more locks must be held if many rows are locked. Locking at a larger
granularity, such as tables, are expensive in terms of concurrency because
locking an entire table restricts access to any part of the table by other
transactions, but has a lower overhead because fewer locks are being
maintained.
SQL Server can lock these resources (listed in order of increasing granularity).
Resource Description
DB Database.
SQL Server locks resources using different lock modes that determine how the
resources can be accessed by concurrent transactions.
SQL Server uses these resource lock modes.
Shared (S) Used for operations that do not change or update data (read-
only operations), such as a SELECT statement.
128
Exclusive (X) Used for data-modification operations, such as INSERT, UPDATE,
or DELETE. Ensures that multiple updates cannot be made to the
same resource at the same time.
Intent Used to establish a lock hierarchy. The types of intent locks are:
intent shared (IS), intent exclusive (IX), and shared with intent
exclusive (SIX).
Bulk Update (BU) Used when bulk-copying data into a table and the TABLOCK hint
is specified.
Shared Locks
Update Locks
Update (U) locks prevent a common form of deadlock. A typical update pattern
consists of a transaction reading a record, acquiring a shared (S) lock on the
resource (page or row), and then modifying the row, which requires lock
conversion to an exclusive (X) lock. If two transactions acquire shared-mode
locks on a resource and then attempt to update data concurrently, one
transaction attempts the lock conversion to an exclusive (X) lock. The shared-
mode-to-exclusive lock conversion must wait because the exclusive lock for one
transaction is not compatible with the shared-mode lock of the other transaction;
a lock wait occurs. The second transaction attempts to acquire an exclusive (X)
lock for its update. Because both transactions are converting to exclusive (X)
locks, and they are each waiting for the other transaction to release its shared-
mode lock, a deadlock occurs.
To avoid this potential deadlock problem, update (U) locks are used. Only one
transaction can obtain an update (U) lock to a resource at a time. If a transaction
129
modifies a resource, the update (U) lock is converted to an exclusive (X) lock.
Otherwise, the lock is converted to a shared-mode lock.
Exclusive Locks
Intent Locks
An intent lock indicates that SQL Server wants to acquire a shared (S) lock or
exclusive (X) lock on some of the resources lower down in the hierarchy. For
example, a shared intent lock placed at the table level means that a transaction
intends on placing shared (S) locks on pages or rows within that table. Setting an
intent lock at the table level prevents another transaction from subsequently
acquiring an exclusive (X) lock on the table containing that page. Intent locks
improve performance because SQL Server examines intent locks only at the table
level to determine if a transaction can safely acquire a lock on that table. This
removes the requirement to examine every row or page lock on the table to
determine if a transaction can lock the entire table.
Intent locks include intent shared (IS), intent exclusive (IX), and shared with
intent exclusive (SIX).
Intent shared (IS) Indicates the intention of a transaction to read some (but not
all) resources lower in the hierarchy by placing S locks on
those individual resources.
Intent exclusive (IX) Indicates the intention of a transaction to modify some (but
not all) resources lower in the hierarchy by placing X locks on
those individual resources. IX is a superset of IS.
Shared with intent Indicates the intention of the transaction to read all of the
exclusive (SIX) resources lower in the hierarchy and modify some (but not all)
resources lower in the hierarchy by placing IX locks on those
130
individual resources. Concurrent IS locks at the top-level
resource are allowed. For example, an SIX lock on a table
places an SIX lock on the table (allowing concurrent IS locks),
and IX locks on the pages being modified (and X locks on the
modified rows). There can be only one SIX lock per resource
at one time, preventing updates to the resource made by
other transactions, although other transactions can read
resources lower in the hierarchy by obtaining IS locks at the
table level.
Schema Locks
Schema modification (Sch-M) locks are used when a table data definition
language (DDL) operation (such as adding a column or dropping a table) is being
performed.
Schema stability (Sch-S) locks are used when compiling queries. Schema stability
(Sch-S) locks do not block any transactional locks, including exclusive (X) locks.
Therefore, other transactions can continue to run while a query is being compiled,
including transactions with exclusive (X) locks on a table. However, DDL
operations cannot be performed on the table.
Bulk update (BU) locks are used when bulk copying data into a table and either
the TABLOCK hint is specified or the table lock on bulk load table option is set
using sp_tableoption. Bulk update (BU) locks allow processes to bulk copy data
concurrently into the same table while preventing other processes that are not
bulk copying data from accessing the table.
Deadlocking
131
wait for the owning thread to release the target resource. The waiting thread is
said to have a dependency on the owning thread for that particular resource.
If the owning thread wants to acquire another resource that is currently owned
by the waiting thread, the situation becomes a deadlock: both threads cannot
release the resources they own until their transactions are committed or rolled
back, and their transactions cannot be committed or rolled back because they are
waiting on resources the other owns. For example, thread T1 running transaction
1 has an exclusive lock on the Supplier table. Thread T2 running transaction 2
obtains an exclusive lock on the Part table, and then wants a lock on the
Supplier table. Transaction 2 cannot obtain the lock because transaction 1 has it.
Transaction 2 is blocked, waiting on transaction 1. Transaction 1 then wants a
lock on the Part table, but cannot obtain it because transaction 2 has it locked.
The transactions cannot release the locks held until the transaction is committed
or rolled back. The transactions cannot commit or roll back because they require
a lock held by the other transaction to continue.
132
CURSORS
A cursor is a pointer to the result of a SELECT statement. The following
are the features provided by a cursor.
Retrieving one row or block of rows from the current position in the
result set.
Types of Cursors:
Static cursors
Dynamic cursors
Forward-only cursors
Keyset-driven cursors
Static cursors detect few or no changes but consume relatively few resources
while scrolling, although they store the entire cursor in tempdb. Dynamic
cursors detect all changes but consume more resources while scrolling,
although they make the lightest use of tempdb. Keyset-driven cursors lie in
between, detecting most changes but at less expense than dynamic cursors.
Cursor Statements:
We can control the records of a result set with the use of these cursor
statements. They are:
DECLARE
OPEN
FETCH
CLOSE
DEALLOCATE
133
DECLARE Statement is used to provide cursor declarations such as name
Of the cursor, the select statement to which result set the cursor should point
etc.,
OPEN Statement starts using the cursor. It executes the select statement
in the cursor and points the cursor to the first record of the result set.
FETCH statement is used to retrieve the data in the current location and
navigate the cursor to the required position.
CLOSE statement stops using the cursor. But the resources used by the
cursor are still open.
Example:
Suppose there is a table with some data and indexes. After the index
creation, if any modifications are performed on the table, those changes will not
reflect directly into the index structure. We have to refresh the index structure on
all table using the following statement.
134
The above command should be executed for all tables of the database. To
perform this task we can make use of the following cursor program:
open tblcursor
while @@fetch_status=0
begin
dbcc dbreindex(@tblname)
fetch next from tblcursor into @tblname
end
close tblcursor
deallocate tblcursor
135
SECURITY
SQL Server validates users at two levels of security on database
user accounts and roles.
Login Authentication
Permissions Validation
The authentication stage identifies the user using a login account and verifies
only the ability to connect with SQL Server. If the authentication is successful,
the user is connected to SQL Server. The user then needs permissions to access
database on the server, which is done by using an account in each database,
mapped to the user login.
The permission validation stage controls the activities the user is allowed to
perform in the SQL Server database.
Login Authentications:
A user must have a login account to connect to SQL Server. SQL
Server provides two types of Login Authentications.
Windows NT Authentication
SQL Server Authentication
Windows NT Authentication:
When using SQL Server authentication, the users must supply the SQL
Server login and password to connect to SQL Server. The users are identified in
SQL Server by their SQL Server login.
Authentication Modes:
136
Mixed Mode: It allows users to connect to SQL Server using Windows NT
Authentication or SQL Server Authentication.
Click “OK”
137
Providing access to a database for a user:
138
Granting Permissions on a table:
139
BACKING UP AND RESTORING DATABASES
140
3. In the window displayed click on ADD button and choose the location
where the backup to be stored along with name.
4. Click on “Options” tab and choose “Overwrite existing backup sets” option
5. Click “OK”
141
Recovering Database :
under “To database”. Select “From Device” option button and choose
(browse) button
142
4. Choose the file from the “Locate Backup file” window.
5. Select “ok”
6. Make a check mark under “Restore” item for the corresponding backup
database file.
7. Click on “Options” tab and choose “Overwrite Existing Database” option
8. Click “OK” button.
Note: If any error occurred regarding path, change the path under
“Restore As” to new path.
143
CASE STUDY
LOCATION
Location_ID Regional_Group
122 NEW YORK
123 DALLAS
124 CHICAGO
167 BOSTON
DEPARTMENT
Department_ID Name Location_ID
10 ACCOUNTING 122
20 RESEARCH 124
30 SALES 123
40 OPERATIONS 167
JOB
Job_ID Function
667 CLERK
668 STAFF
669 ANALYST
670 SALESPERSON
671 MANAGER
672 PRESIDENT
144
EMPLOYEE
CYNTHI
7521 WARK D 670 7698 22-FEB-85 1250 500 30
A
Simple Queries:
Where Conditions:
8. List the details about “SMITH”
9. List out the employees who are working in department 20
10. List out the employees who are earning salary between 3000 and 4500
145
11. List out the employees who are working in department 10 or 20
12. Find out the employees who are not working in department 10 or 30
13. List out the employees whose name starts with “S”
14. List out the employees whose name start with “S” and end with “H”
15. List out the employees whose name length is 4 and start with “S”
16. List out the employees who are working in department 10 and draw the
salaries more than 3500
17. list out the employees who are not receiving commission.
Order By Clause:
18. List out the employee id, last name in ascending order based on the
employee id.
19. List out the employee id, name in descending order based on salary
column
20. list out the employee details according to their last_name in ascending
order and salaries in descending order
21. list out the employee details according to their last_name in ascending
order and then on department_id in descending order.
22. How many employees who are working in different departments wise in
the organization
23. List out the department wise maximum salary, minimum salary, average
salary of the employees
24. List out the job wise maximum salary, minimum salary, average salaries
of the employees.
25. List out the no.of employees joined in every month in ascending order.
26. List out the no.of employees for each month and year, in the ascending
order based on the year, month.
27. List out the department id having atleast four employees.
28. How many employees in January month.
29. How many employees who are joined in January or September month.
30. How many employees who are joined in 1985.
146
31. How many employees joined each month in 1985.
32. How many employees who are joined in March 1985.
33. Which is the department id, having greater than or equal to 3 employees
joined in April 1985.
Sub-Queries
43. List out the employees who earn more than every employee in department
30.
44. List out the employees who earn more than the lowest salary in
department 30.
45. Find out whose department has not employees.
46. Find out which department does not have any employees.
47. Find out the employees who earn greater than the average salary for their
department.
147
Joins
Simple join
Self Join:
Outer Join:
148
Set Operators:
Solutions
149
19. Select employee_id, last_name, salary from employee order by salary
desc
20. Select employee_id, last_name, salary from employee order by
last_name, salary desc
21. Select employee_id, last_name, salary from employee order by
last_name, department_id desc
22. Select department_id, count(*), from employee group by department_id
23. Select department_id, count(*), max(salary), min(salary), avg(salary)
from employee group by department_id
24. Select job_id, count(*), max(salary), min(salary), avg(salary) from
employee group by job_id
25. select datepart(mm,hire_date) month,count(*) from employee
group by datepart(mm,hire_date) order by month
26. select datepart(yy,hire_date) year,datepart(mm,hire_date)
month,count(*) from employee group by datepart(yy,hire_date)
,datepart(mm,hire_date) order by year
27. Select department_id, count(*) from employee group by department_id
having count(*)>=4
28. select datename(mm,hire_date) month,count(*) NoOfEmployees from
employee group by datename(mm,hire_date) having
datename(mm,hire_date)='January'
29. select datename(mm,hire_date) month,count(*) NoOfEmployees from
employee group by datename(mm,hire_date) having
datename(mm,hire_date) in ('January','September')
30. select datename(yy,hire_date) year,count(*) NoOfEmployees from
employee
group by datename(yy,hire_date) having datename(yy,hire_date)=1985
31. Select datepart(yy,hire_date)Year, datepart(mm,hire_date) Month,
count(*) [No. of employees] from employee where
datepart(yy,hire_date)=1985
group by datepart(yy,hire_date),datepart(mm,hire_date)
32. Select datepart(yy,hire_date) Year, datename(mm,hire_date) Month,
count(*) [No. of employees] from employee
where datepart(yy,hire_date)=1993 and
datename(mm,hire_date)='March'
group by datepart(yy,hire_date),datename(mm,hire_date)
150
33. Select department_id, count(*) [No. of employees] from employee
where datepart(yy,hire_date)=1985 and datename(mm,hire_date)='April'
group by datepart(yy,hire_date), datename(mm,hire_date),
department_id having count(*)>=3
34. Select * from employee where salary=(select max(salary) from
employee)
35. Select * from employee where department_id IN (select department_id
from department where name=’SALES’)
36. Select * from employee where job_id in (select job_id from job where
function=’CLERK’
37. Select * from employee where department_id=(select department_id
from department where location_id=(select location_id from location
where regional_group=’New York’))
38. Select * from employee where department_id=(select department_id
from department where name=’SALES’ group by department_id)
39. Update employee set salary=salary*10/100 where job_id=(select job_id
from job where function=’CLERK’)
40. delete from employee where department_id=(select department_id from
department where name=’ACCOUNTING’)
41. Select * from employee where salary=(select max(salary) from employee
where salary <(select max(salary) from employee))
42. Select distinct e.salary from employee where & no-1=(select
count(distinct salary) from employee where sal>e.salary)
43. Select * from employee where salary > all (Select salary from employee
where department_id=30)
44. Select * from employee where salary > any (Select salary from employee
where department_id=30)
45. Select employee_id, last_name, department_id from employee e where
not exists (select department_id from department d where
d.department_id=e.department_id)
46. Select name from department d where not exists (select last_name from
employee e where d.department_id=e.department_id)
47. Select employee_id, last_name, salary, department_id from employee e
where salary > (select avg(salary) from employee where
department_id=e.department_id)
48. Select employee_id, last_name, name from employee e, department d
where e.department_id=d.department_id
151
49. Select employee_id, last_name, function from employee e, job j where
e.job_id=j.job_id
50. Select employee_id, last_name, name, regional_group from employee e,
department d, location l where e.department_id=d.department_id and
d.location_id=l.location_id
51. Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name
52. Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name having name=’SALES’
53. Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name having count (*)>=5
order by name
54. Select function, count(*) from employee e, job j where j.job_id=e.job_id
group by function
55. Select regional_group, count(*) from employee e, department d, location
l where e.department_id=d.department_id and d.location_id=l.location_id
and regional_group=’NEW YORK’ group by regional_group
56. Select employee_id, last_name, grade_id from employee e, salary_grade
s where salary between lower_bound and upper_bound order by
last_name
57. Select grade_id, count(*) from employee e, salary_grade s where salary
between lower_bound and upper_bound group by grade_id order by
grade_id desc
58. Select grade_id, count(*) from employee e, salary_grade s where salary
between lower_bound and upper_bound and lower_bound>=2000 and
lower_bound<=5000 group by grade_id order by grade_id desc
59. Select e.last_name emp_name, m.last_name, mgr_name from employee
e, employee m where e.manager_id=m.employee_id
60. Select e.last_name emp_name, e.salary emp_salary, m.last_name,
mgr_name, m.salary mgr_salary from employee e, employee m where
e.manager_id=m.employee_id and m.salary<e.salary
61. Select m.manager_id, count(*) from employee e, employee m where
e.employee_id=m.manager_id group by m.manager_id
62. Select last_name, d.department_id, d.name from employee e,
department d where e.department_id*=d.department_id
152
63. Select last_name, d.department_id, d.name from employee e,
department d where e.department_id*=d.department_id and
d.department_idin (select department_id from department where name IN
(‘SALES’,’OPERATIONS’))
64. Select function from job where job_id in (Select job_id from employee
where department_id=(select department_id from department where
name=’SALES’)) union Select function from job where job_id in (Select
job_id from employee where department_id=(select department_id from
department where name=’ACCOUNTING’))
65. Select function from job where job_id in (Select job_id from employee
where department_id=(select department_id from department where
name=’SALES’)) union all Select function from job where job_id in (Select
job_id from employee where department_id=(select department_id from
department where name=’ACCOUNTING’))
66. Select function from job where job_id in (Select job_id from employee
where department_id=(select department_id from department where
name=’RESEARCH’)) intersect Select function from job where job_id in
(Select job_id from employee where department_id=(select
department_id from department where name=’ACCOUNTING’)) order by
function
153
More Practical Examples
1. Assuming system date as current date, solve the following
i) Get the last day of week
ii) Get the first day of week
iii) Get the last day of the month
Note: The solution you provided should work for any given date.
2. In the Northwind database, get the customerid,companyname and no.of
orders made by each customer.
3. A table is having the following information-
id name Age
1 A 25
2 B 26
3 C 24
2 B 26
Write a query to delete duplicate records.(only one record with sid 2
should exist).
4. In my database I have a table with a column name ‘MyColumn1’. Write a
query to get the names of the tables that contains this column.
The department store also has many customers who purchase goods from
various sections. Customers can be of two types Regular and Ad-hoc.
Regular customers get credit at the department store. Maximum credit
limit allowed is Rs.10000.
The store procures goods from various suppliers. The goods are stored in
a warehouse and transferred to the store as and when requirement comes
up. Quantity of goods supplied cannot be less than 0 and cannot be
greater than 10000 for a particular supply.
The store has a computerized system for all its operations. Given below
are the tables in the database:
154
Section ( SectionNo int, Description Varchar(30), Section_Head_EmpNo
int)
Employees( EmpNo int, First_Name Varchar(30), Last_Name
Varchar(30), Address Varchar(30), Grade int, Salary Numeric(9,2),
SectionNo int, Date_Joined Datetime)
Customers( CustNo int, First_Name Varchar(30), Last_Name
Varchar(30), CustType char(1) (with check constraint R/A), Credit_Limit
Numeric(9,2), Credit_Card_No bigint, Credit_Card_Type Varchar(8))
Suppliers (SuppNo int,Name Varchar(30),Address Varchar(30), City
Varchar(30))
Products (ProductNo int identity, Product_Category_Code
Char(3),Description Varchar(30), Price Numeric(9,2), Qty_On_Hand int)
Product_CategoryMaster(Product_Category_Code Char(3),Description
Varchar(15))
Suppliers_Products ( SuppNo int, ProductNo int, Date_Supplied
Datetime, Qty_Supplied int)
Customers_Products( TransactionID int, CustNo int, ProductNo int,
Date_of_Purchase Datetime, Qty_Purchased int)
The column names which have been underlined are the primary keys for the
tables.
Create the tables with all appropriate constraints. Use the constraints
UNIQUE, NOT NULL, CHECK, PRIMARY KEY, FOREIGN KEY etc. wherever
necessary
5. Find all employees whose names begin with ‘A’ and end with ‘A’.
6. Find the total salary paid by each section to employees.
7. Display the section name and the name of the person who heads the
section.
8. Display supplier names and cities. If the city is null, display ‘LOCAL’.
9. Display the customer names and the customer type. If the customer type
is ‘R’ displays ‘Regular’, if the customer type is ‘A’ display ‘Ad-hoc’.
10. Try creating a view which when used, will display the supplier names,
product names , the quantity supplied and the date supplied for all records
in Supp_Products. The listing should be in alphabetical order of supplier
names.
11. List all suppliers who have not supplied any products. Use an outer join to
do this.
12. Display the average salary of employees in each section.
13. Display the customer no and the total number of products purchased by
him, for those customers who have purchased at least 2 or more different
products. Sort the listing in ascending order of customer number.
155
14. Display the customer name and product names which have been
purchased by him. The customer and product names should be in upper
case.
15. Display the products that have been supplied more than a month ago.
16. Display employee names and the date joined for employees. Date should
be in the format ‘DD-MMM-YYYY’.
17. Display employee names and the number of months between today’s date
and the joining date.
18. Display product names and the price rounded to the nearest integer.
19. Find the product which has the greatest price in each category.
T-SQL programming
20. Write a Procedure code which will let you insert a record into the Section
table. Use variables to represent the values of section_no,description and
section_head_empno. What happens if you try to insert a value of
section_no which already exists in the section table? Write proper error
handler.
21. Write a stored procedure to get the total quantity supplied for a particular
product. The procedure should total the quantity, and the calling block
should print the product no, product description and the total quantity
supplied. The procedure should raise an exception if the total quantity
supplied is 0, or the product does not exist.
156
Grade Designation
1 Vice President
2 Senior Manager
3 Assistant Manager
4 Section Supervisor
5 Sales Assistant
24. Whenever the location of the department changes, update the employee
location also. (Use an AFTER UPDATE trigger for this).
26. Write a Trigger that gets fired whenever employee salaries are updated for
a particular grade. The trigger inserts a record into the table
SALARY_UPDATE_LOG that contains the USERNAME, DATE OF UPDATION
of the user who updated the salary.
27. Using northwind database, create a view that gets the information about
orderid, orderdate, productid, proudctname , quantityorderd. Enter a new
order using the view.(used instead of insert trigger)
28. Write a user-defined function that gets the details of orders made by a
given customerid. Call this function from a t-SQL program.(function should
return a table).
Solutions:
1.
i) DECLARE @Date datetime
select @Date = GETDATE()
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 1),@Date) AS 'First day of the
week'
157
2. select c.customerid,companyname,count(*) nooforderes from customers c
inner join orders o
on c.customerid=o.customerid
group by c.customerid,companyname
3.
create table t1
(id int,name char(10),age int)
insert into t1
select 1,'A',25 union all
select 2,'B',26 union all
select 3,'C',24 union all
select 2,'B',26
First, run the above GROUP BY query to determine how many sets of duplicate
PK values exist, and the count of duplicates for each set.
Select the duplicate key values into a holding table. For example:
SELECT id,name,count=count(*)
INTO holdkey
FROM t1
GROUP BY id,name
HAVING count(*) > 1
Select the duplicate rows into a holding table, eliminating duplicates in the
process. For example:
158
At this point, the holddups table should have unique PKs, however, this will not
be the case if t1 had duplicate PKs, yet unique rows (as in the SSN example
above). Verify that each key in holddups is unique, and that you do not have
duplicate keys, yet unique rows. If so, you must stop here and reconcile which of
the rows you wish to keep for a given duplicate key value. For example, the
query:
should return a count of 1 for each row. If yes, proceed to step 5 below. If no,
you have duplicate keys, yet unique rows, and need to decide which rows to
save. This will usually entail either discarding a row, or creating a new unique key
value for this row. Take one of these two steps for each such duplicate PK in the
holddups table.
Delete the duplicate rows from the original table. For example:
DELETE t1
FROM t1, holdkey
WHERE t1.id = holdkey.id
Put the unique rows back in the original table. For example:
159
8. select suppno,name,isnull(city,'Local') from suppliers
9. select Custno,First_name,Last_name,
case CustType
when 'R' then 'Regular'
when 'A' then 'Ad-hoc'
end from customers
160
19. select p.productno,p.product_category_code,p.price
from products p inner join (select product_category_code,max(price)
maxPrice from products group by product_category_code) a
on p.product_category_code=a.product_category_code and
p.Price=maxPrice order by p.Product_Category_Code
21.
alter procedure pGetProductQtySupplied(@pid int)
as
begin
declare @count int
select @count= COUNT(*) from Suppliers_Products where ProductNo=@pid
if @count=0
raiserror('Productno doenot exist',10,1)
else
select p.productno,p.description,sum(qty_supplied) from products
p,suppliers_products su
where p.productno=su.productno and su.productno=@pid group by
p.productno,p.description
end
exec pGetProductQtySupplied 10
161
22.
create procedure pInsertSupplierProducts(@sno int,@pid int,@dtSupp
datetime,@qtySupp int)
as
begin
insert into Suppliers_Products values(@sno,@pid,@dtSupp,@qtySupp)
end
23.
select first_name + ' ' + last_name,sectionno,
case Grade
when 1 then 'Vice President'
when 2 then 'Senior Manager'
when 3 then 'Assistant Manager'
when 4 then 'Section Supervisor'
when 5 then 'Sales Assistant'
end Designation from employees
162
24.
create trigger trgUpdateLocation
on department
for update
as
begin
declare @oldloc varchar(20),@newloc varchar(20)
select @newloc=location from inserted
select @oldloc=location from deleted
update emp set location=@newloc where location=@oldloc
end
testing:
select * from emp
select * from department
update department set location='Sec' where location='Secunderabad'
163
26. create table SALARY_UPDATE_LOG
(username varchar(20),DateofUpdate datetime)
testing:
select * from emp
select * from SALARY_UPDATE_LOG
update emp set empsalary=empsalary+50000 where empNo=101
27.
CREATE VIEW Customerorders_vw
with schemabinding
as
select o.orderid,o.orderdate,oi.productid,oi.quantity,oi.unitprice
from dbo.orders o inner join dbo.[order details] oi
on o.orderid=oi.orderid
inner join dbo.products p on oi.productid=p.productid
if @@rowcount=0
raiserror('no matching orders. cannot perform insert',10,1)
end
insert into customerorders_Vw values(1,GETDATE(),2,10,150)
164
28.
create function fnGetOrders(@cid NCHAR(5))
returns table
as
return(select Cu.Customerid,o.orderid,o.orderdate,od.productid,
p.productname, od.unitprice,od.quantity
from customers cu inner join orders o on cu.customerid=o.customerid
inner join [order details] od on o.orderid=od.orderid
inner join products p on od.productid=p.productid
where cu.customerid=@cid)
Testing:
select * from dbo.fnGetOrders('HANAR')
dbcc checkident('customers',reseed,30)
165
FREQUENTLY ASKED QUESTIONS
1. What are the new data types in SQL Server?
2. How to get the version of SQL Server?
3. What are system Databases?
4. What happens if we delete any one of either Master or Model databases?
5. What are data files?
6. What is the Maximum number of databases that can be created for an
instance of SQL Server?
7. What is identity property?
8. How to insert explicit values into identity column?
9. What is the maximum size of data that can be entered in a single row of a
table?
10. How to get the table names in the database?
11. How to insert multiple rows using insert statement?
12. Difference between DELETE and TRUNCATE?
13. Difference between WHERE and HAVING clauses?
14. What are the types of Integrity Constraints?
15. Difference between UNIQUE and PRIMARY KEY?
16. What is composite primary key?
17. How many columns can be given in a composite primary key?
18. What is ON DELETE CASCADE?
19. How many references can be given to a table?
20. What are Joins? Types of Joins?
21. What is a correlated sub query?
22. What is the difference between IN and ANY Operators?
23. What is a View?
24. What is an Index? What are the types of indexes?
25. How many Clustered Indexes can be created on a table?
26. How may NonClustered Indexes be able to be created on a table?
27. What is Normalization?
28. What are the Normal Forms?
29. What is Demoralization?
30. What is a cursor?
31. What are the types of cursors?
32. What is @@FETCH_STATUS?
33. What is a stored procedure?
34. How many stored procedures can be nested?
35. How to raise errors inside a stored procedure?
36. What is a trigger?
37. What are Instead of Triggers?
38. What is the difference between a Stored Procedure and a Trigger?
39. What is User Defined Function?
166
40. What is the difference between Stored Procedure and User Defined
Function?
41. What are ACID properties?
42. What is Lock?
43. What is a Deadlock?
44. Write a query to get nth maximum salary?
45. How to delete duplicate rows from a table?
46. What is the use of DBCC commands
47. What are the authentications available in sql sever?
48. What are the authentication modes available?
49. How to increase the performance of a query?
Solutions
1. SQL Server 2000 introduces three new data types. bigint is an 8-byte
integer type. sql_variant is a type that allows the storage of data values
of different data types. table is a type that allows applications to store
results temporarily for later use. It is supported for variables, and as the
return type for user-defined functions.
2. The following 3 commands can be used to get the version of SQL Server
Select @@Version
EXEC sp_msgetversion
Exec xp_msver
Master: The master database records all of the system level information
for a SQL Server system. It records all login accounts and all system
configuration settings. Master is the database that records the existence
of all other databases, including the location of the database files. Master
records the initialization information for SQL Server.
Model: The model database is used as the template for all databases
created on a system. When a CREATE DATABASE statement is issued, the
first part of the database is created by copying in the contents of the
model database, then the remainder of the new database is filled with
empty pages.
167
MSDB: The msdb database is used by SQL Server Agent for scheduling
alerts and jobs, and recording operators.
4. SQL Server won’t work properly if we delete any one of Master or Model
databases.
The primary data file is the starting point of the database and points to
the other files in the database. Every database has one primary data file.
The recommended file name extension for primary data files is .mdf.
Secondary data files comprise all of the data files other than the primary
data file. Some databases may not have any secondary data files, while
others have multiple secondary data files. The recommended file name
extension for secondary data files is .ndf.
Log files
Log files hold all of the log information used to recover the database.
There must be at least one log file for each database, although there can
be more than one. The recommended file name extension for log files is
.ldf.
168
6. 32,767
7. Identity:
Auto number generated columns can be implemented using the
IDENTITY property, which allows the application developer to specify both
an identity number for the first row inserted into the table (Seed
property) and an increment (Increment property) to be added to the
seed to determine successive identity numbers. When inserting values into
a table with an identifier column, Microsoft® SQL Server™ 2000
automatically generates the next identity value by adding the increment to
the seed.
9. 8060 bytes
10. To get the name of all the tables in a database you can use one of the
following 3 methods.
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE=’BASE TABLE’
SELECT NAME FROM SYSOBJECTS WHERE TYPE=’U’
EXEC SP_TABLES returns all tables (system, user
169
12. Both TRUNCATE and DELETE commands are used to delete the data from
the table. The difference between them is :
With TRUNCATE entire table data will be deleted. Whereas with
DELETE command we can delete entire table data as well as certain
row data, which is not possible with TRUNCATE.
Even though, we are deleting entire table data, the deletion will be
done row by row. Where as, with TRUNCATE, the deletion will be
done at once.
DELETE maintains log information about the deleted records.
Where as, TRUNCATE does not maintain log details. Instead of this,
it maintains deallocation of Data Pages.
13. Both WHERE and HAVING clauses are used to provide a restriction to the
result set. Only, those records, which satisfy the criteria, will be returned.
The difference between them is:
With WHERE clause the condition can be provided based on any
column of table. Whereas, by using HAVING clause, the condition
can be specified either by using an Aggregate Function or a GROUP
BY column.
Suppose, if the SELECT statement contains WHERE and GROUP BY
clauses, the WHERE clause should precede GROUP BY clause.
Whereas, if the SELECT statement contains GROUP BY and HAVING
clauses, the HAVING clause should come after GROUP BY clause.
14. Integrity Constraints are used to maintain Data Integrity in the database.
It is a restriction that can be applied on a column or a table. 3 types of
Integrity constraints are available
DOMAIN INTEGRITY: They can be applied on a column of a table. It
ensures that a column should satisfy specified criteria. Ex: CHECK
ENTITY INTEGRITY: they can be provided on a column or on a
table. It ensures that the column must have unique
(non=duplicate) values.
Ex. UNIQUE, PRIMARY KEY
REFERENCIAL INTEGRITY: Referential integrity preserves the
defined relationships between tables when records are entered or
deleted. In Microsoft® SQL Server™ 2000, referential integrity is
based on relationships between foreign keys and primary keys or
between foreign keys and unique keys (through FOREIGN KEY and
CHECK constraints). Referential integrity ensures that key values
are consistent across tables. Such consistency requires that there
be no references to nonexistent values and that if a key value
changes, all references to it change consistently throughout the
database.
170
When you enforce referential integrity, SQL Server prevents users
from:
17. 16 columns.
18. In general if the parent table record is having a reference In the child
table, we can’t delete the record directly. With the use of “ON DELETE
CASCADE”, when we delete the parent table record, that record and all
its child references will be deleted at once.
20. A JOIN is a select statement used to get the data distributed among
different tables.
Types of Joins:
1. Inner Join: Returns only the matching records between the two
tables based on the criteria.
2. Outer Join: Returns left alone records along with matching
records.
Left Outer Join: Returns all the matching records between
the two tables and all the left alone records from left table.
171
Right Outer Join: Returns all the matching records
between the two tables and all the left alone records from
Right table.
Full Outer Join: Returns all the matching records between
the two tables and all the left alone data from left table as
well as all the left alone data from the right table.
3. Cross Join: A cross join that does not have a WHERE clause
produces the Cartesian product of the tables involved in the join.
The size of a Cartesian product result set is the number of rows in
the first table multiplied by the number of rows in the second table.
This is an example of a Transact-SQL cross join. Cross joins return
all rows from the left table, each row from the left table is
combined with all rows from the right table.
4. Self Join: Joining a table to itself is called as self Join. In a self join
we have to use two copies of the same table to join them. To
distinguish the two copies, we use duplicate names to the tables
called as ‘table aliases’.
21. Correlated Sub Query: In a normal sub query, at first the inner query
will be executed and based on the result the parent query will be
executed. Both queries will execute only once.
Whereas, in a Correlated Sub Query, the inner query will execute for each and
every row of the parent query. The internal process in the execution of a
correlated sub query is as follows.
The outer query passes the value of the first record into the
inner query.
The inner query then executes based on the values passed in.
and it passes the resultant values back to the parent query.
The parent query uses those values to finish the processing.
The above 3 steps should be performed for each row of the parent query.
22. IN operator can be used to provide the list of values to checked, either
by using explicit list of values and also with the resultant values of a
SELECT statement, which is not possible with ANY operator, where we can
use only the SELECT statement to specify the list of values.
23. A view can be thought of as either a virtual table or a stored query. The
data accessible through a view is not stored in the database as a distinct
object. What is stored in the database is a SELECT statement. The result
set of the SELECT statement forms the virtual table returned by the view.
A user can use this virtual table by referencing the view name in Transact-
SQL statements the same way a table is referenced. A view is used to do
any or all of these functions:
172
Restrict a user to specific rows in a table.
For example, allow an employee to see only the rows recording his or her
work in a labor-tracking table.
For example, allow employees who do not work in payroll to see the
name, office, work phone, and department columns in an employee table,
but do not allow them to see any columns with salary information or
personal information.
Join columns from multiple tables so that they look like a single table.
Views are created by defining the SELECT statement that retrieves the
data to be presented by the view. The data tables referenced by the
SELECT statement are known as the base tables for the view
25. 1
26. 249
173
27. Normalization is the process of breaking up data into a logical non-
repetitive format that can easily be reassembled as a whole.
28.Normal Forms:
Basically there are 6 Normal Forms. A fully normalized database is the one that is
normalized to the Third Normal Form.
Retrieving one row or block of rows from the current position in the
result set.
174
Providing Transact-SQL statements in scripts, stored procedures, and
triggers access to the data in a result set.
31.Types of Cursors:
Static cursors
Dynamic cursors
Forward-only cursors
Keyset-driven cursors
Static cursors detect few or no changes but consume relatively few resources
while scrolling, although they store the entire cursor in tempdb. Dynamic
cursors detect all changes but consume more resources while scrolling,
although they make the lightest use of tempdb. Keyset-driven cursors lie in
between, detecting most changes but at less expense than dynamic cursors.
32.@@FETCH_STATUS:
Returns the status of the last cursor FETCH statement issued against any
cursor currently opened by the connection.
175
Parameters
Parameters are used to exchange data between stored procedures and the
application or tool that called the stored procedure:
Input parameters allow the caller to pass a data value to the stored
procedure.
34. 32
176
Stored procedure allows input and output parameters. Whereas, an
UDF allows only input parameters. Instead of output parameters
they support RETURN values.
Stored Procedures also provide RETURN keyword but it specifies
only the success or failure by returning an integer value. Whereas,
an UDF’s RETRUN value can return any type of data.
A Stored Procedure cannot be used inside a SELECT statement.
Whereas, an UDF can be used as part of the SELECT statement.
41.
A transaction is a logical unit of work in which, all the steps must be
performed or none. ACID stands for Atomicity, Consistency, Isolation,
Durability. These are the properties of a transaction. For more information
and explanation of these properties, see SQL Server books online or any
RDBMS fundamentals text book.
Atomicity
Consistency
Isolation
177
Durability
43.DeadLocking:
178
45. Deleting Duplicate rows in SQL Server:
Windows Authentication
SQL Server Authentication
49. This is a very open ended question and there could be a lot of reasons
behind the poor performance of a query. But some general issues that you
could talk about would be: No indexes, table scans, missing or out of date
statistics, blocking, excess recompilations of stored procedures, procedures
and triggers without SET NOCOUNT ON, poorly written query with
unnecessarily complicated joins, too much normalization, excess usage of
cursors and temporarytables.
179