Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

1. Nth highest salary.

select sal from emp a where N = (select count(distinct sal) from emp b where
a.sal <= b.sal)

or

select top n salary


from
( select distinct top n salary from employee where order by salary desc)
Order by salary

Difference between Temporary Tables and Table Variables.

Temporary Tables Table Variables


Temporary Tables are tables that are Table variables are laid out like tables.
temporarily created for a particular They are partially stored both in the
session. Once the session is memory and in the disk.
terminated, the temporary tables are
automatically deleted. In other words,
these are the physical tables, which are
created in tempdb database in SQL
Server
Syntax DECLARE@Employee TABLE
The syntax for creating Temporary (
Table and Table Variable differs largely.  Id INT,
How to Create Temporary Table in SQL  Name VARCHAR(50)
Server? )
--Insert Two records
-- Create Temporary Table INSERT INTO@Employee
CREATE TABLE #Employee VALUES(1,'Max')
(Id INT, Name VARCHAR(50)) INSERT INTO@Employee
--Insert Two records VALUES(2,'Clarks')
INSERT INTO #Employee --Retrieve the records
VALUES(1,'Max') SELECT* FROM@Employee
INSERT INTO #Customer GO
VALUES(2,'Clark')
--Retrieve the records
SELECT * FROM #Employee
--DROP Temporary Table
DROP TABLE #Employee
GO

There are mainly two types of They can be declared in batch or stored
Temporary Tables-Local & Global procedure. Unlike Temporary Tables,
Temporary Tables. they cannot be dropped explicitly. Once
Local Temporary Table: These tables the batch execution is finished, the
are only available for the session that Table Variables are dropped
has created them. Once the session is automatically.
terminated, these tables are
automatically deleted. They can be also
be deleted explicitly.
Global Temporary Table: These tables
are available for all the sessions and
users. They are not deleted until the
last session using them is terminated.
Similar to local Temporary Table, a
user can delete them explicitly.

The Temporary Tables are stored in The Table Variables are stored in both
tempdb database of SQL server. the memory and the disk in the
Table Variable tempdb database.

The structure of Temporary Tables can The structure of Table Variables cannot
be created even after its creation. be changed once they are created.
Thus, we can use DDL statements like Thus, it means that DDL commands
ALTER, DROP and CREATE as shown in cannot be run in Table Variables.
the below-mentioned example. In the
example we have created a Temporary
Table named as Employee. In this we
will add an Address column and then
finally drop the table.
--Create Temporary Table
  CREATE TABLE#Employee
  (Id INT, Name VARCHAR(50))
  GO
  --Add Address Column
  ALTER TABLE#Employee
  ADD Address VARCHAR(400)
  GO
  --DROP Temporary Table
  DROP TABLE#Employee
  GO

Table Variable
They are not allowed in the user- The table variables can be used in
defined functions. user-defined functions.

They support the explicit transactions They do not participate in the


that are defined by the user. transactions that have been explicitly
defined by the user.

Local and Global Temporary Tables Table Variables do not allow creation of
support creation of indexes on them in indexes on them.
order to increase the performance.

Since the Temporary Tables are


physical tables, while reading from the Since the Table Variables are partially
table, SQL Optimizer puts a read lock stored in the memory, they cannot be
on the table. accessed by any other user or process
that the current user. Therefore, no
read lock is put on the Table Variable

SQL performance tuning?

SQL performance tuning can be an incredibly difficult task. Even a minor change can
have a dramatic impact on performance. Here are the 10 most effective ways to
optimize your SQL queries. 

1. Indexing: Ensure proper indexing for quick access to the database.


2. Select query: Specify the columns in SELECT query instead of SELECT* to avoid
extra fetching load on the database.
3. Running queries: Loops in query structure slows the sequence. Thus, avoid them.
4. Matching records: Use EXITS() for matching if the record exists.
5. Subqueries: Avoid correlated sub queries as it searches row by row, impacting the
speed of SQL query processing.
6. Wildcards: Use wildcards (e.g. %xx%) wisely as they search the entire database
for matching results.
7. Operators: Avoid using function at RHS of the operator.
8. Fetching data: Always fetch limited data.
9. Loading: Use a temporary table to handle bulk data.
10. Selecting Rows: Use the clause WHERE instead of HAVING for primary filters.

What is ROWCOUNT in Sql server ?

Causes SQL Server to stop processing the query after the specified number of rows are
returned.

-- Syntax

SET ROWCOUNT { number | @number_var }

