AWS Global Infrastructure

Databases

Topics Covered
  • Cassandra (14 Blogs)
  • MongoDB Dev and Admin (15 Blogs)
  • MySQL (55 Blogs)
  • SQL Essentials Training and Certification (9 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

SQL Server Tutorial – Everything You Need To Master Transact-SQL

Published on Nov 06,2019 181 Views

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

In today’s market, where a humongous amount of data gets generated every day, it is very important to understand how to handle data. SQL Server is an integrated environment developed by Microsoft to handle data. In this article on the SQL Server tutorial, you will be learning all the operations and commands that you need to explore your databases.

For your better understanding, I have divided the blog into the following categories:

CommandsDescription

Data Definition Language commands(DDL)

This set of commands are used to define a database.

Data Manipulation Language commands(DML)

The manipulation commands are used to manipulate the data present in the database.

Data Control Language commands(DCL)

This set of commands deal with the permissions, rights and other controls of the database systems.

Transaction Control Language commands(TCL)

These commands are used to deal with the transaction of the database.

Apart from the commands, the following topics are covered in this article:

MS SQL Server - SQL Server Tutorial - Edureka

  1. What is SQL Server?
  2. Install SQL Server
  3. Connect to SQL Server using SSMS
  4. Access Database Engine
  5. SQL Server Architecture
  6. Comments in SQL
  7. SQL Server Data Types
  8. Keys in database
  9. Constraints in database
  10. Operators
  11. Aggregate Functions
  12. User-Defined functions
  13. Nested Queries
  14. Joins
  15. Loops
  16. Stored Procedures
  17. Exception Handling

 

***NOTE***  In this SQL Server Tutorial, I am going to consider the below database as an example, to show you how to learn and write commands.

StudentIDStudentNameParentNamePhoneNumberAddressCityCountry
1VihaanAkriti Mehra9955339966Brigade Road Block 9HyderabadIndia
2ManasaShourya Sharma9234568762Mayo Road 15KolkataIndia
3AnaySoumya Mishra9876914261Marathalli House No 101BengaluruIndia
4PreetiRohan Sinha9765432234Queens Road 40DelhiIndia
5ShanayaAbhinay Agarwal9878969068Oberoi Street 21 MumbaiIndia

Before we start understanding the different commands used in SQL Server, let us understand what is SQL Server, its architecture and how to install it.

 

What is SQL Server?

Microsoft SQL Server is a relational database management system. It supports the Structured Query language and comes with its own implementation of the SQL language which is the Transact-SQL(T-SQL). It has an integrated environment to handle SQL databases, which is the SQL Server Management Studio.

The key components of SQL Server are as follows:

  • Database Engine: This component handle storage, Rapid transaction Processing, and Securing Data.
  • SQL Server –  This service is used to start, stop, pause and continue the instance of MS SQL Server.
  • SQL Server Agent –  The Server Agent service plays the role of task scheduler and is triggered by any event or as per the requirement.
  • SQL Server Browser – This service is used to connect the incoming request to the desired SQL Server instance.
  • SQL Server Full-Text Search – Used to let the user run full-text queries against the character data in SQL tables.
  • SQL Server VSS WriterAllows backups and restoration of data files when the SQL Server does not run.
  • SQL Server Analysis Services(SSAS)  – This service is used to provide data analysis, data mining and machine learning capabilities. The SQL Server is also integrated with Python and R for advanced data analytics.
  • SQL Server Reporting Services (SSRS) – As the name suggests, this service is used to provide features and decision-making capabilities including integration with Hadoop.
  • SQL Server Integration Services (SSIS)This service is used to perform the ETL operations for different types of data from multiple sources of data.

Now, that you know what is MS SQL Server, let us move forward in this article on the SQL Server tutorial and understand how to install and setup the SQL Server.

 

Install SQL Server

Follow the below steps to install SQL Server:

Step 1: Go to the official page of Microsoft SQL Server download, where you will find the option to install SQL Server either on-premises or on the cloud.

Install SQL Server - SQL Server Tutorial - Edureka

Step 2: Now, scroll down and you will see two options: Developer & Enterprise edition. Here, I will be downloading the Developer edition. To download, you just have to click on the Download now option. Refer below.

Download SQL Server - SQL Server Tutorial - Edureka

Step 3: Once the application is downloaded, double click on the file and you will see the following window.

Installation Type - SQL Server Tutorial - Edureka

Step 4: Now, you can choose either of the 3 options to setup SQL Server. Here, I will just choose the Basic option. On selecting the installation type option, the next screen would be to accept the license agreement. To do that, click on Accept in the following window.

License Agreement - SQL Server Tutorial - Edureka

Step 5: Next, you have to specify the SQL Server installation location. Then, you have to click on Install.

Choose Installation Path - SQL Server Tutorial - Edureka

Once you click on Install, you will see that the required packages are getting downloaded. Now, after the installation is complete, you will see the following screen:

Choose Instance Name - SQL Server Tutorial - Edureka

Here, you can either go forward and click on Connect Now, or you can Customize the installation. For your better understanding, I will go forward and choose Customize.

Step 6: Once you click on Customize in the above window, you will see the following wizard opening up. in the following window, click on Next.

Update - SQL Server Tutorial - Edureka

Step 7: After the rules get installed automatically, click on Next. Refer below.

Install Rules - SQL Server Tutorial - Edureka

Step 8: Next, you have to choose the installation type. So, choose the Perform a new installation of SQL Server 2017 option and then click on Next. 

Install Types - SQL Server Tutorial - Edureka

Step 9: In the wizard that opens, choose the edition: Developer.  Then, click on Next. Refer below.

Product Key - SQL Server Tutorial - Edureka

Step 10: Now, read and accept the license agreements by check-in the radio button and then click on Next. Refer below.

Accept License Agreement - SQL Server Tutorial - Edureka

Step 11: In the below wizard you can choose the features which you wish to install. Also, you can choose the instance root directory and then click on Next. Here, I will choose the Database Engine Services.

Feature Selection - SQL Server Tutorial - Edureka

Step 12: Next you have to name the instance, and automatically the instance ID will be created. Here, I will name the instance “edureka”. Then, click on Next.

Instance Configuration - SQL Server Tutorial - Edureka

Step 13: In the Server Configuration wizard, click on Next.

Server Configuration - SQL Server Tutorial - Edureka

Step 14: Now, you have to enable the authentication modes. Here, you will see the Windows authentication mode and Mixed Mode. I will choose Mixed Mode. Then, mention the password and then I will add the current user as Admin by choosing the Add Current User option.

Database Engine Configuration - SQL Server Tutorial - Edureka

Step 15: Then, choose the configuration file path and click on  Install.

Install - SQL Server Tutorial - Edureka

After the installation is complete, you will see the following screen:

Complete Installation - SQL Server Tutorial - Edureka

 

Connect to SQL Server using SSMS

After the SQL Server is installed, your next step is to connect the SQL Server to the SQL Server Management Studio. To do that follow the below steps:

Step 1: Go back, to the following window, and click on the install SSMS option.

Install SSMS - SQL Server Tutorial - Edureka

Step 2: Once you click on that option, you will be redirected to the following page, where you have to choose Download SSMS.

Download SSMS - SQL Server Tutorial - Edureka

Step 3: After the setup has been downloaded, double-click on the application and you will see the following wizard opening up.

SSMS - SQL Server Tutorial - Edureka

Step 4: Click on Install option, in the above window and you will see that that installation will begin.

Installation in Progress - SQL Server Tutorial - Edureka

Step 5: After the installation is complete you will get a dialog box as shown below.

Setup Complete - SQL Server Tutorial - Edureka

After you install the SSMS, the next step is to access the Database Engine.

 

Accessing Database Engine

When you open the SQL server management studio from the start menu, a window will open similar to the window shown in the picture below.

Connect - SQL Server Tutorial - Edureka

Here, mention the Server Name, Authentication Mode and click on Connect.

After you click on Connect, you will see the following screen.

SQL Server Management Studio - SQL Server Tutorial - Edureka

Well folks, thats how you install and setup the SQL Server. Now, moving forward in this SQL Server tutorial, let us understand the different components of the architecture of SQL Server.

 

SQL Server Architecture

The architecture of SQL Server is as follows:

SQL Server Architecture - SQL Server Tutorial - Edureka-min

  • Server −  This is where the SQL services are installed and the database resides
  • Relational Engine − Contains the query parser, optimizer, and the executor; and the execution happens in the relational engine.
  • Command Parser − Checks the syntax of the query and converts the query to machine language.
  • Optimizer − Prepares the execution plan as output by taking statistics, query and Algebrator tree as input.
  • Query Executor − This is the place where queries get executed step by step
  • Storage Engine − This is responsible for storage and retrieval of data on the storage system, manipulation of data, managing and locking transactions.

Now, that you know how to set up and install SQL Server and its various components, let us get started with writing commands in SQL Server. But, before that let me cover how to write comments in SQL Server.

 

Comments in SQL Server

There are two ways in which you can comment in SQL, i.e. either use the single-line comments or the multi-line comments.

Single-Line Comments

The single-line comments start with two hyphens (–). Hence, the text mentioned after (–), till the end of a single line will be ignored by the compiler.

Example:

--Example of single line comments

Multi-Line Comments 

The multi-line comments start with /* and end with */. Hence, the text mentioned between /* and */ will be ignored by the compiler.

Example:

/* Example for 
multi-line comments */

Now in this article on the SQL Server tutorial, let us start with the first set of commands i.e. Data Definition Language commands.

Data Definition Language commands

This section of the article will give you an idea about the commands with the help of which you can define your database. The commands are as follows:

CREATE

This statement is used to create a table, database or view.

The ‘CREATE DATABASE’ Statement

This statement is used to create a database.

Syntax

CREATE DATABASE DatabaseName;

Example

CREATE DATABASE Students;

The ‘CREATE TABLE’ Statement

As the name suggests, this statement is used to create a table.

Syntax

CREATE TABLE TableName (
Column1 datatype,
Column2 datatype,
Column3 datatype,
....

ColumnN datatype
);

Example

CREATE TABLE StudentInfo
(
StudentID int,
StudentName varchar(8000),
ParentName varchar(8000),
PhoneNumber int,
AddressofStudent varchar(8000),
City varchar(8000),
Country varchar(8000)
);

 

DROP

This statement is used to drop an existing table, database or view.

The ‘DROP DATABASE’ Statement

This statement is used to drop an existing database. The complete information present in the database will be lost as soon as you execute the below command.

Syntax

DROP DATABASE DatabaseName;

Example

DROP DATABASE Students;

The ‘DROP TABLE’ Statement

This statement is used to drop an existing table. The complete information present in the table will be lost as soon as you execute the below command.

Syntax

DROP TABLE TableName;

Example

DROP TABLE StudentInfo;

 

ALTER

The ALTER command is used to add, delete or modify columns or constraints in an existing table.

The ‘ALTER TABLE’ Statement

This statement is used to add, delete, modify columns in a pre-existing table.

The ‘ALTER TABLE’ Statement with ADD/DROP COLUMN

The ALTER TABLE statement is used with ADD/DROP Column command to add and delete a column.

Syntax

ALTER TABLE TableName
ADD ColumnName Datatype;

ALTER TABLE TableName
DROP COLUMN ColumnName;

Example

--ADD Column BloodGroup:
ALTER TABLE StudentInfo
ADD BloodGroup varchar(8000);
 
--DROP Column BloodGroup:
ALTER TABLE StudentInfo
DROP COLUMN BloodGroup ;

The ‘ALTER TABLE’ Statement with ALTER COLUMN

The ALTER TABLE statement can be used with the ALTER column to change the data type of an existing column in a table.

Syntax

ALTER TABLE TableName
ALTER COLUMN ColumnName Datatype;

Example

--Add a column DOB and change the data type from date to datetime.
ALTER TABLE StudentInfo
ADD DOB date;
ALTER TABLE StudentInfo
ALTER COLUMN DOB datetime;

 

TRUNCATE

This SQL command is used to delete the information present in the table but does not delete the table itself. So, if you want to delete the information present in the table, and not delete the table itself, you have to use the TRUNCATE command. Else, use the DROP command.

Syntax

TRUNCATE TABLE TableName;

Example

TRUNCATE TABLE StudentInfo;

 

RENAME

This statement is used to rename one or more tables.

Syntax

sp_rename 'OldTableName', 'NewTableName';

Example

sp_rename 'StudentInfo', 'Infostudents';

Moving on in this article on SQL Server tutorial, let us understand the different data types supported by SQL Server.

 

SQL Server Data Types

Data Type CategoryData Type NameDescriptionRange/ Syntax
Exact numericsnumericUsed to store numeric values and have fixed precision and scale numbers – 10^38 +1 to 10^38 – 1.
tinyintUsed to store integer values0 to 255
smallintUsed to store integer values-2^15 (-32,768) to 2^15-1 (32,767)
bigintUsed to store integer values-2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)
intUsed to store integer values-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
bitStores an integer data type which tale a value of 0, 1 or NULL0, 1, or NULL
decimalUsed to store numeric values and have fixed precision and scale numbers – 10^38 +1 to 10^38 – 1.
smallmoneyUsed to store monetary or currency values.– 214,748.3648 to 214,748.3647
moneyUsed to store monetary or currency values.-922,337,203,685,477.5808 to 922,337,203,685,477.5807 (-922,337,203,685,477.58
to 922,337,203,685,477.58 for Informatica. 
Approximate numericsfloatUsed to store floating-point numeric data– 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to 1.79E+308
realUsed to store floating-point numeric data– 3.40E + 38 to -1.18E – 38, 0 and 1.18E – 38 to 3.40E + 38
Date and timedateUsed to define a date in SQL Server.Syntax: date
smalldatetimeUsed to define a date that is combined with a time of day; where the time is based on a 24-hour day, with seconds always zero (:00) and without fractional seconds.Syntax: smalldatetime
datetimeUsed to define a date that is combined with a time of day with fractional seconds based on a 24-hour clock.Syntax: datetime
datetime2datetime2 is as an extension of the existing datetime type that has a larger default fractional precision, larget date range.Syntax: datetime2
datetimeoffsetUsed to define a date that is combined with a time of a day that has time zone awareness. It is based on a 24-hour clock.Syntax: datetimeoffset
timeUsed to define a time of a day. Syntax: time
Character stringscharUsed to store fixed-size characters.char [ ( n ) ] where n value varies from  1 – 8,000
varcharUsed to store variable-length characters.varchar [ ( n | max ) ] where the n value varies from 1-8000 and the maximum storage allowed is 2GB. 
textUsed to store variable-length non-Unicode dataMaximum string length allowed – 2^31-1 (2,147,483,647)
Unicode character stringsncharUsed to store fixed-size characters.nchar [ ( n ) ] where n value varies from 1-4000
nvarcharUsed to store variable-length characters.varchar [ ( n | max ) ] where the n value varies from 1-4000 and the maximum storage allowed is 2GB. 
ntextUsed to store variable-length Unicode dataMaximum string length allowed – 2^30-1 (2,147,483,647)
Binary stringsbinaryUsed to store binary data types of either fixed lengthbinary [ ( n ) ] where n value varies from  1 – 8,000
varbinaryUsed to store binary data types of either fixed lengthvarbinary [ ( n ) ] where the n vale varies from 1-8000 and the maximum storage allowed is 2^31-1 bytes. 
imageUsed to store variable-length binary data0 – 2^31-1 (2,147,483,647) bytes
Other data typescursorIt is a data type for stored procedure or variables OUTPUT parameters that contain a reference to a cursor.
rowversionUsed to expose automatically generated, unique binary numbers within a database.
hierarchyid Used to represent position in a hierarchy.
uniqueidentifierIs a 16-byte GUID.Syntax: uniqueidentifier
sql_variantUsed to store the values of various SQL Server-supported data typesSyntax: sql_variant
xmlUsed to store XML data type.

xml ( [ CONTENT | DOCUMENT ] xml_schemacollection )

Spatial Geometry TypesUsed to represent data in a Euclidean (flat) coordinate system.
Spatial Geography TypesUsed to store ellipsoidal (round-earth) data, such as GPS latitude and longitude coordinates.
tableUsed to store a result set for processing at a later time

Next, in this article let us understand the different types of keys and constraints in the database.

 

Different Types Of Keys In Database

The following are the different types of keys used in database:

  • Candidate Key – Candidate Key is a set of attributes that can uniquely identify a table. A table can have more than a single candidate key, and out of the chosen candidate keys, one key is chosen as the Primary Key.
  • Super Key – The set of attributes can uniquely identify a tuple. So, candidate keys, unique keys, and primary keys are super keys, but the vice-versa isn’t true.
  • Primary Key – Primary keys are used to uniquely identify every tuple. 
  • Alternate Key – Alternate Keys are those candidate keys that are not chosen as a Primary key.
  • Unique Key –  Unique keys are similar to the primary key, but allow a single NULL value in the column.
  • Foreign Key – An attribute that can only take the values present as the values of some other attribute, is the foreign key to the attribute to which it refers.
  • Composite Key Composite keys are a combination of two or more columns that identify each tuple uniquely.

 

Constraints Used In Database

Constraints are used in a database to specify the rules for data stored in a table. The different types of constraints in SQL are as follows:

NOT NULL

The NOT NULL constraint ensures that a column cannot have a NULL value.

Example

CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000)
);

