Sql advanced - case-Study for Students

37
SQL Training Material (Advanced) Version 1.1 Updated as on 21-Jan-2011 Only for internal circulation Page 1 of 37

Transcript of Sql advanced - case-Study for Students

SQL Training Material (Advanced)

Version 1.1

Updated as on 21-Jan-2011

Only for internal circulation Page 1 of 37

Contents

INTRODUCTION TO SQL ................................................................................................................................... 4

SQL ........................................................................................................................................................... 4

SQL OBJECTS:............................................................................................................................................... 4

SQL QUERIES ................................................................................................................................................ 4

DATA DEFINITION LANGUAGE (DDL) ............................................................................................................ 5

DATA MANIPULATION LANGUAGE (DML) ...................................................................................................... 5

SQL ALIASES ................................................................................................................................................. 5

THE SELECT STATEMENT .............................................................................................................................. 6

THE WHERE CLAUSE .................................................................................................................................... 6

ORDER BY ................................................................................................................................................... 8

IN OPERATOR ................................................................................................................................................. 8

BETWEEN ... AND ........................................................................................................................................ 8 SQL FUNCTIONS ............................................................................................................................................. 9

TYPES OF FUNCTIONS ................................................................................................................................. 9

SQL GROUP BY AND HAVING .................................................................................................................. 11

GROUP BY ............................................................................................................................................. 11

HAVING CLAUSE ..................................................................................................................................... 11

TOP, DISTINCT, UNION AND UNION ALL ............................................................................................... 12

TOP .......................................................................................................................................................... 12

DISTINCT .................................................................................................................................................. 12

UNION AND UNION ALL ............................................................................................................................. 12

DIFFERENCE BETWEEN UNION AND UNION ALL .................................................................................... 12

JOINS AND KEYS ........................................................................................................................................... 13

THE INSERT INTO STATEMENT ................................................................................................................... 14

THE UPDATE STATEMENT ........................................................................................................................... 14

THE DELETE STATEMENT .............................................................................................................................. 14

CREATE DATABASE, TABLE .......................................................................................................................... 15

CREATE A DATABASE ................................................................................................................................ 15

CREATE A TABLE ...................................................................................................................................... 15

SQL DROP TABLE ................................................................................................................................. 17

SQL ALTER TABLE ................................................................................................................................ 17

SQL CONSTRAINTS....................................................................................................................................... 18

SQL NOT NULL CONSTRAINT ..................................................................................................................... 19

SQL UNIQUE CONSTRAINT ......................................................................................................................... 20

SQL UNIQUE CONSTRAINT ON CREATE TABLE .................................................................................... 20

SQL UNIQUE CONSTRAINT ON ALTER TABLE ....................................................................................... 20

TO DROP A UNIQUE CONSTRAINT .......................................................................................................... 21

Only for internal circulation Page 2 of 37

SQL PRIMARY KEY CONSTRAINT ......................................................................................................................... 22

SQL PRIMARY KEY CONSTRAINT ON CREATE TABLE ......................................................................... 22

SQL PRIMARY KEY CONSTRAINT ON ALTER TABLE ............................................................................ 22

TO DROP A PRIMARY KEY CONSTRAINT ............................................................................................... 23

FOREIGN KEY CONSTRAINT ....................................................................................................................... 24

SQL FOREIGN KEY CONSTRAINT ON CREATE TABLE ......................................................................... 24

SQL FOREIGN KEY CONSTRAINT ON ALTER TABLE ............................................................................ 25

TO DROP A FOREIGN KEY CONSTRAINT ............................................................................................... 25

CHECK CONSTRAINT ................................................................................................................................... 26

SQL CHECK CONSTRAINT ON CREATE TABLE ..................................................................................... 26

SQL CHECK CONSTRAINT ON ALTER TABLE ........................................................................................ 26

TO DROP A CHECK CONSTRAINT ........................................................................................................... 27

DEFAULT CONSTRAINT ............................................................................................................................... 27

SQL DEFAULT CONSTRAINT ON CREATE TABLE .................................................................................. 27

SQL DEFAULT CONSTRAINT ON ALTER TABLE ..................................................................................... 28

TO DROP A DEFAULT CONSTRAINT ....................................................................................................... 28

