Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

What is Difference in Temp Table and Table Variable

In SQL Server, a temporary table and a table variable are two different types of temporary storage objects that can be used to store data during the execution of a query or a batch.

Here are the main differences between temporary tables and table variables:

Scope
Temporary tables are created in the tempdb database and are visible to all sessions on the same SQL Server instance. Table variables are local to the batch or stored procedure in which they are defined.

Durability
Temporary tables are durable and are not dropped automatically when they go out of scope. You need to explicitly drop them when they are no longer needed. Table variables are not durable and are automatically dropped when they go out of scope.

Indexing
Temporary tables can have indexes and statistics, which can help improve query performance. Table variables do not support indexes, but they can benefit from statistics created on the columns used in queries against them.

Memory usage
Table variables are stored in memory, and their size is limited to the available memory on the server. Temporary tables can be stored in memory or on disk, depending on their size and the memory settings of the server.

Performance
Table variables are generally faster than temporary tables for small datasets, due to their in-memory storage and lack of indexing overhead. However, for larger datasets, temporary tables can be faster due to their ability to use indexes and statistics.

Here's an example of creating a temporary table:

CREATE TABLE #TempTable (
    ID INT PRIMARY KEY,
    Name VARCHAR(50)
);

INSERT INTO #TempTable (ID, Name)
VALUES (1, 'John'), (2, 'Jane'), (3, 'Bob');

SELECT * FROM #TempTable;

DROP TABLE #TempTable;

And here's an example of creating a table variable:

DECLARE @TableVariable TABLE (
    ID INT PRIMARY KEY,
    Name VARCHAR(50)
);

INSERT INTO @TableVariable (ID, Name)
VALUES (1, 'John'), (2, 'Jane'), (3, 'Bob');

SELECT * FROM @TableVariable;


What are Triggers and Types of Triggers in SQL Server

In SQL Server, triggers are a type of stored procedure that automatically execute in response to specific data manipulation events, such as insert, update, or delete operations on a table. Triggers can be used to enforce data integrity rules, audit changes to the data, or perform complex business logic.

There are two types of triggers in SQL Server:

DML Triggers: 
These triggers fire in response to data manipulation language (DML) statements, such as INSERT, UPDATE, and DELETE. DML triggers can be defined to execute either before or after the DML statement.

DDL Triggers: 
These triggers fire in response to data definition language (DDL) statements, such as CREATE, ALTER, and DROP. DDL triggers can be defined to execute either before or after the DDL statement.

DML triggers can be further classified into two types based on when they fire:

  1. After Triggers: These triggers execute after the DML statement has completed, but before any constraints or referential integrity rules are enforced.
  2. Instead of Triggers: These triggers execute instead of the DML statement. They allow you to modify the data or perform custom business logic before the data is inserted, updated, or deleted.

Triggers can be defined at the table level or at the database level. When a trigger is defined at the table level, it only fires in response to data manipulation events on that table. When a trigger is defined at the database level, it fires in response to data manipulation events on any table in the database.

Here are a few examples of triggers in SQL Server:

Implementation as Audit Trigger: This trigger can be used to audit changes to a table. For example, suppose you have a table named "Employee" and you want to track changes to the "Salary" column. You can create a trigger that fires after an update to the "Salary" column and inserts a record into an audit table. 

Here's an example of the trigger:

CREATE TRIGGER Audit_Employee_Salary
ON Employee
AFTER UPDATE
AS
BEGIN
    INSERT INTO Employee_Audit (EmployeeID, OldSalary, NewSalary, ChangeDate)
    SELECT i.EmployeeID, d.Salary, i.Salary, GETDATE()
    FROM inserted i
    INNER JOIN deleted d ON i.EmployeeID = d.EmployeeID
END

Implementation as Constraint Trigger: This trigger can be used to enforce data integrity rules. For example, suppose you have a table named "Orders" and you want to ensure that the total amount of an order cannot exceed the customer's credit limit. You can create a trigger that fires before an insert or update to the "Orders" table and checks the customer's credit limit. 

Here's an example of the trigger:

CREATE TRIGGER Orders_CreditLimit
ON Orders
INSTEAD OF INSERT, UPDATE
AS
BEGIN
    IF EXISTS (
        SELECT *
        FROM inserted i
        INNER JOIN Customers c ON i.CustomerID = c.CustomerID
        WHERE i.TotalAmount > c.CreditLimit
    )
    BEGIN
        RAISERROR ('Total amount of the order exceeds the customer''s credit limit.', 16, 1)
        ROLLBACK TRANSACTION
        RETURN
    END

    INSERT INTO Orders (OrderID, CustomerID, OrderDate, TotalAmount)
    SELECT OrderID, CustomerID, OrderDate, TotalAmount
    FROM inserted
END

Note that these are just a few above examples of the types of triggers that can be created in SQL Server. The possibilities are endless, and triggers can be used to perform a wide range of tasks depending on your specific needs.

What are Advantages of using Stored procedure instead a Inline Query

Stored procedures and inline queries both serve the purpose of executing SQL statements, but they differ in several aspects.

A stored procedure is a pre-compiled program that is stored in a database and can be executed multiple times with different parameters. It can contain multiple SQL statements and can be called from various applications or client programs. Stored procedures can also be used to encapsulate complex business logic and rules, making it easier to maintain and update the code.