--NOT NULL on ALTER TABLE
ALTER TABLE StudentsInfo
ALTER COLUMN PhoneNumber int NOT NULL;

UNIQUE

This constraint ensures that all the values in a column are unique.

Example

--UNIQUE on Create Table
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL UNIQUE,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000)
);
 
--UNIQUE on Multiple Columns
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000)
CONSTRAINT UC_Student_Info UNIQUE(StudentID, PhoneNumber)
);
 
--UNIQUE on ALTER TABLE
 
ALTER TABLE StudentsInfo
ADD UNIQUE (StudentID);
 
--To drop a UNIQUE constraint
 
ALTER TABLE  StudentsInfo
DROP CONSTRAINT UC_Student_Info;

CHECK

The CHECK constraint ensures that all the values in a column satisfy a specific condition.

Example

--CHECK Constraint on CREATE TABLE
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000) CHECK (Country ='India')
);
 
--CHECK Constraint on multiple columns
 
CREATE TABLE StudentsInfo
(
StudentID int NOT NULL,
StudentName varchar8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000) CHECK (Country ='India'  AND City = 'Hyderabad')
);
 
--CHECK Constraint on ALTER TABLE
 
ALTER TABLE StudentsInfo
ADD CHECK (Country ='India');
 
--To give a name to the CHECK Constraint
 