INDEXES........................................................................................................................................................ 28

SQL CREATE INDEX SYNTAX ................................................................................................................ 28

SQL CREATE UNIQUE INDEX SYNTAX ................................................................................................. 28

CREATE INDEX EXAMPLE ...................................................................................................................... 29

THE DROP INDEX STATEMENT ............................................................................................................... 29

VIEWS ........................................................................................................................................................... 30

SQL CREATE VIEW STATEMENT ............................................................................................................ 30

SQL CREATE VIEW SYNTAX. ................................................................................................................. 30

SQL CREATE VIEW EXAMPLES .............................................................................................................. 30

SQL UPDATING A VIEW ............................................................................................................................. 31

SQL DROPPING A VIEW ............................................................................................................................ 31

STORED PROCEDURE .................................................................................................................................... 32

CREATE PROCEDURE ......................................................................................................................... 32

SQL CURSOR ............................................................................................................................................ 34

DECLARE CURSOR .............................................................................................................................. 34

OPEN ...................................................................................................................................................... 34

FETCH .................................................................................................................................................... 34

CLOSE .................................................................................................................................................... 35

SQL FUNCTIONS ........................................................................................................................................... 36

CREATE FUNCTION .............................................................................................................................. 36

Only for internal circulation Page 3 of 37

Introduction to SQL

SQL

SQL stands for Structured Query Language. It is an ANSI (American National Standards Institute)

standard computer language for accessing and manipulating database systems. SQL statements are

used to retrieve and update data in a database. SQL works with database programs like MS Access,

DB2, Informix, MS SQL Server, Oracle, Sybase, etc.

Unfortunately, there are many different versions of the SQL language, but to be in compliance with the

ANSI standard; they must support the same major keywords in a similar manner (such as SELECT,

UPDATE, DELETE, INSERT, WHERE, and others).

Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL

standard! SQL comes in many flavors. Oracle databases utilize their proprietary PL/SQL. Microsoft

SQL Server makes use of Transact-SQL. However, all of these variations are based upon the industry

standard ANSI SQL.

SQL Objects:

The basic SQL objects are Database, Table, View, UDF and Stored Procedure.

• Database: A database is a collection of related data. A database consists of other SQL object

such as tables, views etc.

• Table: A database most often contains one or more tables. Each table is identified by a name

(e.g. "Customers" or "Orders"). Tables contain records (rows) with data.

• View: A view is the logical representation of data of one or more tables.

• UDF: A user-defined function, which is a SQL routine that returns a value.

• Stored Procedure: A stored procedure is a group of SQL statements that form a logical unit and

perform a particular task.

SQL Queries

With SQL, we can query a database and have a result set returned. The two types of SQL are:

Only for internal circulation Page 4 of 37

Data Definition Language (DDL)

The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We

can also define indexes (keys), specify links between tables, and impose constraints between database

tables.

The most important DDL statements in SQL are:

• CREATE TABLE - creates a new database table

• ALTER TABLE - alters (changes) a database table

• DROP TABLE - deletes a database table

Data Manipulation Language (DML)

SQL (Structured Query Language) is the syntax for executing queries. But the SQL language also

includes syntax to update, insert, and delete records. These query and update commands together form

the Data Manipulation Language (DML) part of SQL:

• SELECT - extracts data from a database table

• UPDATE - updates data in a database table

• DELETE - deletes data from a database table

• INSERT INTO - inserts new data into a database table

SQL Aliases

With SQL, aliases can be used for column names and table names.

Column Name Alias

The syntax is:

• SELECT column AS column_alias FROM table

Table Name Alias

The syntax is:

• SELECT column FROM table AS table_alias

Only for internal circulation Page 5 of 37

The SELECT Statement

The SELECT Statement

The SELECT statement is used to select data from a table. The tabular result is stored in a result

table (called the result-set).

• SELECT column_name(s) FROM table_name

Select Some Columns

1) To select the columns named "LastName" and "FirstName", use a SELECT statement like this:

• SELECT first_name_c, last_name_c, phone_no_c, mail_c FROM usr_info_tbl

• SELECT column FROM table AS table_alias

2) To select all columns from the "Persons" table, use a * symbol instead of column names, like this:

• SELECT * FROM usr_info_tbl ORDER BY first_name_c

