Tuesday, August 12, 2008

SQL - Structured query language notes

© Moreniche

Data Types

Binary(n)

It is used to store Hexadecimal values with a maximum length of 8000 bytes. It is used when data entries in a column are expected to have consistent size.

Varbinary(n)

It is used to store Hexadecimal values with a maximum length of 8000 bytes. It is used when data entries in a column are expected to vary in size.

Image

0 to 231-1 bytes.

Char(n)

Use char when every entry for a column has the same fixed length. Maximum upto 8 KB or 0-8000 bytes

Varchar(n)

Use char when every entry for a column has varied length. Maximum upto 8 KB or 0-8000 bytes

Nchar(n)

Use char when every entry for a column has the same fixed length. Maximum upto 4 KB or 0-4000 bytes

Nvarchar(n)

Use char when every entry for a column has varied length. Maximum upto 4 KB or 0-4000 bytes

Text

Used to store large amount of data with a max limit of 2147483647 chars.

Ntext

Storage size is 2 times the number of chars entered

Datetime

8 bytes. Date between 1-1-1753 to 31-12-9999

Smalldatetime

4 bytes. Date between 1-1-1900 to 6-6-2079

Int

4 bytes. Between -231 to 231

Smallint

2 bytes. Between -215 to 215

Tinyint

1 byte. Between 0 to 255

Bigint

8 bytes. Between -263 to 263

Money

8 bytes. Between -263 to 263

smallmoney

4 bytes. Between -214748 to 214748

Bit

Integer data with a value of 0 and 1. 0-8 then 1 byte. 9-16 then 2 bytes.

JOINS

Joins are used to retrive data from two or more tables based on a logical relationship between tables. It specifies foreign key relationship between the tables.

Types Of JOINS

  1. Inner
  2. Outer

Ø Left Outer

Ø Right Outer

  1. Self

Inner Join

Select B.Branch_code,B.add1,R.tno,R.Pass_name

from Branch as B

INNER JOIN

Reservation as R ON

B.Branch_code=R.Branch_code

Order by B.Branch_code

Left Outer Join

Select R.Flightno,R.Branch_code,B.city,R.Class from

Reservation as R

LEFT OUTER JOIN

Branch as B ON

B.Branch_code=R.Branch_code

Order by R.flightno

Right Outer Join

Select B.Branch_code, B.city, R.flightno, R.class from

Reservation as R

RIGHT OUTER JOIN

Branch B ON

R.Branch_code=b.Branch_code

Self Join

Select A.origin+A.destination+B.destination from

Fare as A, Fare as B where

A.origin=b.destination

Data Integrity

Data Integrity means reliability and accuracy of data.

Types Of Data Integrity

1. Entity Integrity

  1. Domain Integrity
  2. Referential Integrity
  3. User-Defined Integrity

Entity Integrity

Entity integrity defines row as a unique entity. It is also called as Row Integrity.

Domain Integrity

Domain Integrity enforce restrictions on the values entered.

Referential Integrity

This integrity is used for creating relationships between the tables.

Entity Integrity

Primary Key

Unique key Constraint

IDENTITY

Domain Integrity

DEFAULT Constraint

Foreign Key

Check Constraint

NOT NULL

Referential Integrity

Foreign Key

Check Constraint

User Defined Integrity

Rules

Stored Procedures

Triggers

Constraint

Constraint is a property that can be placed on a column or set of columns in a table.

Rules

Rules provide a defined restriction on the values, for a column or a user-defined datatype. It can be used for insert and update statement.

Primary Key

A primary key is a column or group of columns that uniquely identify rows in a table. It does not contain null.

Foreign Key

A foreign key column refers to the values of primary key column of another table or same table.

Unique Key

The Unique constraint is similar to the primary key constraint except that it allows null values.

Check Constraint

It is used to enforce domain integrity.

Set Default Property

ALTER TABLE SERVICE add CONSTRAINT

Serv_def DEFAULT 100 for SS_Fare

Sp_unbindefault ‘service.ss_Fare’

Alter table Service drop constraint Serv_def

Set Identity Property