ALTER TABLE StudentsInfo
ADD CONSTRAINT CheckConstraintName CHECK (Country ='India');
 
--To drop a CHECK Constraint
 
ALTER TABLE StudentsInfo
DROP CONSTRAINT CheckConstraintName;

DEFAULT

The DEFAULT constraint consists of a set of default values for a column when no value is specified.

Example

--DEFAULT Constraint on CREATE TABLE
 
CREATE TABLE StudentsInfo
(
StudentID int,
StudentName varchar(8000) NOT NULL,
ParentName varchar(8000),
PhoneNumber int ,
AddressofStudent varchar(8000) NOT NULL,
City varchar(8000),
Country varchar(8000) DEFAULT 'India'
);
 
--DEFAULT Constraint on ALTER TABLE
 
ALTER TABLE StudentsInfo
ADD CONSTRAINT defau_Country
DEFAULT 'India' FOR Country;
 
--To drop the Default Constraint
 
ALTER TABLE StudentsInfo
ALTER COLUMN Country DROP defau_Country;

INDEX

The INDEX constraint is used to create indexes in the table, through which you can create and retrieve data from the database very quickly.

Syntax

--Create an Index where duplicate values are allowed
CREATE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);

--Create an Index where duplicate values are not allowed
CREATE UNIQUE INDEX IndexName
ON TableName (Column1, Column2, ...ColumnN);