The WHERE Clause

• The WHERE clause is used to specify a selection criterion.

The WHERE Clause

To conditionally select data from a table, a WHERE clause can be added to the SELECT statement.

Syntax

• SELECT column FROM table WHERE column operator value.

With the WHERE clause, the following operators can be used:

Comparison Operators

Operator Description = Equal

<> Not equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

Only for internal circulation Page 6 of 37

Logical Operators

Operator

BETWEEN

AND, OR

LIKE

Description

Between an inclusive range

The AND operator displays a row if ALL

conditions listed are true. The OR operator

displays a row if ANY of the conditions

listed are true.

Search for a pattern

List the users whose first name is 'john'

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

WHERE first_name_c='john' ORDER BY FullName

List the users whose firstname starts with 'john'

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

WHERE first_name_c like 'john%' ORDER BY FullName

List the users whose firstname contains 'john'

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

WHERE first_name_c like '%john%' ORDER BY FullName

List the users whose firstname ends with 'john'

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

WHERE first_name_c like '%john' ORDER BY FullName

List users from the country "US" or "UK"

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

WHERE country='US' or country=‘UK’ ORDER BY FullName

List users from 'US' whose first name starts with 'John'

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

WHERE first_name_c like '%john' and country='US' ORDER BY FullName

Only for internal circulation Page 7 of 37

ORDER BY

The ORDER BY keyword is used to sort the result and display the list in an ordered format. You can order

by more than one field by specifying it as a comma separated one.

ASC - Ascending Order (default choice)

DESC - Descending Order

• SELECT first_name_c+' '+last_name_c as FullName, phone_no_c, mail_c FROM usr_info_tbl

ORDER BY FullName DESC, mail_c

IN Operator

The IN operator may be used if you know the exact value you want to return for at least one of the

columns.

• SELECT column_name FROM table_name WHERE column_name IN (value1, value2,..)

• SELECT first_name_c FROM usr_info_tbl WHERE user_id_c in (‘[email protected]’,’[email protected]’)

BETWEEN ... AND

The BETWEEN ... AND operator selects a range of data between two values. These values can be

numbers, text, or dates.

SELECT column_name FROM table_name

WHERE column_name

BETWEEN value1 AND value2

List the users whose info modified between the dates 1/1/2006 and till today.

• SELECT user_id_c FROM usr_info_tbl WHERE changed_date_dt between ‘1/1/2006’ and getdate ()

Only for internal circulation Page 8 of 37

SQL Functions

SQL has a lot of built-in functions for counting and calculations.

Function Syntax

The syntax for built-in SQL functions is:

• SELECT function (column) FROM table

Types of Functions

There are several basic types and categories of functions in SQL. The basic types of functions are:

• Aggregate Functions • String functions • Date and Time functions • Mathematical functions

Aggregate functions

Aggregate functions operate against a collection of values, but return a single value.

Note: If used among many other expressions in the item list of a SELECT statement, the SELECT must have

a GROUP BY clause!!

Aggregate functions in SQL Server

Function Description

AVG (column) Returns the average value of a column

COUNT (column) Returns the number of rows (without a NULL value) of a column

COUNT (*) Returns the number of selected rows

COUNT (DISTINCT column) Returns the number of distinct results

MAX (column) Returns the highest value of a column

MIN (column) Returns the lowest value of a column

SUM (column) Returns the total sum of a column

Only for internal circulation Page 9 of 37

String Functions

These scalar functions perform an operation on a string input value and return a string or numeric value.

ASCII NCHAR SOUNDEX

CHAR PATINDEX SPACE

CHARINDEX REPLACE STR

DIFFERENCE QUOTENAME STUFF

LEFT REPLICATE SUBSTRING

LEN REVERSE UNICODE

LOWER RIGHT UPPER

LTRIM RTRIM

Only for internal circulation Page 10 of 37

SQL GROUP BY and HAVING

Aggregate functions (like SUM) often need an added GROUP BY functionality.

GROUP BY...

GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of all

column values every time they are called, and without the GROUP BY function it was impossible to find

the sum for each individual group of column values.

The syntax for the GROUP BY function is:

• SELECT column, SUM (column) FROM table GROUP BY column

The GROUP BY clause contains the following components:

• One or more aggregate-free expressions. These are usually references to the grouping columns. • Typically, the HAVING clause is used with the GROUP BY clause, although HAVING can be

specified separately.

• SELECT user_id_c, count (ssn_id_i) AS visited_count

FROM usr_ssn_track_tbl sst

GROUP BY user_id_c ORDER BY visited_count desc

HAVING Clause

Used to add filter condition for aggregates in the SELECT statement.

• SELECT user_id_c, count (ssn_id_i) AS visited_count

FROM usr_ssn_track_tbl sst

GROUP BY user_id_c HAVING

count(ssn_id_i)>100 ORDER BY

visited_count desc

Only for internal circulation Page 11 of 37

TOP, DISTINCT, UNION AND UNION ALL

Top

The Top logical and physical operator will scan the input, returning only the first specified number or

percent of rows. The Argument column can optionally contain a list of the columns that are being checked

for ties. In update plans, the Top operator is used to enforce row count limits.

Select top 5 user_id_c from usr_info_tbl order by user_id_c

Note: “Top” operator is specific to MS SQL. If you want to do the same in MYSQL, then you can do it via

“Limit” operator

Distinct

The Distinct logical operator scans the input, removing duplicates.

Select DISCTINCT first_name_c from usr_info_tbl to remove duplicates.

Union And Union All

The Union logical operator scans multiple inputs, outputting each row scanned and removing duplicates,

combines the results of two or more queries into a single result set consisting of all the rows belonging to

all queries in the union.

Two basic rules for combining the result sets of two queries with UNION are:

• The number and the order of the columns must be identical in all queries. • The data types must be compatible.

Difference between UNION AND UNION ALL

UNION

Specifies that multiple result sets are to be combined and returned as a single result set.

UNION ALL

Incorporates all rows into the results, including duplicates.

Only for internal circulation Page 12 of 37

Joins and Keys

Sometimes we have to select data from two or more tables to make our result complete. We have to

perform a join.

Tables in a database can be related to each other with keys. A primary key is a column with a unique

value for each row. The purpose is to bind data together, across tables, without repeating all of the data in

every table.

There are two types of Joins.

Inner join - The Inner Join logical operator returns each row that satisfies the join of the first (top) input with

the second (bottom) input. For each row in the first table, there should be a row in the joining

table

• SELECT a.first_name_c+' '+a.last_name_c FROM usr_info_tbl a INNER JOIN usr_login_tbl b ON

b.user_id_c=a.user_id_c

Outer join - Outer joins, however, return all rows from at least one of the tables or views mentioned in the

FROM clause, as long as those rows meet any WHERE or HAVING search conditions. All rows

are retrieved from the left table referenced with a left outer join, and all rows from the right table

referenced in a right outer join. All rows from both tables are returned in a full outer join

• SELECT a.first_name_c+' '+a.last_name_c FROM usr_info_tbl a LEFT OUTER JOIN usr_login_tbl b

ON b.user_id_c=a.user_id_c

Only for internal circulation Page 13 of 37

The INSERT INTO Statement

The INSERT INTO statement is used to insert new rows into a table.

Syntax

• INSERT INTO table_name VALUES (value1, value2,....)

You can also specify the columns for which you want to insert data:

• INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

Insert a New Row

• INSERT INTO usr_info_tbl (fist_name_c, last_name_c) values (‘Arun’,’JeyPrakash’)

The UPDATE Statement

The UPDATE statement is used to modify the data in a table.

Syntax

• UPDATE table_name SET column_name = new_value WHERE column_name = some_value

• UPDATE usr_info_tbl SET first_name_c=‘Arul’ Where user_id_c=’[email protected]

The Delete Statement

The DELETE statement is used to delete rows in a table.

Syntax

• DELETE FROM table_name WHERE column_name = some_value • DELETE FROM usr_info_tbl WHERE user_id_c=’[email protected]

Only for internal circulation Page 14 of 37

Create Database, Table

Create a Database

To create a database:

• CREATE DATABASE database_name

Create a Table

To create a table in a database:

• CREATE TABLE table_name

(

column_name1 data_type,

column_name2 data_type,

.......

)

Example

This example demonstrates how you can create a table named "Person", with four columns. The column

