SQL Programming
SQL Programming
DBMS
RDBMS
•Eliminating redundant data, for example, storing the same data in more than one table.
These constraints are defined along with the column definition. These constraints can be applied to
any one column at a time.
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.
• The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key
in the second table.
• The CHECK constraint ensures that all the values in a column satisfies certain conditions.
SELECT *
FROM Person
WHERE name = “Smith”
15
Creating Indexes
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.
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]
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition]
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.
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
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;
END
GO
User Defined Functions
• SQL Server supports three types of user-defined functions
§ Scalar functions
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);
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.
• 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