To set this option off so that all rows are returned, specify SET ROWCOUNT 0.

Example:

set ROWCOUNT 5

select * from dim.model (30 records)

output:
Difference between stored procedure and function

1) Procedure can return zero or n values whereas function can return one value
which is mandatory.
2) Procedures can have input, output parameters for it whereas functions can
have only input parameters.
3) Procedure allows select as well as DML statement in it whereas function
allows only select statement in it.
4) Functions can be called from procedure whereas procedures cannot be called
from function.
5) Exception can be handled by try-catch block in a procedure whereas try-catch
block cannot be used in a function.
6) We can go for transaction management in procedure whereas we can't go in
function.
7) Procedures cannot be utilized in a select statement whereas function can be
embedded in a select statement.

@@IDENTITY

t will return last or newly inserted record id of any table in current session but
it’s not limited to current scope. In current session if any trigger or functions
inserted record in any table that it will return that latest inserted record id
regardless of table. We need to use this property whenever we don’t have any
other functions or triggers that run automatically.

The @@identity function returns the last identity created in the same session

Syntax:

SELECT @@IDENTITY

SCOPE_IDENTITY()

This property will return last or newly inserted record id of table in current
session or connection and it’s limited to current scope that means it will return id
of newly inserted record in current session / connection stored procedure or
query executed by you in current scope even we have any other functions or
triggers that run automatically. Its better we can go with property whenever we
need to get last or newly inserted record id in table.
The scope_identity() function returns the last identity created in the same
session and the same scope

Syntax

SELECT SCOPE_IDENTITY()

IDENT_CURRENT

This property will return last or newly inserted record id of specified table. It’s
not limited to any session or scope it’s limited to mentioned table so it will return
last inserted record id of specified table.

 The ident_current(name) returns the last identity created for a specific table


or view in any session.

Syntax

SELECT IDENT_CURRENT(table_name)

Offset and Fetch Next Use and Example?

Select
BusinessEntityID,[FirstName], [LastName],[JobTitle]
from
HumanResources.vEmployee
Order By BusinessEntityID
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY

OFFSET and FETCH NEXT clause used for data pagination in SQL server 2012.

If we use offset with order by clause, the query excludes the number of records
we mentioned in OFFSET n Rows. In the above example, we used OFFSET 10
ROWS so, SQL will exclude first 10 records from the result and display the rest
of all records in the defined order.

If we use offset with fetch next, we can define how many records we need to
exclude. Also we can define that after exclusion how many records we need to
pick up. In the above example, SQL excludes first 10 records and will pick up 10
records afterwards.
In other words, we can say that whenever we need to do paging we need 2
things. 1st, the page no. and 2nd the no. of records in each page.
Here OFFSET is used for page number and FETCH NEXT is the number of
records in each page.

In this example, creating a stored procedure with both ORDER BY OFFSET and
FETCH NEXT keyword to enhancement the paging in SQL Server 2012.

 
CREATE PROCEDURE TestPaging
(
  @PageNumber INT,
  @PageSize INT
)
AS
DECLARE @OffsetCount INT
SET @OffsetCount = (@PageNumber-1)*@PageSize
SELECT  *
FROM [UserDetail]
ORDER BY [User_Id]
OFFSET @OffsetCount ROWS
FETCH NEXT @PageSize ROWS ONLY
 

select * from (
select ad.dealer_hierarchy_id,ad.dealer_id,ad.parent_dealer_hierarchy_id,
ROW_NUMBER() over(partition by ad.parent_dealer_hierarchy_id order by ad.dealer_id
desc) as rnk
--ad1.dealer_hierarchy_id,ad1.dealer_id,ad1.parent_dealer_hierarchy_id
from #temp ad,#temp ad1
where
ad.parent_dealer_hierarchy_id=ad1.dealer_hierarchy_id
) as t
where
rnk=1

What is Trigger ?

A trigger is a special kind of stored procedure that automatically executes when an event
occurs in the database server. DML triggers execute when a user tries to modify data
through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or
DELETE statements on a table or view.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE.
So, there are three types of triggers and hybrids that come from mixing and matching the events
and timings that fire them. Basically, triggers are classified into two main types:

i. After Triggers (For Triggers)


ii. Instead Of Triggers
After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for
views. 
AFTER TRIGGERS can be classified further into three types as:

a. AFTER INSERT Trigger.


b. AFTER UPDATE Trigger.
c. AFTER DELETE Trigger.

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on
this table, I will be attaching several triggers.