names will be "LastName", "FirstName", "Address", and "Age":

• CREATE TABLE Person

(

LastName varchar,

FirstName varchar,

Address varchar,

Age int

)

This example demonstrates how you can specify a maximum length for some columns:

CREATE TABLE Person

(

LastName varchar(30),

FirstName varchar,

Only for internal circulation Page 15 of 37

Address varchar,

Age int (3)

)

The data type specifies what type of data the column can hold. The table below contains the most

common data types in SQL:

Data Type Description

Integer (size) Hold integers only. The maximum number of digits is specified in

int (size) parenthesis.

smallint (size)

tinyint (size)

decimal (size, d) Hold numbers with fractions. The maximum number of digits is specified

numeric(size, d) in "size". The maximum number of digits to the right of the decimal is

specified in "d".

char (size) Holds a fixed length string (can contain letters, numbers, and special

characters). The fixed size is specified in parenthesis.

varchar (size) Holds a variable length string (can contain letters, numbers, and special

characters). The maximum size is specified in parenthesis.

Only for internal circulation Page 16 of 37

SQL DROP TABLE

Delete a Table or Database

To delete a table (the table structure, attributes, and indexes will also be deleted):

• DROP TABLE table_name

To delete a database:

• DROP DATABASE database_name

Truncate a Table

What if we only want to get rid of the data inside a table, and not the table itself ?

Use the TRUNCATE TABLE command (deletes only the data inside the table):

• TRUNCATE TABLE table_name

SQL ALTER TABLE

ALTER TABLE

The ALTER TABLE statement is used to add or drop columns in an existing table.

• ALTER TABLE table_name

Note: Some database systems for example DB2 don't allow the dropping of a column in a database table

(DROP COLUMN column_name).

Only for internal circulation Page 17 of 37

SQL Constraints

Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a

table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE

statement). Following are the constraints.

• NOT NULL • UNIQUE • PRIMARY KEY • FOREIGN KEY • CHECK • DEFAULT

Only for internal circulation Page 18 of 37

SQL NOT NULL Constraint

The NOT NULL constraint enforces a column to NOT accept NULL values i.e. always contain a value. This

means that you cannot insert a new record, or update a record without adding a value to this field.

Example:

The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values.

Only for internal circulation Page 19 of 37

SQL UNIQUE Constraint

The UNIQUE constraint uniquely identifies each record in a database table.

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or

set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per

table.

SQL UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is

created.

To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use

the following SQL syntax.

SQL UNIQUE Constraint on ALTER TABLE

To create a UNIQUE constraint on column(s) when the table is already created, use the following SQL.

Only for internal circulation Page 20 of 37

To DROP a UNIQUE Constraint

To drop a UNIQUE constraint, use the following SQL syntax.

Only for internal circulation Page 21 of 37

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values. Each table should have a primary key, and each table

can have only ONE primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created.

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple

columns, use the following SQL syntax.

SQL PRIMARY KEY Constraint on ALTER TABLE

To create a PRIMARY KEY constraint on column(s) when the table is already created, use the following

SQL.

Only for internal circulation Page 22 of 37

Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must

already have been declared to not contain NULL values (when the table was first created).

To DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL.

Only for internal circulation Page 23 of 37

FOREIGN KEY Constraint

A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's

illustrate the foreign key with an example. Look at the following two tables: The

"Persons" table:

The "Orders" table:

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table.

The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key

column, because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY Constraint on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created.

Only for internal circulation Page 24 of 37

SQL FOREIGN KEY Constraint on ALTER TABLE

To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created,

use the following SQL.

To DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

Only for internal circulation Page 25 of 37

CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values in

other columns in the row.

SQL CHECK Constraint on CREATE TABLE

The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is

created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than

0.

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use

the following SQL syntax.

SQL CHECK Constraint on ALTER TABLE

To create a CHECK constraint on the "P_Id" column when the table is already created, use the following

SQL.

ALTER TABLE Persons

Only for internal circulation Page 26 of 37

ADD CHECK (P_Id>0)

To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use

the following SQL SQL.

ALTER TABLE Persons

ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint

To drop a CHECK constraint, use the following SQL.

ALTER TABLE Persons

DROP CONSTRAINT chk_Person

DEFAULT Constraint