Example

CREATE INDEX idex_StudentName
ON StudentsInfo (StudentName);
 
--To delete an index in a table
 DROP INDEX StudentsInfo.idex_StudentName;

Moving forward in this article on SQL Server tutorial, let us now understand the different Data Manipulation Language commands used in Microsoft SQL Server.

 

Data Manipulation Language commands

This section of the article will cover all those commands through which you can manipulate the database. The commands are as follows:

Apart from these commands, there are also other manipulative operators/functions such as:

USE

This statement is used to select the database to start performing various operations on it.

Syntax

USE DatabaseName;

Example

USE Students;

 

INSERT INTO

The INSERT INTO statement is used to insert new records into an existing table.

Syntax

INSERT INTO TableName (Column1, Column2, Column3, ...,ColumnN)
VALUES (value1, value2, value3, ...);

--If you don't want to mention the column names then use the below syntax

INSERT INTO TableName
VALUES (Value1, Value2, Value3, ...);

Example

INSERT INTO StudentsInfo(StudentID, StudentName, ParentName, PhoneNumber, AddressofStudent, City, Country)
VALUES ('06', 'Sanjana','Kapoor', '9977331199', 'Buffalo Street House No 10', 'Kolkata', 'India');
 
INSERT INTO StudentsInfo
VALUES ('07', 'Vishal','Mishra', '9876509712', 'Nice Road 15', 'Pune', 'India');

 

UPDATE

The UPDATE statement is used to modify or update the records already present in the table.

Syntax

UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE Condition;

Example

UPDATE StudentsInfo
SET StudentName = 'Aahana', City= 'Ahmedabad'
WHERE StudentID = 1;

 

DELETE

The DELETE statement is used to delete the existing records in a table.

Syntax

DELETE FROM TableName WHERE Condition;

Example

DELETE FROM StudentsInfo
WHERE StudentName='Aahana';

 

MERGE

The MERGE statement is used to perform the INSERT, UPDATE and DELETE operations on a specific table, where the source table is provided. Refer below.

Merge Statement - SQL Server Tutorial - Edureka

Syntax

MERGE TagretTableName USING SourceTableName
ON MergeCondition
WHEN MATCHED
THEN Update_Statement
WHEN NOT MATCHED
THEN Insert_Statement
WHEN NOT MATCHED BY SOURCE
THEN DELETE;

Example

To understand the MERGE statement, consider the following tables as the Source table and the Target table.

Source Table:

StudentIDStudentNameMarks
1Vihaan87
2Manasa92
4Anay74

Target Table:

StudentIDStudentNameMarks
1Vihaan87
2Manasa67
3Saurabh55
MERGE SampleTargetTable TARGET USING SampleSourceTable SOURCE ON (TARGET.StudentID = SOURCE.StudentID)                                                                                       
WHEN MATCHED AND TARGET.StudentName <> SOURCE.StudentName OR TARGET.Marks <> SOURCE.Marks 
THEN UPDATE SET TARGET.StudentName = SOURCE.StudentName, TARGET.Marks = SOURCE.Marks         
WHEN NOT MATCHED BY TARGET THEN  
INSERT (StudentID,StudentName,Marks) VALUES (SOURCE.StudentID,SOURCE.StudentName,SOURCE.Marks)
WHEN NOT MATCHED BY SOURCE THEN         
DELETE;    

Output

StudentIDStudentNameMarks
1Vihaan87
2Manasa92
4Anay74

SELECT

The SELECT statement is used to select data from a database, table or view. The data returned is stored in a result table, called the result-set.

Syntax

SELECT Column1, Column2, ...ColumN
FROM TableName;

--(*) is used to select all from the table
SELECT * FROM table_name;

-- To select the number of records to return use:
SELECT TOP 3 * FROM TableName;

Example

-- To select few columns
SELECT StudentID, StudentName
FROM StudentsInfo;
 
--(*) is used to select all from the table
SELECT * FROM StudentsInfo;
 
-- To select the number of records to return use:
SELECT TOP 3 * FROM StudentsInfo;

We can also use the following keywords with the SELECT statement:

 

 DISTINCT

The DISTINCT keyword is used with the SELECT statement to return only different values.

Syntax

SELECT DISTINCT Column1, Column2, ...ColumnN
FROM TableName;

Example

SELECT DISTINCT PhoneNumber FROM StudentsInfo;

 

ORDER BY

This statement is used to sort the required results either in the ascending or descending order. By default, the results are stored in ascending order. Yet, if you wish to get the results in descending order, you have to use the DESC keyword.

Syntax

SELECT Column1, Column2, ...ColumnN
FROM TableName
ORDER BY Column1, Column2, ... ASC|DESC;

Example