On the other hand, an inline query is a SQL statement that is included in the code of an application or a client program. It is compiled and executed every time it is called, which can result in performance issues for complex queries.

Here are some advantages of using stored procedures over inline queries:

Performance: 
Stored procedures are compiled once and stored in the database, which means that subsequent calls are faster than inline queries, as they don't need to be compiled each time. This can result in significant performance improvements, especially for complex queries.

Security: 
Stored procedures can be used to control access to the database by granting specific permissions to users or roles. This allows you to limit the actions that can be performed on the database, making it more secure.

Encapsulation: 
Stored procedures can encapsulate complex business logic, making it easier to maintain and update the code. This also allows developers to reuse code across multiple applications, reducing development time and improving code quality.

Debugging: 
Stored procedures can be debugged using SQL Server Management Studio or other debugging tools, which can make it easier to identify and fix issues.

Overall, stored procedures provide a more secure, efficient, and maintainable way of executing SQL statements, particularly for complex queries or those that are frequently used.




What is Difference in Primary Key and Unique Key

Both Primary Key and Unique Key are used to enforce uniqueness of a column or a group of columns in a database table. However, there are some differences between them.

Primary Key:
A primary key is a column or a combination of columns that uniquely identify a record in a table. It cannot contain null values and there can be only one primary key per table. The primary key is automatically indexed by the database and is used as a foreign key in related tables to establish relationships between them.

Unique Key:
A unique key is a column or a combination of columns that must have unique values. Unlike primary keys, it can contain null values but there can be more than one unique key per table. A unique key is used to enforce the integrity of the data and ensure that there are no duplicate values in the table.

In summary, the main differences between Primary Key and Unique Key are:
  • A table can have only one primary key, but can have multiple unique keys.
  • A primary key cannot contain null values, but a unique key can contain null values.
  • A primary key is used as a foreign key in other tables to establish relationships, while a unique key is used to enforce the integrity of the data and ensure that there are no duplicate values.
Both Primary Key and Unique Key are important in ensuring data integrity and should be carefully chosen based on the specific requirements of the database design.

What is difference between Clustered Index and Non Clustered Index

A Table can have two type of index that is Clustered Index and Non-Clustered Index but both job is to store data in sorted order and retrieve a data faster when perform a query.

Clustered Index 

The Clustered Index determines how data is stored in physically on the table in the sorted order. Advantage of using index is to store data in table in sorted order even insertion in the table is not sorted. Default sorting of data is ascending.

A table can have only one clustered index and this is usually created by default on the primary key. A clustered index can be created for another column also if primary key is not exists on the table. 

For an Example - The primary key on EmpId column will create a clustered index for the EmpId column. A table can have only one clustered index on it.

SQL Server stores data in the table according a clustered index. It helps to make SELECT query faster. A query with index is always faster than a query without index.

getdate()
SELECT  * FROM  EMPLOYEE where EmpId = 150
getdate()

Insert some dummy data into Employee Table, Let's say 10,000 records to measure the above query execution time without index and with index on EmpId.

If no any index is added then each row will be compared to find the EmpId 150. If Clustered index is created on the table then it will give records faster from physically stored data using a search technique Binary Search Tree.

Clustered Index is slightly faster than non-clustered index.

Non-Clustered Index 

When the Non-clustered index created then It takes extra physical storage of the data in sorted order of non-clustered index column with a row pointer which points to row of actual storage data in the table. When perform a query on non-clustered index column then it do extra lookup for actual data which is stored in the table with the help of row pointer.

Non-Clustered are generally used when we want to have more than one index other than primary key constraint.

We can create a single non-clustered index for multiple columns and all columns will be sorted as specified in the index. We call it Composite Clustered Index.

The 249 Non-clustered Index can be created per table in SQL Server 2005 where SQL server 2008 can have 999 non-clustered Index per table.

On which Column we have to apply the non-Clustered Index -

  • The column used multiple time in the search criteria across.
  • The column most of the time used to join other tables.
  • The column used as Foreign Key most of the time.
  • The column used in Join, Where, and Order By clauses in most cases
4 Main Differences in Clustered Index and Non-Clustered Index

1. Only one clustered Index can be created per table where non clustered index can be created  per table more than one.
2. Clustered Index is by default unique key Index where non-clustered index can be non unique too.
3. Clustered Index are slightly faster than Non-Clustered Index.
4. Clustered Index stored sorted data with in the table itself where non-clustered index required extra disk storage to sort the data.

What is Difference in Stored Procedure and Functions

Stored Procedure and User Defined Functions both are SQL Server objects but both are much different in  implementation and usage.

Differences -
  1. Function must return something in from of single value or table but stored procedure may or may not.
  2. Function cannot have output parameter where stored procedure can have output parameter.
  3. Function must be written with single input parameter where stored procedure can be written without any parameter.
  4. Functions are usually called by a Stored Procedure where Stored Procedure cannot be call from a Function.
  5. Function cannot have try-catch block where Stored Procedure can have try-catch block and can handle exceptions. 
  6. Transaction block cannot be written in Function where in Stored Procedure it can be written.
Usage Difference -
  • To avoid a repeating code in Stored Procedure you can write a user defined function and can use this function for all stored procedures.
  • To implement a generic code can be written a function. For an example - Write a function which returns customer's Age in years base on his Date of Birth.
  • Functions used usually for returning something somewhat common. For an example - In-built SQL Function getdate() returns always today date and repeatedly called in Stored Procedure.