SQL Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Programming in SQL Server

Differences between DBMS and RDBMS

DBMS

Data is stored in a single large table


Single record modification affects the whole database

RDBMS

Database is 'broken down' into smaller pieces


The changes will not affect the entire database
RDBMS Concept
• Increases the sharing of data and faster development of new applications
• Support a simple data structure, namely tables or relations
• Limit redundancy or replication of data
• Better integrity as data inconsistencies are avoided by storing data in one place
• Provide physical data independence so users do not have to be aware of underlying objects
• Offer logical database independence - data can be viewed in different ways by different users.
• Expandability is relatively easy to achieve by adding new views of the data as they are required.
• Support one off queries using SQL or other appropriate language.
• Better backup and recovery procedures
• Provides multiple interfaces
• Solves many problems created by other data models
• The ability to handle efficiently simple data types
• Multiple users can access which is not possible in DBMS
Normalization
Database normalization is the process of efficiently organizing data in a database.

There are two reasons of this normalization process −

•Eliminating redundant data, for example, storing the same data in more than one table.

•Ensuring data dependencies make sense.

Most used types of Normalization

1.First Normal Form (1NF)


2.Second Normal Form (2NF)
3.Third Normal Form (3NF)
First Normal Form (1NF)

There are no repeating or duplicate fields.


Each cell contains only a single value.
Each record is unique.
Identified by primary key
Second Normal Form (2 NF)
Divide 1 NF table in to tables
Non-key fields depend on primary key
Third Normal Form (3 NF)
No non-key fields depends upon another
All non-key fields depends only on the Primary Key
Constraints
Constraints are the rules enforced on the data columns of a table.

Column Level Constraint

These constraints are defined along with the column definition. These constraints can be applied to
any one column at a time.

Table Level Constraints

If the data constraint attached to a specific cell in a table references the content of another cell in the
table then the table level constraint is used.
NOT NULL Constraint
• Ensures that a column cannot have NULL value.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
)
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL
DEFAULT Constraint
• Provides a default value for a column when none is specified.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID)
)
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00

ALTER TABLE CUSTOMERS


ALTER COLUMN SALARY DROP DEFAULT
UNIQUE Constraint

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
)

ALTER TABLE CUSTOMERS


ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);
Primary Key
• Uniquely identifies each row/record in a database table.

ALTER TABLE CUSTOMERS


ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME)

ALTER TABLE CUSTOMERS DROP PRIMARY KEY


Foreign Key

• Uniquely identifies a row/record in any of the given database table

• The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key
in the second table.

ALTER TABLE ORDERS


ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID)
CHECK Constraint

• The CHECK constraint ensures that all the values in a column satisfies certain conditions.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
)

ALTER TABLE CUSTOMERS


MODIFY AGE INT NOT NULL CHECK (AGE >= 18 )
Indexes

REALLY important to speed up query processing time.

Suppose we have a relation

Person (name, age, city)

SELECT *
FROM Person
WHERE name = “Smith”

Sequential scan of the file Person may take long

15
Creating Indexes

Indexes can be created on more than one attribute:

CREATE INDEX doubleindex ON


Example:
Person (age, city)

SELECT *
Helps in: FROM Person
WHERE age = 55 AND city = “Seattle”

SELECT *
and even in: FROM Person
WHERE age = 55

SELECT *
But not in: FROM Person
WHERE city = “Seattle” 16
The Index Selection Problem
• We are given a workload = a set of SQL queries plus how often
they run
• What indexes should we build to speed up the workload ?
• FROM/WHERE clauses  favor an index
• INSERT/UPDATE clauses  discourage an index

17
SQL Statement Types
DML - stands for Data Manipulation Language, it’s the part
of SQL that deals with querying updating and inserting
records in tables.

DDL – stands for Data Definition Language, it’s the part of


SQL that deals with the construction and alteration of
database structures like tables, views and the further
entities inside these tables like columns. It may be used to
set the properties of columns as well
DDL Statements
• CREATE DATABASE
CREATE DATABASE DatabaseName
• DROP DATABASE
DROP DATABASE DatabaseName
• SELECT Database
USE DatabaseName
• CREATE TABLE
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
)
• DROP TABLE
DROP TABLE table_name
DML Statement
INSERT Query
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN)

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN)

Populate one table using another table


INSERT INTO first_table_name [(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition]

SELECT Query
SELECT column1, column2, columnN FROM table_name
DML Statement
WHERE, AND and OR Conjunctive Operators
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN]

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]

Update, Delete Statement

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition]

DELETE FROM table_name


WHERE [condition]
DML Statement
LIKE Clause

The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in
conjunction with the LIKE operator.

The percent sign (%)


The underscore ( _ )

WHERE SALARY LIKE '200%'


WHERE SALARY LIKE '%2'
Finds any values that start with 200.
Finds any values that end with 2.

WHERE SALARY LIKE '%200%'


WHERE SALARY LIKE '_2%3'
Finds any values that have 200 in any position.
Finds any values that have a 2 in the second position and
end with a 3.
WHERE SALARY LIKE '_00%'
Finds any values that have 00 in the second and third WHERE SALARY LIKE '2___3'
positions
Finds any values in a five-digit number that start with 2 and
end with 3.
WHERE SALARY LIKE '2_%_%'
Finds any values that start with 2 and are at least 3
characters in length
Using Joins
There are different types of joins available in SQL