-- Select all students from the 'StudentsInfo' table sorted by ParentName:
SELECT * FROM StudentsInfo
ORDER BY ParentName;
 
-- Select all students from the 'StudentsInfo' table sorted by ParentName in Descending order:
SELECT * FROM StudentsInfo
ORDER BY ParentName DESC;
 
-- Select all students from the 'StudentsInfo' table sorted by ParentName and StudentName:
SELECT * FROM StudentsInfo
ORDER BY ParentName, StudentName;

/* Select all students from the 'StudentsInfo' table sorted by ParentName 
in Descending order and StudentName in Ascending order: */
SELECT * FROM StudentsInfo
ORDER BY ParentName ASC, StudentName DESC;

 

GROUP BY

This statement is used with the aggregate functions to group the result-set by one or more columns.

Syntax

SELECT Column1, Column2,..., ColumnN
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
ORDER BY ColumnName(s);

Example

-- To list the number of students from each city.
SELECT COUNT(StudentID), City
FROM StudentsInfo
GROUP BY City;

 

GROUPING SETS

GROUPING SETS were introduced in SQL Server 2008, used to generate a result-set that can be generated by a UNION ALL of the multiple simple GROUP BY clauses.

Syntax

SELECT ColumnNames(s)
FROM TableName
GROUP BY GROUPING SETS(ColumnName(s));

Example

SELECT StudentID, StudentName, COUNT(City)
from StudentsInfo
Group BY
GROUPING SETS
((StudentID, StudentName, City),(StudentID),(StudentName),(City));

HAVING

This clause is used in the scenario where the WHERE keyword cannot be used.

Syntax

SELECT ColumnName(s)
FROM TableName
WHERE Condition
GROUP BY ColumnName(s)
HAVING Condition
ORDER BY ColumnName(s);

Example

SELECT COUNT(StudentID), City
FROM StudentsInfo
GROUP BY City
HAVING COUNT(StudentID) > 2
ORDER BY COUNT(StudentID) DESC;

 

INTO

The INTO keyword can be used with the SELECT statement to copy data from one table to another. Well, you can understand these tables to be temporary tables. The temporary tables are generally used to perform manipulations on data present in the table, without disturbing the original table.

Syntax

SELECT *
INTO NewTable [IN ExternalDB]
FROM OldTable
WHERE Condition;

Example

-- To create a backup of table 'StudentsInfo'
SELECT * INTO StudentsBackup
FROM StudentsInfo;
 
--To select only few columns from StudentsInfo
SELECT StudentName, PhoneNumber INTO StudentsDetails
FROM StudentsInfo;
 
SELECT * INTO PuneStudents
FROM StudentsInfo
WHERE City = 'Pune';

 

CUBE

CUBE is an extension of the GROUP BY clause. It allows you to generate the sub-totals for all the combinations of the grouping columns specified in the GROUP BY clause.

Syntax

SELECT ColumnName(s)
FROM TableName
GROUP BY CUBE(ColumnName1, ColumnName2, ....., ColumnNameN);

Example

SELECT StudentID, COUNT(City)
FROM StudentsInfo
GROUP BY CUBE(StudentID)
ORDER BY StudentID;  

ROLLUP

ROLLUP is an extension of the GROUP BY clause. This allows you to include the extra rows which represent the subtotals. These are referred to as super-aggregated rows along with the grand total row.

Syntax

SELECT ColumnName(s)
FROM TableName
GROUP BY ROLLUP(ColumnName1, ColumnName2, ....., ColumnNameN);

Example

SELECT StudentID, COUNT(City)
FROM StudentsInfo
GROUP BY ROLLUP(StudentID);

 

OFFSET

The OFFSET clause is used with the SELECT and ORDER BY statement to retrieve a range of records. It must be used with the ORDER BY clause since it cannot be used on its own. Also, the range that you mention must be equal to or greater than 0. If you mention a negative value, then it shows an error.

Syntax

SELECT ColumnNames)
FROM TableName
WHERE Condition
ORDER BY ColumnName(s)
OFFSET RowsToSkip ROWS;

Example

Consider a new column Marks in the StudentsInfo table.

SELECT StudentName, ParentName
FROM StudentsInfo
ORDER BY Marks
OFFSET 1 ROWS;

 

FETCH

The FETCH clause is used to return a set of a number of rows. It has to be used in conjunction with the OFFSET clause.

Syntax

SELECT ColumnNames)
FROM TableName
WHERE Condition
ORDER BY ColumnName(s)
OFFSET RowsToSkip 
FETCH NEXT NumberOfRows ROWS ONLY;

Example

SELECT StudentName, ParentName
FROM StudentsInfo
ORDER BY Marks
OFFSET 1 ROWS
FETCH  NEXT 1 ROWS ONLY;

 

TOP

The TOP clause is used with the SELECT statement to mention the number of records to return.

Syntax

SELECT TOP Number ColumnName(s)
FROM TableName
WHERE Condition;

Example

SELECT TOP 3 * FROM StudentsInfo;

 

PIVOT

PIVOT is used to rotate the rows to column values and runs aggregations when required on the remaining column values.

Syntax

SELECT NonPivoted ColumnName,  
    [First Pivoted ColumnName] AS ColumnName,  
    [Second Pivoted ColumnName] AS ColumnName, 
    [Third Pivoted ColumnName] AS ColumnName,   
    ...  
    [Last Pivoted ColumnName] AS ColumnName  
FROM 
    (SELECT query which produces the data)   
    AS [alias for the initial query]  
PIVOT  
(  
    [AggregationFunction](ColumName)  
FOR  
[ColumnName of the column whose values will become column headers]   
    IN ( [First Pivoted ColumnName], [Second Pivoted ColumnName],  [Third Pivoted ColumnName]
    ... [last pivoted column])  
) AS [alias for the Pivot Table];

Example

To get a detailed example, you can refer to my article on SQL PIVOT and UNPIVOT. Next in this SQL Server Tutorial let us look into the different operators supported by Microsoft SQL Server.

 

Operators

The different types of operators supported by SQL Server are as follows:

Let us discuss each one of them one by one.

 

Arithmetic Operators

OperatorMeaningSyntax

 +

Addition

expression + expression

Subtraction

expression – expression

*

Multiplication

expression * expression

/

Divison

expression / expression