ALTER TABLE Cancellation add

Srlno int IDENTITY(2000,1)

Set Primary Key

ALTER TABLE Branch

ALTER COLUMN Branch_code char(4) NOT NULL

ALTER TABLE Branch

Add Constraint Branch_const Primary Key(Branch_code)

CREATE TABLE A(B int Primary Key)

Set Foreign Key

ALTER TABLE FlightSchedule

Add Constraint Flt_const FOREIGN KEY(Airbusno)

REFERENCES Airbus(Airbusno)

ALTER TABLE FlightSchedule

NoCheck Constraint Flt_const

Set Unique Key

ALTER TABLE FlightSchedule

Add Constraint fltsch_const

UNIQUE(Flightno)

ALTER TABLE FlightSchedule

DROP Constraint fltsch_const

Set Check Constraint

ALTER TABLE Reservation

Add Constraint res_chkconst

Check(class in(‘B’,’E’,’F’))

Set Rules

CREATE RULE Rule2 as

@Serv_code in(‘cc’,’nu’,’wc’)

Sp_bindrule Rule2, ‘Reservation.SS_code’,FUTUREONLY

Indexes

Types Of Indexes

Clustered Index

A clustered index determines the storage order of data in a table.

A table can have only one clustered index.

Non-Clustered Index

A non-clustered index specifies a logical ordering only. Here the data is stored in one place, the index in the another, with pointers to the storage location of the data.

Unique Index

A unique index ensures that the indexed column contains no duplicate values.

Composite Index

A composite index consists of 2 or more columns indexed together. The maximum number of columns that can be combined is 16 and the allowable size is 900 bytes.

Clustered Index

CREATE CLUSTERED INDEX fare_route

On Fare(Route_code)

Non-Clustered Index

CREATE NONCLUSTERED INDEX

fare_desc on fare(route_desc)

Unique Index

CREATE UNIQUE INDEX branch_city

On Branch(city)

Composite Index

CREATE INDEX comp_index on

reservation(TNO,flightno)

Drop Index

drop index fare.fare_route

Views

A view is an alternate way of looking at data from one or more tables in the database. A view is a virtual table, usually created as a subset of columns or rows from one or more tables. However, a view does not exist as a set of stored data values in a database. The rows and columns come from tables referenced in the query. The data will be displayed directly from the table at the time of execution. A view acts as a filter on the table addressed in the query.

Advantages

For the end user

o Easier to understand results

o Easier to obtain data

For the developer

o Easier to restrict data retrieval

o Applications are easy to maintain

Guidelines for creating view

  1. View can be created only in the current database
  2. A view name should be similar to the table name because it is easy to remember and understand
  3. A view can be built on other views. SQL Server allows views to be nested upto
    32 levels.
  4. Defaults, Rules and triggers cannot be associated with views.
  5. Views cannot be indexed.
  6. Temporary tables cannot participate in views
  7. The query defining the view cannot include ORDER BY,COMPUTE, COMPUTE BY clauses or the INTO Keyword

Modifying data through views

1. No aggregate functions can be used in the select list.

2. The view contains at least one table in the from clause.

3. The view has no derived columns in the select list.

Indexed Views

Indexed view has been introduced with SQL Server 2000 and is supported only by its enterprise edition.

Create View cv with schemabinding as

Select B.Branch_code,B.add1,R.tno,R.Pass_name

from [dv6-0205b].Branch as B

INNER JOIN

[dv6-0205b].Reservation as R ON

B.Branch_code=R.Branch_code

You have to enable the ARITHABORT option while creating the index. The ARITHABORT option is used to terminate the query in case of any overflow or divide by zero error. This option helps to discontinue arithmetic operations in case of errors.

SET ARITHABORT ON

CREATE UNIQUE CLUSTERED INDEX IND

ON cv(BRANCH_CODE)

Distributed partitioned views

SQL Server 2000 supports the feature “Distributed partitioned views(DPV)”. This feature allows partitioning and distributing data horizontally to multiple number of servers and databases. It also makes us feel that it is uniformaly one database.