The DEFAULT constraint is used to insert a default value into a column. The default value will be added

to all new records, if no other value is specified.

SQL DEFAULT Constraint on CREATE TABLE

The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is

created.

The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE().

Only for internal circulation Page 27 of 37

SQL DEFAULT Constraint on ALTER TABLE

To create a DEFAULT constraint on the "City" column when the table is already created, use the following

syntax.

To DROP a DEFAULT Constraint

To drop a DEFAULT constraint, use the following syntax.

Indexes

An index can be created in a table to find data more quickly and efficiently.

The users cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes

also need an update). So you should only create indexes on columns (and tables) that will be frequently

searched against.

SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed.

CREATE INDEX index_name

ON table_name (column_name)

SQL CREATE UNIQUE INDEX Syntax

Only for internal circulation Page 28 of 37

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name

ON table_name (column_name)

Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax

for creating indexes in your database.

CREATE INDEX Example

The SQL statement below creates an index named "PIndex" on the "LastName" column in the "Persons"

table.

CREATE INDEX PIndex

ON Persons (LastName)

If you want to create an index on a combination of columns, you can list the column names within the

parentheses, separated by commas.

CREATE INDEX PIndex

ON Persons (LastName, FirstName)

The DROP INDEX Statement

The DROP INDEX statement is used to delete an index in a table.

DROP INDEX Syntax for MS Access:

DROP INDEX index_name ON table_name

DROP INDEX Syntax for MS SQL Server:

DROP INDEX table_name.index_name

DROP INDEX Syntax for DB2/Oracle:

DROP INDEX index_name

DROP INDEX Syntax for MySQL:

ALTER TABLE table_name DROP INDEX index_name

Only for internal circulation Page 29 of 37

Views

A view is a virtual table.

SQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more

real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data

were coming from one single table.

SQL CREATE VIEW Syntax.

CREATE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's

SQL statement, every time a user queries a view.

SQL CREATE VIEW Examples

If you have the Northwind database you can see that it has several views installed by default.

The view "Current Product List" lists all active products (products that are not discontinued) from the

"Products" table. The view is created with the following SQL.

CREATE VIEW [Current Product List] AS

SELECT ProductID,ProductName

FROM Products

WHERE Discontinued=No

We can query the view above as follows:

Only for internal circulation Page 30 of 37

SELECT * FROM [Current Product List]

Another view in the Northwind database calculates the total sale for each category in 1997. Note that this

view selects its data from another view called "Product Sales for 1997":

CREATE VIEW [Category Sales For 1997] AS

SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales

FROM [Product Sales for 1997]

GROUP BY CategoryName

We can query the view above as follows:

SELECT * FROM [Category Sales For 1997]

We can also add a condition to the query. Now we want to see the total sale only for the category

"Beverages":

SELECT * FROM [Category Sales For 1997]

WHERE CategoryName='Beverages'

SQL Updating a View

You can update a view by using the following syntax.

CREATE OR REPLACE OR ALTER VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition

SQL Dropping a View

You can delete a view with the DROP VIEW command. Find below the syntax.

DROP VIEW view_name

Only for internal circulation Page 31 of 37

Stored Procedure

A stored procedure is a set of one or more SQL statements that are stored together in database.

Stored procedure can improve database performance because the SQL statements in each procedure

are only compiled and optimized the first time they are executed.

Coding business logic into a single stored procedure also offers a single point of control for ensuring that

business rules are correctly enforced.

The results do not have to be returned to the client to have the conditional logic applied; all of the work is

done on the server.

CREATE PROCEDURE

To create a stored procedure, use CREATE PROCEDURE statement.

Syntax

The following example retrieves ContactNumber from UserInfo table for the given UserID.

-- =============================================

-- Author: Vernalis Systems

-- Create date: 12-Jan-2011 -- Description: To -- ============================================= CREATE PROCEDURE [dbo].MySampleSlect

-- Add the parameters for the stored procedure here

Only for internal circulation Page 32 of 37

@UserID int = 0

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

-- Insert statements for procedure here

SELECT ContactNumber FROM UserInfo WHERE UserID = @UserID

END

GO

To use the stored procedure you send a request for it to be executed. When server receives the request,

it executes the stored procedure. Find below the syntax.