%

Modulous

expression % expression

Assignment Operators

OperatorMeaningSyntax

 =

Assign a value to a variable

variable = ‘value’

Bitwise Operators

OperatorMeaningSyntax

 & (Bitwise AND)

Used to perform a bitwise logical AND operation between two integer values.

expression & expression

&= (Bitwise AND Assignment)

Used to perform a bitwise logical AND operation between two integer values. It also sets a value to the output of the operation.

expression &= expression

| (Bitwise OR)

Used to perform a bitwise logical OR operation between two integer values as translated to binary expressions within Transact-SQL statements.

expression | expression

|= (Bitwise OR Assignment)

Used to perform a bitwise logical OR operation between two integer values as translated to binary expressions within Transact-SQL statements. It also sets a value to the output of the operation.

expression |= expression

^ (Bitwise Exclusive OR)

Used to perform a bitwise exclusive OR operation between two integer values.

expression ^ expression

^= (Bitwise Exclusive OR Assignment)

Used to perform a bitwise exclusive OR operation between two integer values. It also sets a value to the output of the operation.

expression ^= expression

~ (Bitwise NOT)

Used to perform a bitwise logical NOT operation on an integer value.

~ expression

Comparison Operators

OperatorMeaningSyntax

 =

 Equal to

expression = expression

>

Greater than

expression > expression

<

Less than

expression < expression

>=

Greater than or equal to

expression >= expression

<=

Less than or equal to

expression <= expression

<>

Not equal to

expression <> expression

!=

Not equal to

expression != expression

!<

Not less than

expression !< expression

!>

Not greater than

expression !> expression

Compound Operators

OperatorMeaningSyntax

+ =

Used to add value to the original value and set the original value to the result.

expression += expression

-=

Used to subtract a value from the original value and set the original value to the result.

expression -= expression

*=

Used to multiply value to the original value and set the original value to the result.

expression *= expression

/=

Used to divide a value from the original value and set the original value to the result.

expression /= expression

%=

Used to divide a value from the original value and set the original value to the result.

expression %= expression

&=

Used to perform a bitwise AND operation and set the original value to the result.

expression &= expression

^=

Used to perform a bitwise exclusive OR operation and set the original value to the result.

expression ^= expression

|=

Used to perform a bitwise OR operation and set the original value to the result.

expression |= expression

Logical Operators

OperatorMeaningSyntax

ALL

Returns TRUE if all of set of comparisons are TRUE.

scalar_expression { = | <> | != | > | >= | !> | < | <= | !< } ALL ( subquery )

AND

Returns TRUE if both the expressions are TRUE.

boolean_expression AND boolean_expression

ANY

Returns TRUE if any one of a set of comparisons are TRUE.

scalar_expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } { ANY } ( subquery )

BETWEEN

Returns TRUE if an operand is within a range.

sampleexpression [ NOT ] BETWEEN beginexpression AND endexpression

EXISTS

Returns TRUE if a subquery contains any rows.

 EXISTS (sub query)

IN

Returns TRUE if an operand is equal to one of a list of expressions.

test_expression [ NOT ] IN( subquery | expression [ ,…n ])

LIKE

Returns TRUE if an operand matches a pattern.

match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

NOT

Reverses the value of any boolean operator.

[ NOT ] boolean_expression

OR

Returns TRUE if either of the boolean expression is TRUE.

boolean_expression OR boolean_expression

SOME

Returns TRUE if some of a set of comparisons are TRUE.

scalar_expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } { SOME} ( subquery )

Scope Resolution Operators

OperatorMeaningExample

 ::

Provides access to static members of a compound data type. Compound data types are those data types which contain multiple methods and simple data types. Compound data types These include  the built-in CLR types and custom SQLCLR User-Defined Types (UDTs).

DECLARE @hid hierarchyid; SELECT @hid = hierarchyid::GetRoot(); PRINT @hid.ToString();

 

Set Operators

There are mainly three set operations: UNIONINTERSECTMINUS. You can refer to the image below to understand the set operations in SQL. Refer to the below image:

SET Operators - SQL Server Tutorial - Edureka

OperatorMeaningSyntax

UNION

The UNION operator is used to combine the result-set of two or more SELECT statements.

SELECT ColumnName(s) FROM Table1
UNION
SELECT ColumnName(s )FROM Table2;

INTERSECT

The INTERSECT clause is used to combine two SELECT statements and return the intersection of the data-sets of both the SELECT statements.

SELECT Column1 , Column2 ….
FROM TableName;
WHERE Condition
INTERSECT
SELECT Column1 , Column2 ….
FROM TableName;
WHERE Condition

EXCEPT

The EXCEPT operator returns those tuples that are returned by the first SELECT operation, and are not returned by the second SELECT operation.

SELECT ColumnName
FROM TableName;
EXCEPT
SELECT ColumnName
FROM TableName;

String Operators

OperatorMeaningSyntax/ Example

 + (String Concatenation)

Concatenates two or more binary or character strings, columns, or a combination of strings and column names into a single expression

expression+expression

 += (String Concatenation)

Used to concatenate two strings and sets the string to the result of the operation. 

expression+=expression

% (Wildcard Characters to match)

Used to matches any string of zero or more characters. 

Example: ‘sample%’

[] (Wildcard Characters to match)

Used to match a single character within the specified range or set that is specified between brackets []. 

Example:  m[n-z]%’

[^] (Wildcard Characters to match)

Used to match a single character which is not within the range or set specified between the square brackets.

Example:  ‘Al[^a]%’

_ (Wildcard Characters to match)

Used to match a single character in a string comparison operation

test_expression [ NOT ] IN( subquery | expression [ ,…n ])

Aggregate Functions

The different aggregate functions supported by SQL Server are as follows:

FunctionDescriptionSyntaxExample

SUM()

Used to return the sum of a group of values.

SELECT SUM(ColumnName) FROM TableName;

SELECT SUM(Marks) FROM StudentsInfo;

COUNT() 

Returns the number of rows either based on a condition, or without a condition.

SELECT COUNT(ColumnName) FROM TableName WHERE Condition;

SELECT COUNT(StudentID) FROM StudentsInfo;

AVG()

Used to calculate the average value of a numeric column.

SELECT AVG(ColumnName) FROM TableName;