INNER JOINS - Returns rows when there is a match in both tables.

LETF OUTER JOIN - returns all rows from the left table, even if there are no matches in the right
table

RIGHT OUTER JOIN - returns all rows from the right table, even if there are no matches in the left
table.

SELF JOIN - Single table is joined to itself; the second table is same as the first but renamed using
an alias.

CROSS JOIN (cartesian product) - returns the Cartesian product of the sets of records from the two
or more joined tables
Stored Procedures

• A stored procedure is a collection of T-SQL statements that SQL


Server compiles into a single execution plan.

• Procedure is stored in cache area of memory when the stored


procedure is first executed so that it can be used repeatedly. SQL
Server does not have to recompile it every time the stored
procedure is run.

• It can accept input parameters, return output values as


parameters, or return success or failure status messages.
Creating Stored Procedure

Syntax:
CREATE PROCEDURE <Procedure_Name,>
-- Add the parameters for the stored procedure here
<@Param1> <Datatype_For_Param1> = <Default_Value_For_Param1>,
<@Param2> <Datatype_For_Param2> = <Default_Value_For_Param2>
AS
DECLARE <@Param3> <Datatype_For_Param3>
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert / Update / Delete / Select statements for procedure here

END
GO
User Defined Functions
• SQL Server supports three types of user-defined functions

§ Scalar functions

§ Inline table-valued functions

§ Multi-statement table-valued functions


Scalar functions
CREATE FUNCTION Revenue_Day (@Date datetime) Returns money
AS
BEGIN
DECLARE @total money
SELECT @total = sum(sali_Quantity * sali_price)
FROM Sales_Orders s, Sales_Orders_Items si
WHERE s.sal_number = si.sal_number and year(sal_date) = year(@Date)
and month(sal_date) = month(@Date) and day(sal_date)= day(@Date)
RETURN @total
END

Use:
select dbo.Revenue_In_Day(GETDATE())
Inline Table-valued Functions Example
CREATE FUNCTION AveragePricebyItems (@price money = 0.0) RETURNS table
AS
RETURN ( SELECT Ite_Description, Ite_Price
FROM Items
WHERE Ite_Price > @price)

Use:
select * from AveragePricebyItems (15.00)
Multi-statement Table-Valued Functions Example
CREATE FUNCTION AveragePricebyItems2 (@price money = 0.0) RETURNS @table table
(Description varchar(50) null, Price money null) AS
begin
insert @table SELECT Ite_Description, Ite_Price
FROM Items
WHERE Ite_Price > @price
return
end

Use:
select * from AveragePricebyItems2 (15.00)
Triggers
A trigger is a special kind of a store procedure that executes in response to certain action on the
table like insertion, deletion or updation of data.

Types Of Triggers

• After Triggers (For Triggers) These triggers run after an insert, update or delete on a table.
AFTER INSERT Trigger.
AFTER UPDATE Trigger.
AFTER DELETE Trigger.

• Instead Of Triggers These can be used as an interceptor for anything that anyone tried to do on our
table or view.
INSTEAD OF INSERT Trigger.
INSTEAD OF UPDATE Trigger.
INSTEAD OF DELETE Trigger.
After Insert/ Update/ Delete Trigger
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]
FOR INSERT/ UPDATE/ DELETE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=i.Emp_ID from inserted i;


select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted/ Updated/ Deleted Record .';

insert into Employee_Test_Audit


(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER INSERT/ UPDATE/ DELETE trigger fired.'


GO
Instead Of Insert/ Update/ Delete Triggers
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test]
INSTEAD OF DELETE
AS
declare @emp_id int;
declare @emp_name varchar(100);
declare @emp_sal int;

select @emp_id=d.Emp_ID from deleted d;


select @emp_name=d.Emp_Name from deleted d;
select @emp_sal=d.Emp_Sal from deleted d;

BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO
What Is a Transaction
• A transaction is a series of operations that are performed as one
logical unit of work.

• Transactions allow SQL Server to ensure a certain level of data


integrity and data recoverability.

• The transaction log, which every database must have, keeps a


record of all transactions that make any type of modification
(insert, update, or delete) to the database. SQL Server uses this
transaction log to recover data in case of errors or system failures.
Transactions
• BEGIN TRANSACTION
– Marks the starting point of an explicit transaction for a connection.

• COMMIT TRANSACTION
– Used to end a transaction successfully if no errors were encountered. All data
modifications made in the transaction become a permanent part of the database.
Resources held by the transaction are freed.

• ROLLBACK TRANSACTION
– Used to erase a transaction in which errors are encountered. All data modified by the
transaction is returned to the state it was in at the start of the transaction. Resources held
by the transaction are freed.
Transaction Sample
CREATE PROCEDURE SP_ChangeSupplier @FromSID INT,@ToSID INT, @Result INT OUTPUT AS
-- Declare and initialize a variable to hold @@ERROR.
DECLARE @ErrorSave INT
Select @ErrorSave = 0
-- Begin Transaction
Begin Transaction
Update Products
Set SupplierID = @ToSID
WHERE SupplierID =@FromSID
-- Check if the update is successful
IF (@@ERROR <> 0)
Begin
Select @ErrorSave = -1
Rollback Transaction -- rollback
end
else
commit Transaction -- commit
Select @result = @ErrorSave
GO
Thank You

You might also like