Partitioned tables are distributed across multiple servers. Hence, each server needs to access every other server. Therefore, you need to configure all the servers as linked servers.

create view partview as

Select * from server2k.pubs.dbo.stores

UNION ALL

Select * from aceserver.pubs.dbo.stores

STORED PROCEDURES

Variables

Variables are defined memory locations, which are given a name and which contain some value. Since variables are created in memory, whatever they contain is not permanent. Variables are mainly used for calculations or to store some value for stored procedures. A variable is an object that can hold a data value.

There are two types of variables :

Local Variables

System Global Variables

Ex:

Declaring Variables

DECLARE @FNO CHAR(4)

DECLARE @SNO INT

Set value to variables

SET @FNO=’abc’

SET @TNO=1

Using a variable in an sql query

Select * from flight where flightno=@FNO

Select * from reservation where tno=@TNO

System Global Variables

System Global Variables

This Variable returns

@@Trancount

Transactions currently open on the connection

@@Servername

Local server name

@@RowCount

Numbers of rows effected by the latest SQL statement

@@Nestlevel

Nesting level of the current stored procedure

@@Language

Language name

@@Servicename

SQL Server service name on the current computer

@@Procid

ID of the current stored procedure

@@Connections

Number of connections established with the server since it is started

@@Fetch_Status

Status of the FETCH operation. Returns 0 if it is successful, -1-2 if it is unsuccessful.

Stored Procedures

Stored procedures are vital tool for any database system. Stored procedures are written by database developers or database administrators to run commonly performed administrative tasks or to apply complex business rules. The stored procedure contains data manipulation or data retrieval statements.

Definition

A stored procedure is a precompiled collection of Transact-SQL statements stored with a name and processed as a unit. SQL Server provides some precompiled stored procedures for managing SQL Server and displaying information about the databases and users. These stored procedures are called system stored procedures.

Benefits of stored procedures

Speed

Faster access to data

Less compilation time

Modular programming

Consistency

Enhance security mechanism

Types of stored procedures

  • System stored procedures
  • Extended stored procedures.
  • User-defined stored procedures

System stored procedures

System stored procedures are supplied by SQL Server, they are precompiled collections of Transact-SQL statements. System stored procedures are provided as shortcuts for retrieving information from system tables.

The name of all system procedures starts with ‘sp_’.

System stored procedures are located in the master database and are owned by the system administrator.

System stored procedures are grouped into the following categories:

1. Catalog procedures

2. Security procedures

3. System procedures

4. Cursor procedures

5. Distributed query procedures

6. SQL Server Query Agent procedures

7. Sql Mail extended procedures


Extended stored procedures

Extended stored procedures are similar to user-defined and system stored procedures except that they are not residents of SQL Server. They work outside SQL Server and are stored as DLLs. SQL Server dynamically locates them and executes them. Extended stored procedures are usually denoted by the ‘xp_’ prefix.

Dynamic link library is an executable routine containing a specific set of functions stored in .dll file and loaded on demand when needed by the program.


User defined stored procedures

Apart from using the built-in stored procedures, you can also create your own stored procedures.

To create stored procedures, CREATE PROCEDURE or CREATE PROC statements are used. All stored procedures are created in the current database. In order to create a procedure you must have the permission to execute the CREATE PROCEDURE statement. This permission is assigned by default to the database owner but the owner can transfer it to the other users.

The syntax is:

CREATE PROC[EDURE] procedure_name

Creating procedures

create procedure abc as

Select B.Branch_code,B.add1,R.tno,R.Pass_name

from Branch as B

INNER JOIN

Reservation as R ON

B.Branch_code=R.Branch_code

Order by B.Branch_code

Exec abc

Using parameters

create procedure abc

@tno int

as

Select B.Branch_code,B.add1,R.tno,R.Pass_name

from Branch as B

INNER JOIN

Reservation as R ON

B.Branch_code=R.Branch_code

where tno=@tno

Order by B.Branch_code

EXEC abc 10012

Using return keyword

create proc p1 with recompile

as

declare @sal int

Select @sal=first_fare from fare where origin='new york'