EXECUTE <ProcedureName>

Example

EXECUTE dbo.MySampleSlect

In addition to SELECT statement, a stored procedure can contain the SQL statements such as INSERT,

UPDATE and DELETE.

A trigger is a special type of procedure that executes when rows are inserted, updated or deleted from

table.

A user defined function (UDF) is a special type of procedure that can return a value or a table.

Only for internal circulation Page 33 of 37

SQL CURSOR

In SQL procedures, a cursor make it possible to define a result set (a set of data rows), and perform

complex logic on a row by row basis. By using the same mechanics, an SQL procedure can also define a

result set and return it directly to the caller of the SQL procedure or to a client application.

A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only reference one row at

a time, but can move to other rows of the result set as needed.

To use cursors in SQL procedures, you need to do the following:

1. Declare a cursor that defines a result set. 2. Open the cursor to establish the result set. 3. Fetch the data into local variables as needed from the cursor, one row at a time. 4. Close the cursor when done

To work with cursors you must use the following SQL statements:

• DECLARE CURSOR

• OPEN

• FETCH

• CLOSE

DECLARE CURSOR

Before you use a CURSOR, you’ll need to declare it. The basic form looks like:

DECLARE <CursorName> CURSOR for

SELECT <field1>, <field2> FROM <MyTable>

WHERE <WhereClause>

OPEN

Once we have the cursor declared, we need to OPEN it to cause it to execute:

OPEN <CursorName>

FETCH

To move to the first record, we have to FETCH the row:

Only for internal circulation Page 34 of 37

FETCH NEXT FROM <CursorName>

INTO @field1, @field2

CLOSE

After processing all the rows, we need to close the cursor.

CLOSE <CursorName>

There is a special variable in SQL called @@FETCH_STATUS that will be zero (0) as long as the fetch was

able to retrieve a row, so you’ll want to set up a while loop after your first fetch that checks the status and then

processes the data. Right before the end of the while loop you will issue another FETCH.

DECLARE @P_Id INT

DECLARE @FirstName VARCHAR(255)

DECLARE @LastName VARCHAR(255)

DECLARE @City VARCHAR(255)

DECLARE cursorPerson CURSOR for

SELECT P_Id, LastName, FirstName, City FROM Persons

WHERE P_Id > 5

OPEN cursorPerson

FETCH NEXT FROM cursorPerson

INTO @P_Id, @FirstName, @LastName, @City

While @@FETCH_STATUS = 0

Begin

IF @City = 'Chennai'

SELECT @FirstName + ' ' + @LastName

FETCH NEXT FROM cursorName

INTO @P_Id, @FirstName, @LastName, @City

End

CLOSE cursorPerson

Only for internal circulation Page 35 of 37

SQL Functions

A function is a named SQL block which is similar to a procedure. The major difference between a

procedure and a function is, a function must always return a value, but a procedure may or may not return

a value.

CREATE FUNCTION

The General Syntax to create a function is:

CREATE FUNCTION <FunctionName>

(

-- Add the parameters for the function here

<@Param1, sysname, @p1> <Data_Type_For_Param1, , int>

)

RETURNS <Function_Data_Type, ,int>

AS

BEGIN

-- Declare the return variable here

DECLARE <@ResultVar, sysname, @Result> <Function_Data_Type, ,int>

-- Add the T-SQL statements to compute the return value here

SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1>

-- Return the result of the function

RETURN <@ResultVar, sysname, @Result>

END

GO

Following example will get two input arguments and do multiplication and send back the result.

CREATE FUNCTION dbo.fnMult

(

@num1 INT,

@num2 INT

)

RETURNS INT

Only for internal circulation Page 36 of 37

AS

BEGIN

RETURN (@num1 * @num2)

END

GO

Following example will return a table as a result for a given city.

CREATE FUNCTION fnGetPersonByCity

(

@city VARCHAR(255)

)

RETURNS TABLE

AS

RETURN

(

SELECT FirstName + ' ' + LastName AS PersonName

FROM Persons

WHERE City = @city

)

The following example uses the user defined function (fnGetPersonByCity) that we created as physical

table.

SELECT * FROM fnGetPersonByCity(‘Chennai’)

Only for internal circulation Page 37 of 37