SQL Concepts
SQL Concepts
Joins are used to relate one or more tables in SQL Server. Joins are a part of a SQL Statement that
retrieves rows from a table or tables according to specified conditions.
Types of Joins
1. Inner Join
2. Outer Join
3. Cross Join
4. Self Join
Output
insertion of data
Output
1. Inner Join:
It return all the Rows that satisfy the join Condition. Inner join produces records that match in
Tables.
Output
2. Outer Join:
The result of the Left Outer Join contains all the records of the left table and if any record of the left
table does not match the right table than it returns Null for the right side table.
Output
The result of the Right Outer Join contains all the records of the right table and if any record of the
right table does not match the Left table than it returns Null for the left side table.
A Full Outer Join fetches all records of both tables; where the record does not match, it returns Null.
Output
2. Cross Join:
This join is a Cartesian join. The result of a Cross Join contains records that are the multiplication of
the records from both tables.
Insertion of data
Output
4. Self Join:
In the Self Join a table is joined to itself. A Self Join can be an Inner Join or Outer Join. In the given
example we find the employees that are the manager of other employees.
Output
Constraints:
Constraints are rules and restrictions applied on a column or a table such that unwanted
data can't be inserted into tables. This ensures the accuracy and reliability of the data in the
database. We can create constraints on single or multiple columns of any table. Constraints
maintain the data integrity and accuracy in the table.
Definitions of these types of constraints is given after the creation of the table using the
Alter Command.
A Not null constraint restrict the insertion of null values into a column. If we are using a Not Null
Constraint for a column then we cannot ignore the value of this column during an insert of data into
the table.
Column Level
Syntax
Table Level
Syntax
Example
2. Check Constraint
A Check constraint checks for a specific condition before inserting data into a table. If the
data passes all the Check constraints then the data will be inserted into the table otherwise
the data for insertion will be discarded. The CHECK constraint ensures that all values in a
column satisfies certain conditions.
Column Level
Syntax
Example
Table Level
Syntax
Example
3. Default Constraint
Specifies a default value for when a value is not specified for this column. If in an insertion
query any value is not specified for this column then the default value will be inserted into
the column.
Column Level
Syntax
Example
Syntax
Example
4. Unique Constraint
It ensures that each row for a column must have a unique value. It is like a Primary key but
it can accept only one null value. In a table one or more column can contain a Unique
Constraint.
Column Level
Syntax
Example
Table Level
Syntax
1. Alter Table_Name
2. Add Constraint Constraint_Name Unique(Column_Name)
Example
A Primary key uniquly identifies each row in a table. It cannot accept null and
duplicate data. One or more of the columns of a table can contain a Primary key.
Column Level
Syntax
Example
Table Level
Syntax
Example
A Foreign Key is a field in a database table that is a Primary key in another table. A Foreign
key creates a relation between two tables. The first table contains a primary key and the
second table contains a foreign key.
Column Level
Syntax
Example
Table Level
Example
While using triggers these Inserted & Deleted tables (called as magic tables) will be created automatically.
The inserted table contains a copy of all records that are inserted in the trigger table.
The deleted table contains all records that have been deleted from deleted from the trigger table.
Whenever any updation takes place,the trigger uses both the inserted and deleted tables.
When we insert any record then that record will be added into this Inserted table initially, similarly while
updating a record a new entry will be inserted into Inserted table & old value will be inserted into Deleted
table. In the case of deletion of a record then it will insert that record into the Deleted table.
Note that the Magic Table does not contain the information about the columns of the data-type text, ntext, or
image. Attempting to access these columns will cause an error.
Views:
https://www.c-sharpcorner.com/UploadFile/f0b2ed/views-in-sql-server/
https://www.c-sharpcorner.com/article/sql-server-indexed-views/
https://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-
Select-Quer
https://logicalread.com/advantages-indexed-views-sql-server-mc03/
Views are virtual tables that hold data from one or more tables. It is stored in the database. A view does
not contain any data itself, it is a set of queries that are applied to one or more tables that are stored
within the database as an object. Views are used for security purposes in databases. Views restrict the
user from viewing certain columns and rows. In other words, using a view we can apply the restriction
on accessing specific rows and columns for a specific user. A view can be created using the tables of the
same database or different databases. It is used to implement the security mechanism in the SQL Server.
Views are used to implement the security mechanism in SQL Server. Views are generally used to restrict
the user from viewing certain columns and rows. Views display only the data specified in the query, so it
shows only the data that is returned by the query defined during the creation of the view. The rest of the
data is totally abstract from the end user.
1. CREATE VIEW view_name AS
2. SELECT columns
3. FROM tables
4. WHERE conditions;
Getting Information about a view: We can retrieve all the information of a view using the Sp_Helptext
system Stored Procedure. Let us see an example.
Sp_Helptext Employee_View4
sp_refreshview is a system-level Stored Procedure that refreshes the metadata of any view once you
edit the schema of the table. Let's execute the following:
We don't get the results we exepected because the schema of the view is already defined. So when we
add a new column into the table it will not change the schema of the view and the view will contain the
previous schema. For removing this problem we use the system-defined Stored Procedure
sp_refreshview.
SchemaBinding a VIEW
In the previous example we saw that if we add a new column into the table then we must refresh the
view.
Such a way if we change the data type of any column in a table then we should refresh the view. If we
want to prevent any type of change in a base table then we can use the concept of SCHEMABINDING. It
will lock the tables being referred to by the view and restrict all kinds of changes that may change the
table schema (no Alter command).
We can't specify "Select * from tablename" with the query. We need to specify all the column names for
reference.
Types of VIWES:
1. SIMPLE VIEW -----we can perform DML operations
2. COMPLEX VIEW -----we cannot perform DML operations but we can update view
3. Indexed View---with schema binding, we can create unique cluster index on
this, we cannot create constraints.
Disadvantages of views
• Performance: The DBMS the query against the view into queries against the underlying source table. If a
table is defined by a multi table query, then even a simple query against a view becomes a complicated
join, and it may take a long time to complete. This is reference to insert, delete and update operations
• Update restrictions: when a user tries to update rows of a view, the DBMS must translate the request
into an update into an update on rows of the underlying source table. This is possible for simple views,
but more complicated views cannot be updated.
Practice
2. After creating a view if we insert any records in base table it will effect in the VIEW
After creating a view if we insert any records in VIEW it will effect in base table.
After creating a view if we delete any records in base table it will effect in the VIEW
After creating a view if we delete any records in VIEW it will effect in base table.
3. CREATE VIEW VW_dept_test
AS
SELECT * FROM dept_test
After creating a view if we add column in base table it won’t effect in VIEW. If we want see schema
changes we have to refresh the view.
Exec sp_refreshview VW_dept_test
4. After creating view if we drop table we cannot retive data from view
5. A normal view is just a saved query, nothing more. The data isn't saved on the disk--it isn't
materialized. Thus, you cannot have integrity constraints (check constraints, foreign keys, or
primary keys) on a view: there's nothing to constrain. Even an index view--which is
materialized--does not allow for constraints
6. We cannot create constraints, index on VIEWS
An indexed view has a unique clustered index. The unique clustered index is stored in SQL Server
and updated like any other clustered index. An indexed view is more significant compared to
standard views that involve complex processing of large numbers of rows, such as aggregating lots
of data, or joining many rows. If such views are frequently referenced in queries, we can improve
performance by creating a unique clustered index on the view. For standard view result set is not
stored in database, instead of this the result set is computed for each query but in case of clustered
index the result set is stored in the database just like a table with a clustered index is stored.
Queries that don’t specifically use the indexed view can even benefit from the existence of the
clustered index from the view. Index view has some cost in the form of performance, if we create an
indexed view, every time we modify data in the underlying tables then not only must SQL Server
maintain the index entries on those tables, but also the index entries on the view. In the developer
and enterprise editions of SQL Server, the optimizer can use the indexes of views to optimize
queries that do not specify the indexed view. In the other editions of SQL Server, however, the
query must include the indexed view and specify the hint NOEXPAND to get the benefit of the index
on the view.
Indexes:
https://www.sqlshack.com/what-is-the-difference-between-clustered-and-non-clustered-indexes-
in-sql-server/
Indexes are used to speed-up query process in SQL Server, resulting in high performance. They are
similar to textbook indexes. In textbooks, if you need to go to a particular chapter, you go to the index,
find the page number of the chapter and go directly to that page. Without indexes, the process of finding
your desired chapter would have been very slow.
The same applies to indexes in databases. Without indexes, a DBMS has to go through all the records in
the table in order to retrieve the desired results. This process is called table-scanning and is extremely
slow. On the other hand, if you create indexes, the database goes to that index first and then retrieves
the corresponding table records directly.
1. Clustered Index
2. Non-Clustered Index
Clustered Index
A clustered index defines the order in which data is physically stored in a table. Table data can be sorted
in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key
constraint automatically creates a clustered index on that particular column.
Let’s take a look. First, create a “student” table inside “schooldb” by executing the following script, or
ensure that your database is fully backed up if you are using your live data:
Notice here in the “student” table we have set primary key constraint on the “id” column. This
automatically creates a clustered index on the “id” column. To see all the indexes on a particular table
execute “sp_helpindex” stored procedure. This stored procedure accepts the name of the table as a
parameter and retrieves all the indexes of the table. The following query retrieves the indexes created
on student table.
In the output you can see the only one index. This is the index that was automatically created because of
the primary key constraint on the “id” column.
This clustered index stores the record in the student table in the ascending order of the “id”. Therefore, if
the inserted record has the id of 5, the record will be inserted in the 5th row of the table instead of the
first row. Similarly, if the fourth record has an id of 3, it will be inserted in the third row instead of the
fourth row. This is because the clustered index has to maintain the physical order of the stored records
according to the indexed column i.e. id. To see this ordering in action, execute the following script:
USE schooldb
VALUES
(6, 'Kate', 'Female', '03-JAN-1985', 500, 'Liverpool'),
The above script inserts ten records in the student table. Notice here the records are inserted in random
order of the values in the “id” column. But because of the default clustered index on the id column, the
records are physically stored in the ascending order of the values in the “id” column. Execute the
following SELECT statement to retrieve the records from the student table.
Non-Clustered Indexes
A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is
stored at one place and table data is stored in another place. This is similar to a textbook where the book
content is located in one place and the index is located in another. This allows for more than one non-
clustered index per table.
It is important to mention here that inside the table the data will be sorted by a clustered index.
However, inside the non-clustered index data is stored in the specified order. The index contains column
values on which the index is created and the address of the record that the column value belongs to.
When a query is issued against a column on which the index is created, the database will first go to the
index and look for the address of the corresponding row in the table. It will then go to that row address
and fetch other column values. It is due to this additional step that non-clustered indexes are slower
than clustered indexes.
The syntax for creating a non-clustered index is similar to that of clustered index. However, in case of
non-clustered index keyword “NONCLUSTERED” is used instead of “CLUSTERED”. Take a look at the
following script.
Performance Tuning:
https://www.c-sharpcorner.com/article/sql-server-performance-tuning-tips/
Database is the most important and powerful part of any application. If your database is
not working properly and taking long time to compute the result, this means something is
going wrong in database. Here, database tune up is required, otherwise performance of the
application will degrade.
I know a lot of articles already published on this topic. But in this article, I tried to provide a
list of database tune up tips that will cover all the aspects of database. Database tuning is a
very critical and fussy process. It is true that database tuning is a database admin task but
we should have the basic level of knowledge for doing this. Because, if we are working on a
project where there is no role of admin, then it is our responsibility to the maintain the
performance of the database. If performance of database is degraded, then it will cause
worst effect on the whole system. In this article, I will explain some basic database tuning
tips that I learned from my experience and from my friends who are working as database
administrator. Using these tips, you can maintain or upgrade the performance of your
database system. Basically, these tips are written for SQL Server but we can implement
these into another databases too, like Oracle and MySQL. Please read these tips carefully
and at the end of article, let me know if you find something wrong or incorrect.
We should avoid the Null value in fixed length fields because if we insert the NULL value in
a fixed length field, then it will take the same amount of space as the desired input value for
that field. So, if we require a null value in a field, then we should use a variable length field
that takes lesser space for NULL. The use of NULLs in a database can reduce the database
performance, especially, in WHERE clauses. For example, try to use varchar instead of char
and nvarchar.
When we require all the columns of a table, we usually use a “Select *” statement. Well, this
is not a good approach because when we use the “select *” statement, the SQL Server
converts * into all column names before executing the query, which takes extra time and
efforts. So, always provide all the column names in the query instead of “select *”.
Normalized and managed tables increase the performance of a database. So, always try to
perform at least 3rd normal form. It is not necessary that all tables requires 3NF
normalization form, but if any table contains 3NF form normalization, then it can be called
well structured tables.
Clustered index stores data physically into memory. If the size of a clustered index is very
large, then it can reduce the performance. Hence, a large clustered index on a table with a
large number of rows increases the size significantly. Never use an index for frequently
changed data because when any change in the table occurs, the index is also modified, and
that can degrade performance.
If we select inappropriate data type, it will reduce the space and enhance the performance;
otherwise, it generates the worst effect. So, select an appropriate data type according to the
requirement. SQL contains many data types that can store the same type of data but you
should select an appropriate data type because each data type has some limitations and
advantages upon another one.
I found that many developers try to store the image into database instead of the image
path. It may be possible that it is requirement of application to store images into database.
But generally, we should use image path, because storing image into database increases the
database size and reduces the performance.
We should prefer a CTE over the temp table because temp tables are stored physically in a
TempDB which is deleted after the session ends. While CTEs are created within memory.
Execution of a CTE is very fast as compared to the temp tables and very lightweight too.
The main goal of adopting a naming convention for database objects is to make it easily
identifiable by the users, its type, and purpose of all objects contained in the database. A
good naming convention decreases the time required in searching for an object. A good
name clearly indicates the action name of any object that it will perform.
We should prefer UNION ALL instead of UNION because UNION always performs sorting
that increases the time. Also, UNION can't work with text datatype because text datatype
doesn't support sorting. So, in that case, UNION can't be used. Thus, always prefer UNION
All.
It is very important to use Small data type for index . Because, the bigger size of data type
reduces the performance of Index. For example, nvarhcar(10) uses 20 bytes of data and
varchar(10) uses 10 bytes of the data. So, the index for varhcar data type works better. We
can also take another example of datetime and int. Datetime data type takes 8 Bytes and int
takes 4 bytes. Small datatype means less I/O overhead that increases the performance of
the index.
There is no difference in the performance of these three expressions; but, the last two
expressions are not good considered to be a good practice. So, always use count(10) to get
the numbers of records from a table.
Instead of using the row query, we should use the stored procedure because stored
procedures are fast and easy to maintain for security and large queries.
Use Between instead of In
If Between can be used instead of IN, then always prefer Between. For example, you are
searching for an employee whose id is either 101, 102, 103 or 104. Then, you can write the
query using the In operator like this:
You can also use Between operator for the same query.
It has been seen many times that developers use "Select Count(*)" to get the existence of
records. For example
But, this is not a proper way for such type of queries. Because, the above query
performs the complete table scan, so you can use If Exists for same query. That will
increase the performance of your query, as below.
Most programmers use “sp_” for user-defined Stored Procedures. I suggest to never use
“sp_” for user-defined Stored Procedure because in SQL Server, the master database has a
Stored Procedure with the "sp_" prefix. So, when we create a Stored Procedure with the
"sp_" prefix, the SQL Server always looks first in the Master database, then in the user-
defined database, which takes some extra time.
Avoid Cursors
A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor is a set of rows together with a pointer that identifies the current row. It
is a database object to retrieve the data from a result set one row at a time. But, use of a
cursor is not good because it takes long time because it fetches data row by row. So, we can
use a replacement of cursors. A temporary table for or While loop may be a replacement of
a cursor in some case.
SET NOCOUNT ON
When an INSERT, UPDATE, DELETE or SELECT command is executed, the SQL Server
returns the number affected by the query. It is not good to return the number of rows
affected by the query. We can stop this by using NOCOUNT ON.
Use Try–Catch
In T-SQL, a Try-Catch block is very important for exception handling. A best practice and
use of a Try-Catch block in SQL can save our data from undesired changes. We can put all T-
SQL statements in a TRY BLOCK and the code for exception handling can be put into a
CATCH block.
Remove all unused indexes because indexes are always updated when the table is updated
so the index must be maintained even if not used.
An index is a data structure to retrieve fast data. Indexes are special lookup tables that the
database search engine can use to speed up data retrieval. Simply an index is a pointer to
data in a table. Mainly an index increases the speed of data retrieval. So always try to keep
minimum one index on each table it may be either clustered or non-clustered index.
A foreign key is a column or combination of columns that is the same as the primary key,
but in a different table. Foreign keys are used to define a relationship and enforce integrity
between two tables. In addition to protecting the integrity of our data, FK constraints also
help document the relationships between our tables within the database itself. Also define
a action rules for delete and update command , you can select any action among the No
Action, Set NULL, Cascade and set default.
Use Alias Name
Aliasing renames a table or a column temporarily by giving another name. The use of table
aliases means to rename a table in a specific SQL statement. Using aliasing, we can provide
a small name to large name that will save our time.
Although in most cases the query optimizer will pick the appropriate index for a specific
table based on statistics, sometimes it is better to specify the index name in your SELECT
query.
Example
1. SELECT
2. e.Emp_IId,
3. e.First_Name,
4. e.Last_Name
5. FROM dbo.EMPLOYEE e
6. WITH (INDEX (Clus_Index))
7. WHERE e.Emp_IId > 5
8. Select Limited Data
We should retrieve only the required data and ignore the unimportant data. The less data
retrieved, the faster the query will run. Rather than filtering on the client, push as much
filtering as possible on the server-end. This will result in less data being sent on the wire
and you will see results much faster.
We should drop the index before insertion of a large amount of data. This makes the insert
statement run faster. Once the inserts are completed, you can recreate the index again.
A Check constraint checks for a specific condition before inserting data into a table. If the
data passes all the Check constraints then the data will be inserted into the table otherwise
the data for insertion will be discarded. The CHECK constraint ensures that all values in a
column satisfies certain conditions.
A Unique Constraint ensures that each row for a column must have a unique value. It is like
a Primary key but it can accept only one null value. In a table one or more column can
contain a Unique Constraint. So we should use a Check Constraint and Unique Constraint
because it maintains the integrity in the database.
If we are creating a Non-Clustered index on more than one column then we should consider
the sequence of the columns. The order or position of a column in an index also plays a vital
role in improving SQL query performance. An index can help to improve the SQL query
performance if the criteria of the query matches the columns that are left most in the index
key. So we should place the most selective column at left most side of a non-clustered
index.
We all know that Stored Procedures execute T-SQL statements in less time than the similar
set of T-SQL statements are executed individually. The reason is that the query execution
plan for the Stored Procedures are already stored in the "sys.procedures" system-defined
view. We all know that recompilation of a Stored Procedure reduces SQL performance. But
in some cases it requires recompilation of the Stored Procedure. Dropping and altering of a
column, index and/or trigger of a table. Updating the statistics used by the execution plan
of the Stored Procedure. Altering the procedure will cause the SQL Server to create a new
execution plan.
Sparse column provide better performance for NULL and Zero data. If you have any column
that contain large amount numbers of NULL and Zero then prefer Sparse Column instead of
default column of SQL Server. Sparse column take lesser space then regular column
(without SPARSE clause).
Example
Above method is not a good approach to insert the multiple records instead of this you can
use another method like below.
In A Correlated query inner query take input from outer(parent) query, this query run for
each row that reduce the performance of database.
The best method is that wehsould be prefer the join instaed of correlated query as below.
In some cases, index and join hint may be increase the performance of database, but if you
provide any join or index hint then server always try to use the hint provided by you
although it have a better execution plan, so such type of approach may be reduce the
database performance. Use Join or index hint if you are confidence that there is not any
better execution plan. If you have any doubt then make server free to choose a execution
plan.
Index should be created for all columns which are using Where, Group By, Order By, Top,
and Distinct command.
It is true that use of index makes the fast retrieval of the result. But, it is not always true. In
some cases, the use of index doesn't affect the performance of the query. In such cases, we
can avoid the use of index.
If you are using join on two or more tables and the result of queries is frequently used, then
it will be better to make a View that will contain the result of the complex query. Now, you
can use this View multiple times, so that you don't have to execute the query multiple times
to get the same result.
If your query contains multiple wild card searches using LIKE(%%), then use of Full-text
Index can increase the performance. Full-text queries can include simple words and
phrases or multiple forms of a word or phrase. A full-text query returns any document that
contains at least one match (also known as a hit). A match occurs when a target document
contains all the terms specified in the Full-text query, and meets any other search
conditions, such as the distance between the matching terms.
Temporary Tables:
https://www.c-sharpcorner.com/UploadFile/f0b2ed/temporary-tables-in-sql-server/
These tables are automatically destroyed at the termination of the procedure or session that created
them. SQL Server provides the concept of temporary table that helps the developer in a great way.
These tables can be created at runtime and can do many kinds of operations that a normal table can do.
In SQL Server all temporary tables are present in the tempdb database.
Local temporary tables are temporary tables that are available only to the session that created them.
These tables are automatically destroyed at the termination of the procedure or session that created
them. Local temp tables are only available to the current connection for the user. Names of Local temp
tables starts with (“#”) hash sign.
Global temporary tables are temporary tables that are available to all sessions and all users. Once this
table has been created by a connection, like a permanent table then it is available to any user by any
connection. They are dropped automatically when the last session using the temporary table has
completed. Names of global temp tables start with (“##”) double hash sign.
Practice:
Subquery Derived
Subqueries must be enclosed within Derived table must be enclosed within parentheses and table name
parentheses. must be provided.
Subquery can have only one column. Derived table can have one or more column.
Subquery mainly use in where clause. Derived table used in from clause.
1. SYNTAX
Below is the sample example of Creating a Below is the sample example of Declaring a
Temporary Table, Inserting re cords into it, Table Variable, Inserting records into it and
retrieving the rows from it and then finally dropping retrieving the rows from it.
2. MODIFYING STRUCTURE
Temporary Table structure can be changed after it’s Table Variables doesn’t support DDL
creation it implies we can use DDL statements statements like ALTER, CREATE, DROP etc,
Below script creates a Temporary Table #Customer, variable nor we can drop it explicitly.
Table is dropped.
3. STORAGE LOCATION
One of the most common MYTH about Temporary Table & Table Variable is that: Temporary Tables
are created in TempDB and Table Variables are created In-Memory. Fact is that both are created in
4. TRANSACTIONS
Temporary Tables honor the explicit transactions Table variables doesn’t participate in the
Functions. Functions.
6. INDEXES
Temporary table supports adding Indexes explicitly Table Variables doesn’t allow the explicit
after Temporary Table creation and it can also have addition of Indexes after it’s declaration, the
the implicit Indexes which are the result of Primary only means is the implicit indexes which are
Variable declaration.
CTEs...
• Are unindexable (but can use existing indexes on referenced objects)
• Cannot have constraints
• Are essentially disposable VIEWs
• Persist only until the next query is run
• Can be recursive
• Do not have dedicated stats (rely on stats on the underlying objects)
#Temp Tables...
• Are real materialized tables that exist in tempdb
• Can be indexed
• Can have constraints
• Persist for the life of the current CONNECTION
• Can be referenced by other queries or subprocedures
• Have dedicated stats generated by the engine
http://sqlhints.com/tag/temporary-table-vs-table-variable/
Everyone knows about the basic difference between CHAR and VARCHAR data types. In this
article apart from the basic difference, will discuss on one more interesting difference which
I have observed recently.
CHAR Data Type is a Fixed Length Data Type. For example if you declare a variable/column
of CHAR (10) data type, then it will always take 10 bytes irrespective of whether you are
storing 1 character or 10 character in this variable or column. And in this example as we have
declared this variable/column as CHAR(10), so we can store max 10 characters in this
column.
On the other hand VARCHAR is a variable length Data Type. For example if you declare a
variable/column of VARCHAR (10) data type, it will take the no. of bytes equal to the number of
characters stored in this column. So, in this variable/column if you are storing only one character
then it will take only one byte and if we are storing 10 characters then it will take 10 bytes. And in
this example as we have declared this variable/column as VARCHAR (10), so we can store max 10
characters in this column.
VARCHAR(N)---8000 bytes----8KB VARCHAR(MAX)----2 GB
NVARCHAR will read different languages and It will occupy 2bytes for 1 char
Stored Procedure:
Stored Procedure: Stored Procedure in SQL Server can be defined as the set of logical group of SQL
statements which are grouped to perform a specific task. There are many benefits of using a stored
procedure. The main benefit of using a stored procedure is that it increases the performance of the
database.The other benefits of using the Stored Procedure are given below.
https://www.c-sharpcorner.com/article/how-to-create-a-stored-procedure-in-sql-server-
management-studio/
Functions:
1. UDFs support modular programming. Once you create a UDF and store it in a database then you
can call it any number of times. You can modify the UDF independent of the source code.
2. UDFs reduce the compilation cost of T-SQL code by caching plans and reusing them for repeated
execution.
3. They can reduce network traffic. If you want to filter data based on some complex constraints
then that can be expressed as a UDF. Then you can use this UDF in a WHERE clause to filter data.
Types of UDF
1. Scalar Functions
2. Table Valued Functions
1. Scalar Functions
A Scalar UDF accepts zero or more parameters and return a single value. The return type of a scalar
function is any data type except text, ntext, image, cursor and timestamp. Scalar functions can be use in a
WHERE clause of the SQL Query.
Example
1. PRINT dbo.GetStudent(1)
Output: Ram
1. Table Valued Functions
A Table Valued UDF accepts zero or more parameters and return a table variable. This type of function is
special because it returns a table that you can query the results of a join with other tables. A Table
Valued function is further categorized into an “Inline Table Valued Function” and a “Multi-Statement
Table Valued Function”.
An Inline Table Valued Function contains a single statement that must be a SELECT statement. The
result of the query becomes the return value of the function. There is no need for a BEGIN-END block in
an Inline function.
1. returns Table
2. As
3. return (Select * from Employee)
A Multi-Statement contains multiple SQL statements enclosed in BEGIN-END blocks. In the function
body you can read data from databases and do some operations. In a Multi-Statement Table valued
function the return value is declared as a table variable and includes the full structure of the table to be
returned. The RETURN statement is without a value and the declared table variable is returned.
No.
1 Function must return a value. Stored procedure may or not return values.
2 Will allow only Select statement, it will not Can have select statements as well as DML
etc
3 It will allow only input parameters, doesn’t It can have both input and output parameters.
4 It will not allow us to use try-catch blocks. For exception handling we can use try catch
blocks.
5 Transactions are not allowed within Can use transactions within Stored procefures.
functions.
6 We can use only table variables, it will not Can use both table variables aswell as
7 Stored procedures can’t be called from Stored Procedures can call functions.
function.
Execute/Exec
procedure.
set.
CURSORS:
https://www.dotnettricks.com/learn/sqlserver/sql-server-different-types-of-cursors
Introduction
A cursor is a database object that points to a result set. We use cursor to fetch any specific row from result set.
Most of time cursor is used by application programmer.
• Dynamic cursor
• Keyset cursor
• Static cursor
• Forward-only cursor
Dynamic Cursor
Keyset_cursor
Keyset_cursor is scrollable and sensitive to database changes for update and delete but not for insertion.
Static cursor
Forward_only
Forward_only is not scrollable but sensitive to database changes.
Triggers are database object. Basically these are special type of stored procedure that are automatically
fired/executed when a DDL or DML command statement related with the trigger is executed. Triggers are used
to assess/evaluate data before or after data modification using DDL and DML statements. These are also used
to preserve data integrity, to control server operations, to audit a server and to implement business logic or
business rule.
Types of Triggers
In Sql Server we can create four types of triggers Data Definition Language (DDL) triggers, Data Manipulation
Language (DML) triggers, CLR triggers and Logon triggers.
1. DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system
defined stored procedures that perform DDL-like operations.
Example : If you are going to execute the CREATE LOGIN statement or the sp_addlogin stored procedure to
create login user, then both these can execute/fire a DDL trigger that you can create on CREATE_LOGIN event
of Sql Server.
We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF clause means we can make only
After Trigger on DDL statements.
DDL trigger can be used to observe and control actions performed on the server, and to audit these
operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating database
operations.
2. DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and stored
procedures that perform DML-like operations. DML Triggers are of two types
Example : If you insert record/row in a table then the trigger related/associated with the insert event on
this table will fire only after the row passes all the constraints, like as primary key constraint, and some
rules. If the record/row insertion fails, SQL Server will not fire the After Trigger.
Example : If you insert record/row in a table then the trigger related/associated with the insert event on
this table will fire before the row passes all the constraints, such as primary key constraint and some rules.
If the record/row insertion fails, SQL Server will fire the Instead of Trigger.
If we try to update a view that is based on multiple tables then it will throw an error in such cases
we can use this trigger.
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
IDENTITY:
https://www.c-sharpcorner.com/UploadFile/219d4d/identity-column-in-sql-server/
A SQL Server IDENTITY column is a special type of column that is used to automatically generate
key values based on a provided seed (starting point) and increment
IDENTITY(1,1)
The first parameter is the seed (from where the value will start) and the second parameter is the
increment value.
1. @@IDENTITY
2. SCOPE_IDENTITY
3. IDENT_CURRENT
@@IDENTITY: Returns the last identity values that were generated in a table in the
current session. This method is not limited to a specific scope.
SCOPE_IDENTITY: Returns the last identity values that are generated in any table in the
current session. This method returns values inserted only within the current scope.
IDENT_CURRENT: Returns the last identity value generated for a specific table in any session and
any scope. This method is not affected by scope and session, it only depends on a specific table.
Synthax: IDENT_CURRENT(Tablename)
OFFSET FETCH:
The OFFSET and FETCH clauses are the options of the ORDER BY clause. They allow you to limit
the number of rows to be returned by a query.
The following illustrates the syntax of the OFFSET and FETCH clauses:
1 ORDER BY column_list [ASC |DESC]
2 OFFSET offset_row_count {ROW | ROWS}
3 FETCH {FIRST | NEXT} fetch_row_count {ROW | ROWS} ONLY
In this syntax:
• The OFFSET clause specifies the number of rows to skip before starting to return rows
from the query. The offset_row_count can be a constant, variable, or parameter that is
greater or equal to zero.
• The FETCH clause specifies the number of rows to return after the OFFSET clause has
been processed. The offset_row_count can a constant, variable or scalar that is greater or
equal to one.
• The OFFSET clause is mandatory while the FETCH clause is optional. Also,
the FIRST and NEXT are synonyms respectively so you can use them interchangeably.
Similarly, you can use the FIRST and NEXT interchangeably.