SELECT AVG(Marks) FROM StudentsInfo;

MIN()

This function returns the minimum value of a column. 

SELECT MIN(ColumnName) FROM TableName;

SELECT MIN(Marks) FROM StudentsInfo;

MAX()

Returns a maximum value of a column. 

SELECT MAX(ColumnName) FROM TableName;

SELECT MAX(Marks) FROM StudentsInfo;

FIRST()

Used to return the first value of the column.

SELECT FIRST(ColumnName) FROM TableName;

SELECT FIRST(Marks) FROM StudentsInfo;

LAST() 

This function returns the last value of the column.

SELECT LAST(ColumnName) FROM TableName;

SELECT LAST(Marks) FROM StudentsInfo;

 

User-Defined Functions

Microsoft SQL Server allows the users to create user-defined functions which are routines. These routines accept parameters, can perform simple to complex actions and return the result of that particular action as a value. Here, the value returned can either be a single scalar value or a complete result-set.

You can use user-defined functions to:

  • Allow modular programming
  • Reduce network traffic
  • Allow faster execution of queries

Also, there are different types of user-defined functions you can create. They are:

  • Scalar Functions: Used to return a single data value of the type defined in the RETURNS clause.
  • Table-Valued Functions: Used to return a table data type.
  • System Functions: A variety of system functions are provided by the SQL Server to perform different operations.

Well, apart from the user-defined functions, there is a bunch of in-built functions in SQL Server; which can be used to perform a variety of tasks. Moving on in this article on SQL Server tutorial, let us now understand what are nested queries.

 

Nested Queries

Nested queries are those queries that have an outer query and inner subquery. So, basically, the subquery is a query which is nested within another query such as SELECT, INSERT, UPDATE or DELETE. Refer to the image below:

Nested Queries - SQL Server Tutorial - Edureka

Next in this SQL Server tutorial, let us understand the different types of joins in SQL.

 

Joins

Joins are used to combine tuples from two or more tables, based on a related column between the tables. There are four types of joins: 

  • INNER JOIN: Returns records that have matching values in both the tables.
  • LEFT JOIN: Returns records from the left table, and also those records which satisfy the condition from the right table.
  • RIGHT JOIN: Returns records from the right table, and also those records which satisfy the condition from the left table.
  • FULL JOIN: Returns records which either have a match in the left or the right table.

Joins - SQL Server Tutorial - Edureka

Consider the following table along with the StudentsInfo table, to understand the syntax of joins.

SubjectIDStudentIDSubjectName
1010Maths
211Physics
312Chemistry

INNER JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT Subjects.SubjectID, StudentsInfo.StudentName
FROM Subjects
INNER JOIN StudentsInfo ON Subjects.StudentID = StudentsInfo.StudentID;

 

LEFT JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT StudentsInfo.StudentName, Subjects.SubjectID
FROM StudentsInfo
LEFT JOIN Subjects ON StudentsInfo.SubjectID = Subjects.SubjectID
ORDER BY StudentsInfo.StudentName;

 

RIGHT JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT StudentsInfo.StudentName, Subjects.SubjectID
FROM StudentsInfo
RIGHT JOIN Subjects ON StudentsInfo.SubjectID = Subjects.SubjectID
ORDER BY StudentsInfo.StudentName;

 

FULL JOIN

Syntax

SELECT ColumnName(s)
FROM Table1
FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;

Example

SELECT StudentsInfo.StudentName, Subjects.SubjectID
FROM StudentsInfo
FULL OUTER JOIN Subjects ON StudentsInfo.SubjectID = Subjects.SubjectID
ORDER BY StudentsInfo.StudentName;

Next, in this article on SQL Server tutorial, let us understand the different types of loops supported by the SQL Server.

 

Loops

The different control-of-flow commands are as follows:

Let us discuss each one of them one by one.

 

BEGIN..END

These keywords are used to enclose a series of SQL statements.  Then, this group of SQL statements can be executed. 

Syntax

BEGIN   
     { SQLStatement | StatementBlock }   
END

BREAK

This statement is used to exit the current WHILE loop. In case, the current WHILE loop is nested inside another loop, then the BREAK statement exits only the current loop and the control is passed on to the next statement in the current loop. The BREAK statement is generally used inside an IF statement.

Syntax

BREAK;

CONTINUE

The CONTINUE statement is used to restart a WHILE loop. So, any statements after the CONTINUE keyword will be ignored.

Syntax

CONTINUE;

Here, Label is the point after which processing starts if a GOTO is targeted to that particular label.

 

GOTO

Used to alter the flow of execution to a label.  The statements written after the GOTO keyword are skipped and processing continues at the label. 

Syntax

Define Label:   
Label:   
Alter Execution:  
GOTO Label

Here, Label is the point after which processing starts if a GOTO is targeted to that particular label.

 

IF..ELSE

Like any other programming language, the If-else statement in SQL Server tests the condition and if the condition is false then ‘else’ statement is executed.

Syntax

IF BooleanExpression      
     { SQLStatement | StatementBlock }   
[ ELSE   
     { SQLStatement | StatementBlock } ]

RETURN

Used to exit unconditionally from a query or procedure. So, the statements which are written after the RETURN clause are not executed.

Syntax

RETURN [ IntegerExpression ]

Here, an integer value is returned.

 

WAITFOR

The WAITFOR control flow is used to block the execution of a stored procedure, transaction or a batch until a specific statement modifies,  returns at least one row or a specified time or time interval elapses.

Syntax

WAITFOR   
{  
    DELAY 'TimeToPass'   
  | TIME 'TimeToExecute'   
  | [ ( RecieveStatement ) | ( GetConversionGroupStatement ) ]   
    [ , TIMEOUT timeout ]  
}

where,

  • DELAY – Period of time that must pass
  • TimeToPass – Period of time to wait
  • TIME – The time when the stored procedure, transaction or the batch runs.
  • TimeToExecute – The time at which the WAITFOR statement finishes.
  • RecieveStatement – A valid RECEIVE statement.
  • GetConversionGroupStatement – A valid GET CONVERSATION GROUP statement.
  • TIMEOUT timeoutSpecifies the period of time, in milliseconds, to wait for a message to arrive on the queue.

 

WHILE

This loop is used to set a condition for repeated execution of a particular SQL statement or a SQL statement block. The statements are executed as long as the condition mentioned by the user is TRUE. As soon as the condition fails, the loop stops executing.

Syntax

WHILE BooleanExpression 
{ SQLStatement | StatementBlock | BREAK | CONTINUE }

Now, that you guys know the DML commands, let’s move onto our next section in this article on SQL Tutorial i.e. the DCL commands.

 

Data Control Language Commands (DCL)

This section of SQL Server tutorial will give you an idea about the command through which are used to enforce database security in multiple user database environments. The commands are as follows:

GRANT

The GRANT command is used to provide access or privileges on the database and its objects to the users.

Syntax

GRANT PrivilegeName
ON ObjectName
TO {UserName |PUBLIC |RoleName}
[WITH GRANT OPTION];

where,

  • PrivilegeName – Is the privilege/right/access granted to the user.
  • ObjectName – Name of a database object like TABLE/VIEW/STORED PROC.
  • UserName – Name of the user who is given the access/rights/privileges.
  • PUBLIC – To grant access rights to all users.
  • RoleName – The name of a set of privileges grouped together.
  • WITH GRANT OPTION – To give the user access to grant other users with rights.

Example

-- To grant SELECT permission to StudentsInfo table to user1
GRANT SELECT ON StudentsInfo TO user1;

 

REVOKE

The REVOKE command is used to withdraw the user’s access privileges given by using the GRANT command.

Syntax

REVOKE PrivilegeName 
ON ObjectName 
FROM {UserName |PUBLIC |RoleName}

Example

-- To revoke the granted permission from user1
REVOKE SELECT ON StudentsInfo TO user1;

Moving on in this SQL Server tutorial, let us understand the how to create and use Stored Procedures.

 

Stored Procedures

Stored Procedures are reusable units that encapsulate a specific business logic of the application. So, it is a  group of SQL statements and logic, compiled and stored together to perform a specific task.

Syntax

CREATE [ OR REPLACE] PROCEDURE procedure_name [
(parameter_name [IN | OUT | IN OUT] type [ ])]
{IS | AS }
BEGIN [declaration_section]
executable_section 
//SQL statement used in the stored procedure
END
GO

Example

--Create a procedure that will return a student name when the StudentId is given as the input parameter to the stored procedure
Create  PROCEDURE GetStudentName 
(
@StudentId INT, --Input parameter ,  
@StudName VARCHAR(50)  OUT  --Output parameter, 
AS
BEGIN
SELECT @StudName = StudentName FROM StudentsInfo WHERE StudentID=@StudentId
END

Steps to execute:

      • Declare @StudName as nvarchar(50)
      • EXEC GetStudentName 01, @StudName output
      • SELECT @StudName

The above procedure returns the name of a particular student, on giving that students id as input. Next in this SQL Server tutorial, let us understand the transaction control language commands.

 

Transaction Control Language Commands (TCL)

This section of SQL Server tutorial will give you an insight into the commands which are used to manage transactions in the database. The commands are as follows:

COMMIT

The COMMIT command is used to save the transaction into the database.

Syntax

COMMIT;

ROLLBACK

The ROLLBACK command is used to restore the database to the last committed state.

Syntax

ROLLBACK;

NOTE: When you use ROLLBACK with SAVEPOINT, then you can directly jump to a savepoint in an ongoing transaction. Syntax: ROLLBACK TO SavepointName;

 

SAVEPOINT

The SAVEPOINT command is used to temporarily save a transaction.  So if you wish to rollback to any point, then you can save that point as a ‘SAVEPOINT’.

Syntax

SAVEPOINT SAVEPOINTNAME;

Consider the below table to understand the working of transactions in the database.

StudentIDStudentName
1Rohit
2Suhana
3Ashish
4Prerna

Now, use the below SQL queries to understand the transactions in the database.

INSERT INTO StudentTable VALUES(5, 'Avinash');
COMMIT;
UPDATE StudentTable SET name = 'Akash' WHERE id = '5';
SAVEPOINT S1;
INSERT INTO StudentTable VALUES(6, 'Sanjana');
SAVEPOINT S2;
INSERT INTO StudentTable VALUES(7, 'Sanjay');
SAVEPOINT S3;
INSERT INTO StudentTable VALUES(8, 'Veena');
SAVEPOINT S4;
SELECT * FROM StudentTable;

Next in this article on SQL Server tutorial let us understand how to handle exceptions in Transact-SQL.

 

Exception Handling

There are two types of exceptions, i.e, the system-defined exceptions and the user-defined exceptions. As the name suggests, exception handling is a process through which a user can handle the exceptions generated. To handle exceptions you have to understand the following control flow statements:

THROW

This clause is used to raise an exception and transfers the execution to a CATCH block of a TRY…CATCH construct.

Syntax

THROW [ { ErrorNumber | @localvariable },  
        { Message | @localvariable },  
        { State | @localvariable } ]   
[ ; ]

where,

  • ErrorNumber – A constant or variable that represents the exception. 
  • Message – A variable or string that describes the exception. 
  • State A constant or variable between 0 and 255 that indicates the state to associate with the message.
THROW 51000, 'Record does not exist.', 1;  

TRY..CATCH

Used to implement exception handling in Transact-SQL. A group of statements can be enclosed in the TRY block. In case an error occurs in the TRY block, control is passed to another group of statements that are enclosed in a CATCH block.

Syntax

BEGIN TRY  
     { SQLStatement | StatementBlock}  
END TRY  
BEGIN CATCH  
     [ { SQLStatement | StatementBlock } ]  
END CATCH  
[ ; ]
BEGIN TRY  
    SELECT * FROM StudentsInfo;  
END TRY  
BEGIN CATCH  
    SELECT   
        ERROR_NUMBER() AS ErNum , ERROR_MESSAGE() AS ErMsg;  
END CATCH

With this, we come to the end of this article on SQL Server Tutorial. I hope you enjoyed reading this article on SQL Server Tutorial For Beginners. If you wish to get a structured training on MySQL, then check out our MySQL DBA Certification Training which comes with instructor-led live training and real-life project experience. This training will help you understand MySQL in-depth and help you achieve mastery over the subject. Got a question for us? Please mention it in the comments section of ”SQL Server Tutorial” and I will get back to you.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.