return @sal

drop proc p1

declare @a int

exec @a=p1

Select @a

IF ELSE Statement

Ex:1

Select * from paemployee

if (select count(*) from paemployee where deptid='d001')>0

print 'employee exists'

else

print 'employee does not exists'

Ex:2

declare @mvar int

select @mvar=(select count(*) from paemployee where deptid='d001')

print @mvar

if @mvar>0

print 'employee exists'

else

print 'employee does not exists'

Ex : 3

if exists(Select count(*) from paemployee where deptid='d001')

print 'employee exists'

else

print 'employee does not exists'

BEGIN END

Ex:1

declare @cnt int

if (select count(*) from paemployee where deptid='d001')>0

begin

select @cnt=count(*) from paemployee where deptid='d001'

print convert(varchar(12),@cnt)+' Employee exists'

end

else

print 'sorry no employee'

SELECT * FROM paEMPloyee WHERE deptid='d001'

WHILE LOOP

Ex : 1

declare @cnt int

set @cnt =1

while

@cnt <=10

begin

print @cnt

set @cnt= @cnt+1

end

Triggers

Triggers are special stored procedures created by the user and provoked by SQL Server when data modification statements are issued. Triggers are special objects created on the table and are part of the database.

A trigger is invoked automatically whenever the data in the table is modified. They are invoked in response to INSERT, UPDATE, or DELETE Transact SQL Statements.


Creating a trigger

Syntax:

CREATE TRIGGER Trigger_name

On table

FOR {[DELETE] [,] [INSERT] [,] [UPDATE] }

[WITH ENCRYPTION]

AS Sql_statement

Examples

1. TRIGGER FOR INSERT

CREATE TRIGGER INS_TRIG

ON RESERVATION

FOR INSERT

AS