CREATE TABLE Employee_Test


(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);


INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);

I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into
another audit table. The main purpose of this audit table is to record the changes in the main
table. This can be thought of as a generic audit trigger.

Now, create the audit table as:-

CREATE TABLE Employee_Test_Audit


(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) After Insert Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]


FOR INSERT
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 Record -- After Insert Trigger.';

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 trigger fired.'


GO

The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies the table
name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER
INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the
same.
In the trigger body, table named inserted has been used. This table is a logical table and
contains the row that has been inserted. I have selected the fields from the logical inserted table
from the row that has been inserted into different variables, and finally inserted those values into
the Audit table.

To see the newly created trigger in action, lets insert a row into the main table as:

insert into Employee_Test values('Chris',1500);

Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger
attached to this table has inserted the record into the Employee_Test_Audit as:
6 Chris 1500.00 Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700

(b) AFTER UPDATE Trigger

This trigger is fired after an update on the table. Let’s create the trigger as:

CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]


FOR UPDATE
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;

if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';

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

PRINT 'AFTER UPDATE Trigger fired.'


GO
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table.
There is no logical table updated like the logical table inserted. We can obtain the updated
value of a field from the update(column_name) function. In our trigger, we have used, if
update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly
checked the column Emp_Sal for an update.

Let’s update a record column and see what happens.

update Employee_Test set Emp_Sal=1550 where Emp_ID=6

This inserts the row into the audit table as:

6 Chris 1550.00 Updated Record -- After Update Trigger. 2008-04-26 12:38:11.843

(c) AFTER DELETE Trigger

This trigger is fired after a delete on the table. Let’s create the trigger as:

CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test]


AFTER DELETE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=d.Emp_ID from deleted d;


select @empname=d.Emp_Name from deleted d;
select @empsal=d.Emp_Sal from deleted d;
set @audit_action='Deleted -- After Delete Trigger.';

insert into Employee_Test_Audit


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

PRINT 'AFTER DELETE TRIGGER fired.'


GO

In this trigger, the deleted record’s data is picked from the logical deleted table and inserted
into the audit table. Let’s fire a delete on the main table. A record has been inserted into the
audit table as:
6 Chris 1550.00 Deleted -- After Delete Trigger. 2008-04-26 12:52:13.867

All the triggers can be enabled/disabled on the table using the statement

ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL

Specific Triggers can be enabled or disabled as:


ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete

This disables the After Delete Trigger named trgAfterDelete on the specified table.

(ii) Instead Of Triggers

These can be used as an interceptor for anything that anyone tried to do on our table or view. If
you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and
they will not actually get deleted (unless you issue another delete instruction from within the
trigger)

INSTEAD OF TRIGGERS can be classified further into three types as:

a. INSTEAD OF INSERT Trigger.


b. INSTEAD OF UPDATE Trigger.
c. INSTEAD OF DELETE Trigger.

Let’s create an Instead Of Delete Trigger as:

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

This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a
record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction
will be committed. Now, let’s try to delete a record with the Emp_Sal >1200 as:

delete from Employee_Test where Emp_ID=4

This will print an error message as defined in the RAISE ERROR statement as:


Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200

And this record will not be deleted.

In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.

Transactions:
A transaction is a unit of work that is performed against a database

Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.
 Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and
all the previous operations are rolled back to their former state.
 Consistency − ensures that the database properly changes states upon a
successfully committed transaction.
 Isolation − enables transactions to operate independently of and transparent
to each other.
 Durability − ensures that the result or effect of a committed transaction
persists in case of a system failure.

The following three T-SQL statements control transactions in SQL Server:

 BEGIN TRANSACTION: This marks the beginning of a transaction.


 COMMIT TRANSACTION: This marks the successful end of a transaction. It
signals the database to save the work.
 ROLLBACK TRANSACTION: This denotes that a transaction hasn't been
successful and signals the database to roll back to the state it was in prior to
the transaction.
 SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.
A SAVEPOINT is a point in a transaction when you can roll the transaction back to
a certain point without rolling back the entire transaction.
The syntax for a SAVEPOINT command is as shown below.
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the
transactional statements. The ROLLBACK command is used to undo a group of
transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;

Example1:

1. -- If an error occurred, roll back  
2. if @maxerr <> 0  
3. begin  
4. ROLLBACK  
5. print 'Transaction rolled back'  
6. end  
7. else  
8. begin  
9. COMMIT  
10. print 'Transaction committed'  
11. end  

You might also like