IF((SELECT FLIGHT_DATE FROM INSERTED)

BEGIN

PRINT 'ERROR'

ROLLBACK TRANSACTION

END

SELECT * FROM RESERVATION

INSERT INTO RESERVATION(TNO,FLIGHT_DATE) VALUES(1,'12/12/1999')

2. TRIGGER FOR DELETE

CREATE TRIGGER DEL_TRIG

ON BRANCH

FOR DELETE

AS

IF(SELECT COUNT(*) FROM DELETED)>2

BEGIN

PRINT 'ERROR'

ROLLBACK TRANSACTION

END

DELETE FROM BRANCH

3. TRIGGER FOR TABLE LEVEL UPDATE

CREATE TRIGGER TLT

ON FARE

FOR UPDATE

AS

IF(SELECT FIRST_FARE FROM INSERTED)<2000

BEGIN

PRINT 'THE FARE CANNOT BE LESS THAN 2000'

ROLLBACK TRANSACTION

END

SELECT * FROM FARE

UPDATE FARE SET FIRST_FARE=100 WHERE ORIGIN='NEW YORK' AND DESTINATION='AMSTERDAM'

4. TRIGGER FOR FIELD LEVEL UPDATE

CREATE TRIGGER FLT

ON

FARE

FOR UPDATE

AS

IF(UPDATE(FIRST_FARE))

BEGIN

PRINT 'YOU CANNOT UPDATE FARE'

ROLLBACK TRANSACTION

END

UPDATE FARE SET FIRST_FARE=11100 WHERE ORIGIN='NEW YORK' AND DESTINATION='AMSTERDAM'

5. TRIGGER WITH ENCRYPTION

CREATE TRIGGER ENT

ON FLIGHT

WITH ENCRYPTION

FOR INSERT,UPDATE

AS

IF(SELECT Flightdate FROM INSERTED)

BEGIN

PRINT 'THE FLIGHT DATE CANNOT BE LESS THAN TODAYS DATE'

ROLLBACK TRANSACTION

END

UPDATE FLIGHT SET FLIGHTDATE='1990-09-01' WHERE FLIGHTNO='NL35'

SP_HELPTEXT ENT

SP_HELPTRIGGER FARE

6. ENFORCING REFERENTIAL INTIGRITY USING TRIGGER

CREATE TRIGGER ERIT

ON RESERVATION

FOR INSERT,UPDATE

AS

IF((SELECT SS_CODE FROM INSERTED) NOT IN('CC','NU','WC'))

BEGIN

PRINT 'ERROR'

ROLLBACK TRANSACTION

END

UPDATE RESERVATION SET SS_CODE='NA' WHERE TNO=10012


7. CASCADING TRIGGER

SELECT * FROM FLIGHTSCHEDULE

SELECT * FROM AIRBUS

CREATE TRIGGER CASCTRIG

ON AIRBUS

FOR DELETE

AS

DELETE AIRBUS FROM DELETED,FLIGHTSCHEDULE

WHERE FLIGHTSCHEDULE.AIRBUSNO =DELETED.AIRBUSNO

DELETE FROM AIRBUS WHERE AIRBUSNO='AB04'

8. INSTEAD OF TRIGGER

CREATE TRIGGER INSTR

ON SERVICE INSTEAD OF INSERT

AS

BEGIN

SELECT SS_CODE FROM INSERTED

SELECT SS_CODE FROM DELETED

SELECT SS_CODE FROM SERVICE

END

INSERT INTO SERVICE VALUES ('SS','SDSD',2434)

DROP TRIGGER INSTR

Locks

Lock is a restriction on access to data in multi user environment. SQL Server locks users out of a specific record, field or file automatically to maintain security or prevent concurrent data manipulation problems.

Sql server uses locking to ensure transactional integrity and database consistency. Locking prevents users from reading the data being changed by other users.It prevents multiple users from changing the same data at the same time.

Type of Locks

There are three types of locks :

1. Shared Locks

Shared locks are used for the operations that do not change or update the data such as Select statement. It is used for read only operations. Shared locks allow concurrent transaction to read(Select) a resource. No other transaction can modify the data while shared locks exist on the resource. Shared locks are released as soon as the data has been read.

2. Exclusive Locks

Exclusive locks are used for data modification operations such as update, delete, or insert. Exclusive locks ensures that multiple updates cannot be made to the same resource at the same time. No other transaction can read or modify data locked with an exclusive lock.

3. Update Locks

Update locks are used for update transactions. When data is expected it is first locked using a shared lock. Once the data is found, the shared lock is upgraded to an exclusive lock to modify the data. The problem can arise when one of two sessions, having shared locks on the same resource, wants to change to an exclusive lock to modify the data, but cannot do that because the exclusive lock is not compatible with the shared lock. To avoid this deadlock problem, update locks are used. Only one session can obtain an update lock to a resource at a time.

Permissions

GRANT CREATE DATABASE, CREATE TABLE

TO Mary, John

GRANT INSERT, UPDATE, DELETE

ON authors

TO Mary, John, Tom

DENY SELECT, INSERT, UPDATE, DELETE

ON authors

TO Mary, John, Tom

Transactions

1. EXPLICIT TRANSACTION

Explicit transactions are manually configured transactions in which the beginning and the end of transaction are clearly defined.

BEGIN TRANSACTION

insert into a values(3,2)

create table a(b int,c int)

insert into a values(1,2)

COMMIT TRANSACTION

Select * from a

2. IMPLICIT TRANSACTION

Implicit transaction is enabled with the statement SET IMPLICIT_TRANSACTION ON. The user starts the Explicit Transaction whereas server starts the implicit transaction. Once the implicit transaction is set on, SQL Server will generate a continuous chain of implicit transactions until implicit transaction is set off. If any transaction in the chain of implicit transaction fails, the entire chain is aborted and all successful transactions are rolled back to their original state. This type of transaction does not need BEGIN TRANSACTION. Implicit transaction runs automatically.

SET IMPLICIT_TRANSACTIONS ON

INSERT INTO A VALUES(2,3)

INSERT INTO A VALUES(3,4)

SELECT COUNT(*) FROM A

COMMIT TRANSACTION

INSERT INTO A VALUES(2)

COMMIT TRANSACTION

SET IMPLICIT_TRANSACTIONS OFF

3. Save Point for a transaction

begin transaction

create table ab(a int, b int)

save tran t1

insert into ab values(10,20)

save tran t2

insert into ab values(30,40)

save tran t3

rollback tran t2

end transaction

CURSORS

A cursor is a database object used by applications to manipulate the data by rows instead of sets.

declare abc cursor

scroll

for

select * from memp

open abc

fetch abc

fetch next from abc

fetch prior from abc

fetch first from abc

fetch last from abc

fetch absolute 2 from abc

fetch relative -1 from abc

Types of Cursors

LOCAL

Specifies the scope of the cursor that is confined to the stored procedure or trigger in which it is created.

GLOBAL

Specifies that the scope of the cursor is global.

FORWARD_ONLY

Specifies that the cursor can only be scrolled from first to the last row. fetch next is only supported.

SCROLL

Specifies that all the fetch options are available.

STATIC

Define a cursor that makes a temporary copy of the data to be used by the cursor. No modifications

KEYSET

Specifies the order of the rows in the cursor is fixed when the cursor was opened.

DYNAMIC

Defines a cursor that reflects all the changes made to the rows in the result set as one scrolls around the cursor. Does not support FETCH ABSOLUTE

FAST_FORWARD

Specifies a FORWARD_ONLY and READ_ONLY cursor. FAST_FORWARD and FORWARD_ONLY cursors are mutually exclusive, if one is specified the other one cannot be specified

READ_ONLY

Prevents updates made through this cursor.

SCROLL_LOCKS

Specifies that the positioned updates or deletes made through the cursor are guaranteed to succeed. FAST_FORWARD cursors cannot be specified along with SCROLL_LOCKS.

OPTIMISTIC

Specifies that the positioned updates or deletes made through the cursor do not succeed, if the row is updated since it was read into the cursor.

Examples

1. SCROLL

DECLARE CUR1 CURSOR

SCROLL

FOR SELECT * FROM memp

open cur1

fetch cur1

fetch next from cur1

fetch prior from cur1

fetch first from cur1

fetch last from cur1

fetch absolute 3 from cur1

fetch relative 3 from cur1

close cur1

Select @@fetch_status

WHILE @@FETCH_STATUS=0

BEGIN

FETCH NEXT FROM CUR1

END

2. FORWARD_ONLY

DECLARE CUR2 CURSOR

FORWARD_ONLY

FOR

SELECT * FROM Memp

FOR UPDATE

CLOSE CUR2

OPEN CUR2

FETCH CUR2

UPDATE memp SET desg='Manager' WHERE CURRENT OF CUR2

DEALLOCATE CUR2

FETCH PRIOR FROM CUR2

3. KEYSET

DECLARE KEY_CUR CURSOR

KEYSET

FOR

SELECT * FROM memp

OPEN KEY_CUR

FETCH KEY_CUR

WHILE @@FETCH_STATUS=0

BEGIN

FETCH NEXT FROM KEY_CUR

END

4. DYNAMIC

DECLARE DYNA CURSOR

DYNAMIC

FOR

SELECT * FROM memp WHERE deptid='d001' FOR UPDATE

OPEN DYNA

FETCH DYNA

CLOSE DYNA

5. READ_ONLY

DECLARE READ_CUR CURSOR

READ_ONLY

FOR SELECT * FROM memp

OPEN READ_CUR

FETCH READ_CUR

DELETE FROM memp WHERE CURRENT OF READ_CUR

6. SCROLL_LOCKS

DECLARE SCRL CURSOR

SCROLL_LOCKS

FOR

SELECT * FROM emp FOR UPDATE

OPEN SCRL

FETCH NEXT FROM SCRL

UPDATE emp SET salary=4500 WHERE CURRENT OF SCRL

WHILE @@FETCH_STATUS=0

BEGIN

FETCH NEXT FROM SCRL

END

7. OPTIMISTIC

DECLARE OPTIS1 CURSOR

SCROLL

OPTIMISTIC

FOR

SELECT TNO FROM RESERVATION

FOR UPDATE

open optis1

fetch optis1

0 comments: