0% found this document useful (0 votes)
1 views

SQL Server Full Course

This document provides a comprehensive overview of MS SQL Server, covering its definition, importance, and various SQL commands such as DDL, DML, and DCL. It explains the structure of relational databases, including tables, columns, and rows, as well as the concept of data integrity through constraints. Additionally, it discusses SQL Server Management Studio and the processes for creating, altering, and deleting databases and tables within SQL Server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

SQL Server Full Course

This document provides a comprehensive overview of MS SQL Server, covering its definition, importance, and various SQL commands such as DDL, DML, and DCL. It explains the structure of relational databases, including tables, columns, and rows, as well as the concept of data integrity through constraints. Additionally, it discusses SQL Server Management Studio and the processes for creating, altering, and deleting databases and tables within SQL Server.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

SQL SERVER FULL COURSE

ALL YOU NEED TO KNOW TO GET GOING


WITH MS SQL SERVER

C#.NET 1
MS SQL SERVER FULL COURSE

What is SQL?
• SQL stands for Structured Query Language.
• It is a programming language for storing and processing information in a relational
database.
• It can create new databases and tables in a relational database.
• It can execute queries against a database relational.
• It can retrieve/select data/records from a relational database.
• It can insert, update and delete records from a relational database.
• It can create stored procedures, views and functions etc. in a relational database.
• It can set permissions on tables, procedures, and views in a relational database.

2
MS SQL SERVER FULL COURSE

Importance of SQL
• SQL is a popular query language to work with databases.
• It is portable
• It processes queries quickly
• It doesn’t require coding skills
• It uses standardized language
• It provides multiple data views
• It has open-source code
• It’s used by major database management system vendors
• It’s highly interactive
• It is frequently used in all types of applications that interacts with databases in someway.
• SQL integrates well with different programming languages, and it makes life easier for Data
analysts and developers learn and use it.
• For example, they can embed SQL queries with the C#/Java/Python programming language to
build high-performing data processing applications with major SQL database systems such as
Oracle or MS SQL Server.

3
MS SQL SERVER FULL COURSE

SQL is a standard but …


• Although SQL is an ANSI/ISO standard, there are different versions of the SQL
language.
• However, to be compliant with the ANSI standard, they all support at least the major
commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.
• Note: Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard! For example, PL/SQL and T-SQL.

4
MS SQL SERVER FULL COURSE

Working of SQL
• SQL implementations involve a server machine that processes the database queries and
returns the results.
• Parser
• Correctness – The parser verifies the semantics, or rules, that ensure the correctness of the query
statement, like semicolon, commos etc.
• Authorization – Validates that the user running the query has the necessary authorization.
• Relational Engine – Creates a plan for retrieving, writing, or updating the corresponding
data in the most effective manner.
• Database Engine – It is the software component that processes the byte code and runs the
intended SQL statement. It reads and stores the data in the database files on physical disk
storage. Upon completion, the storage engine returns the result to the requesting application.

5
MS SQL SERVER FULL COURSE

RDBMS
• RDBMS stands for Relational Database Management System.
• A relational database management system (RDBMS) is a program used to create, update,
store and provide access to data points that are related to one another.
• Some of the most well-known RDBMSs include MySQL, PostgreSQL, MariaDB, Microsoft SQL
Server, and Oracle Database.
• A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model as introduced by E. F. Codd in 1970.

6
MS SQL SERVER FULL COURSE

Table, Column, Row and NULL


• Table
• It is basically a collection of related data entries, and it consists of numerous columns and rows.
• It is the basic data storage object in RDBMS.
• Column (Field)
• Every table is broken up into smaller entities called fields. A column is a vertical entity in a table that
contains all information associated with a specific field in a table.
• Row (Record)
• A record is also called as a row. It contains each individual field/column that exists in a table.
• NULL
• It is very important to understand that a NULL value. It is different than a zero value or a field that
contains spaces. A field with a NULL value is the one that has been left blank during a record
creation.

7
MS SQL SERVER FULL COURSE

SQL Commands
• SQL commands are specific keywords or statements that developers use to work with data
stored in a relational database. We can categorize SQL commands as follows.
• DDL Commands – Data Definition Language refers to SQL commands that design the
database structure. DDL commands are used to create, modify and Delete database objects
based on the business requirements. For example, CREATE command to create database
objects such as tables, views, and indexes.
• DQL Commands – Data Query Language consists of instructions for retrieving data stored in
relational databases. Software applications use the SELECT command to filter and return
specific results from a SQL table.

8
MS SQL SERVER FULL COURSE

SQL Commands
• DML Commands – Data Manipulation Language statements write new information or
modify existing records in a relational database. For example, an application uses the
INSERT command to store a new record in the database.
• TCL Commands – Transaction Control Language is used to manage transections in a
relational database. For example, the database uses the ROLLBACK command to undo
an erroneous transaction.
• DCL Commands – Database administrators use Data Control Language to manage or
authorize database access for other users. For example, they can use the GRANT
command to permit certain applications to manipulate one or more tables.

9
MS SQL SERVER FULL COURSE

SQL Commands
• DDL Commands – CREATE, ALTER, DROP and TRUNCATE
• DQL Commands – SELECT
• DML Commands – INSERT, UPDATE and DELETE
• TCL Commands – COMMIT and ROLLBACK
• DCL Commands – GRANT and REVOKE

Note – In some books SELECT is kept in DQL and in others SELECT is kept in DML.

10
MS SQL SERVER FULL COURSE

What is SQL Server?


• The SQL Server is a relational database management system (RDBMS) which is
developed by Microsoft. It is also called MS SQL Server.
• This product is built on the basic function of storing and retrieving data as required by
other applications. It can be run either on the same computer or on another across a
network.
• It is one of the most popular and powerful RDBMS. It can work well small as well
enterprise level data management tasks.
• It has different versions for different kind of needs. SQL Server Express edition is the
free edition that can be used in production for small and medium database handling.
• SQL Server Developer Edition is the full flagged SQL Server, but it cannot be used in
production. It is only for the developers and learners.

11
MS SQL SERVER FULL COURSE

What is SQL Server Management Studio?


• SSMS (SQL Server Management Studio) is a client tool that is used to connect to SQL
Server and write and execute query.
• SSMS comes with a lot of features that enables developer to work effectively and
efficiently with SQL Server.

12
MS SQL SERVER FULL COURSE

Creating, Altering and Deleting Database in SQL Server


• In SQL Server we have two type of databases
• System Databases
• Master Database – Store all system-level information such as system id, culture, server id no, server
version, server culture, etc.
• Model Database – Acts as a template for creating new databases under a server environment.
• MSDB (Microsoft Database) – Store jobs and alerts information i.e., backup file information.
• TEMPDB Database – It is a temporary database location that is allocated by the server when the user
connected to the SQL Server for storing temporary table information.
• User Databases
• Databases that are created and managed by the users are called User Databases.
• Developers works with User Databases. These databases are used for storing business-related
information.
• In SQL Server, the user databases can be created, altered and dropped in two ways
• Using GUI
• Using SQL Query

13
MS SQL SERVER FULL COURSE

Creating, Altering and Deleting Database in SQL Server


• Whenever we create a database tow files gets created
• .MDF File – Master Data File – Contains Actual Data
• .LDF File – Log Data File – Contains log information e.g., Transaction information for Insert,
Update, Delete, Create etc.
• Above two files are used for transferring the required database from one system to
another system or from one location to another location.
• CREATE DATABASE Database_Name
• ALTER DATABASE Database_Name MODIFY NAME = New_Database_Name
• EXECUTE SP_RENAMEDB ‘Database_Name’, ‘New_Database_Name’
• DROP DATABASE Database_Name (You cannot drop a database if it is currently in use.)
• System databases cannot be dropped.

14
MS SQL SERVER FULL COURSE

Creating, Altering and Deleting Table in SQL Server


• CREATE Command
• CREATE command is used to create a new database object in a database such as tables, views,
functions, etc.
• In SQL Server, all database objects are saved with an extension of “dbo.<object name>”.
• Rules for Creating a table
• Table name should be unique under a database.
• Column name should be unique within the table definition.
• Table name should not start with numeric and special characters except the (-) underscore
symbol.
• Table name should not contain spaces. If you want to provide space in a table name, then you
can use the underscore symbol.
• Table name should contain a minimum of 1 character and a maximum of 128 characters.
• Table should contain a minimum of 1 column and a maximum of 1024 columns.

15
MS SQL SERVER FULL COURSE

Creating, Altering and Deleting Table in SQL Server


• ALTER Command
• ALTER Command is used to change or modify the structure of a table.
• In SQL Server, using ALTER Command can do the following operations on an existing table
• Increase/decrease the length(width) of a column.
• Change the data type of a column.
• Change the NOT NULL to NULL or NULL to NOT NULL.
• Used to add a new column to an existing table.
• Used to drop an existing column.
• Used to add a new constraint.
• Used to drop an existing constraint on a table.
• Disable or re-enable check constraint of a table.
• Changing a column name in the table.
• SP_RENAME ‘<Table_Name>.<Old_Column_Name>’, ‘New_Column_Name’
• SP_RENAME ‘<Old_Table_Name>’, ‘New_Table_Name’

16
MS SQL SERVER FULL COURSE

Creating, Altering and Deleting Table in SQL Server


• DROP Command
• If we want to delete a table/view/sp from the database, the we can use DROP Command.
• DROP TABLE Table_Name.
• When a table is dropped all the dependent constraint that are associated with the table also
gets dropped.
• Delete Command
• If we want to delete some specific data from a table, then we can use delete command.
• If we will not use where clause, then it will delete all the data from the table
• TRUNCATE Command
• When we want to delete all the records from a table, then we can use the TRUNCATE command.
• We cannot use WHERE Clause with TRUNCATE Command.
• If we have Identity Column in the table, TRUNCATE Command resets it.

17
MS SQL SERVER FULL COURSE

Delete vs Truncate

Delete Truncate
It is a DML Command. It is a DDL Command.
It can delete specific records from a table. It empty the entire table. Cannot delete specific records.
It supports where clause. It does not support where clause.
It a temporary deletion. It is a permanent deletion.
It supports rollback for restoring deleted data. It does not support rollback. Data can’t be restored once truncated.
It will not reset the Identity Property. It will reset the Identity Property.

18
MS SQL SERVER FULL COURSE

Identity Column in SQL Server


• Identity is a property that can be applied to a column of a table.
• Identity column value is automatically created by the server.
• We as a user cannot insert a value manually into an Identity column.
• SEED – Starting value of a column. Default is 1.
• INCREAMENT – Incremental value that is added to previous value. Default is 1.

• Explicit Value for an Identity Column


• Turn on Identity Insert – SET IDENTITY_INSERT Table_Name ON
• We must supply value to identity column in insert query. If we don’t, we will get an error
• To turn off Identity Insert – SET IDENTITY_INSERT Table_Name OFF
• To reset identity column value – DBCC CHECKIDENT(Table_Name,RESEED,0)

19
MS SQL SERVER FULL COURSE

Constraints – What is Data Integrity?


• Process of ensuring that the data contained in the database is accurate, consistent, and
reliable is known as Data Integrity.
• To ensure data integrity, RDBMS provides us with a set of integrity constraints that
ensures that the data entered the database is going to be accurate, consistent, and
reliable.
• Data Integrity is most important because Data Integrity is the reason end-user can trust
the data.

20
MS SQL SERVER FULL COURSE

Constraints – What is a Constraint?


• A Constraint is a property that can be assigned to a column or columns of a table to
maintain data integrity.
• Constraints are used to restrict the insert/update/delete of unwanted data to maintain
data integrity.
• Constraint can be created on single or multiple columns of a table in SQL Server.
• Types of SQL Server Constraints
• Default Constraint
• UNIQUE KEY constraint
• NOT NULL constraint
• CHECK KEY constraint
• PRIMARY KEY constraint
• FOREIGN KEY constraint

21
MS SQL SERVER FULL COURSE

Constraints – Ways to Impose Constraints


• We can impose constrains in two ways on a table
• On Column
• On Table

22
MS SQL SERVER FULL COURSE

Constraints – Composite Constrains


• A constraint that is created based on more than one column is called as a Composite
Constraint.

23
MS SQL SERVER FULL COURSE

Constraints in Action
• Default Constrains
• NOT NULL Constrains
• UNIQUE Constrains
• CHECK Constrains

24
MS SQL SERVER FULL COURSE

Constraints in Action
• PRIMARY KEY Constrain
• It is the combination of UNIQUE and NOT NULL Constrains.
• It will not allow NULL or Duplicate values into a column on which PK is applied.
• Primary Key enforces entity integrity i.e., using PK we can identify a record uniquely in a table.
• Composite PK Constrain
• Primary Key constraint containing more than one columns is called a Composite Primary Key.
• A Composite PK can include maximum 16 columns.
• A Composite PK can be created at the table level, it cannot be created at the column level.

• Note: In a composite primary key, each column can accept duplicate values, but the
combination of all columns should not contain duplicate values.
• Question – What is the difference between PK and UK?
• Share your thoughts in comment box.

25
MS SQL SERVER FULL COURSE

Constraints in Action
• FOREIGN KEY Constrain
• A foreign key in a table points to the primary key or unique key in another table.
• The foreign key constraints are used to enforce referential integrity.
• Creating relationship between the database tables is one of the most important concepts in a
database.
• These relationship provides a mechanism for linking the data stored in multiple tables and
retrieving them in an efficient manner.
• We can specify an FK in a table that references a column in another table to create a link
between two tables.
• That means Foreign Key constraint is used for binding two tables with each other and then
verify the existence of one table data in other tables.

26
MS SQL SERVER FULL COURSE

Constraints in Action
• Rules to create FK Constrain
• Both the tables must have a common column for linking the tables.
• The common column in both the tables need not have the same name but must have the same
data type.
• The common column in parent table or master table is known as the reference key column and
should not contain any duplicate values.
• So, this column must be UNIQUE or PRIMARY KEY column.
• The common column present in the child or detailed table is known as the Foreign KEY
column.
• We need to impose a Foreign KEY constraint on the column which refers to the reference key
column of the master table.

27
MS SQL SERVER FULL COURSE

Constraints in Action
• Rules for FK Columns
• Rule1 – Cannot insert a value into the foreign key column if value is not existing in the
reference key column of the parent (master) table.
• Rule2 – Cannot update the reference key value of a parent table provided that the value has a
corresponding child record in the child table without addressing what to do with the child
records.
• Rule3 – Cannot delete a record from the parent table if records reference key value has child
record in the child table without addressing what to do with the child record.

• Question – What is the difference between Primary Key and Foreign Key Constraint in
SQL Server?
• Share you answer in comment box.

28
MS SQL SERVER FULL COURSE

Constraints in Action – Cascade Referential Integrity


• Cascading Referential Integrity Constrains are the foreign key constraints that tell SQL Server
to perform certain actions whenever a user attempts to delete or update a primary key to
which an existing foreign keys point.
• SET NULL
• Records in the child table will be set to null when the related record in the parent table will be deleted or
updated
• CASCADE
• Records in the child table will be deleted/updated when the related record in the parent table will be
deleted or updated
• SET DEFAULT
• Records in the child table will be set to default when the related record in the parent table will be
deleted or updated.
• It requires a default constraint defined on the child table.
• NO ACTION
• This is the default action. The action will be denied and rolled back.

29
MS SQL SERVER FULL COURSE

Constraints in Action – Cascade Referential Integrity

30
MS SQL SERVER FULL COURSE

SELECT Statement
• SELECT statement is used to fetch data from one or multiple database tables bases on
one or multiple business criteria.
• SELECT * FROM TableName
• SELECT Column_List FROM TableName
• SELECT SomeExpression FROM Table Name
• SELECT */Column_List/SomeExpression FROM TableName WHERE SomeCondition

31
MS SQL SERVER FULL COURSE

SELECT Statement - WHERE Clause


• WHERE clause is used to fetch data based on some condition. Only those rows will be
returned from database for which the condition will be true.

• SELECT * FROM TableName WHERE Condition

32
MS SQL SERVER FULL COURSE

SELECT Statement – * (ALL)


• We use * symbol to represent all. When we write SELECT * FROM TableName, all the
rows/records from that table will be returned.
• When we need to select all rows based on some condition then we can use where clause
with SELECT statement, like SELECT * FROM TableName WHERE Condition.

33
MS SQL SERVER FULL COURSE

SELECT Statement – DISTINCT


• When we want to remove duplicate records from the result set in that case, we use
DISTINCT.
• If there are some duplicate data in the table. It removes duplicates and gives us the
unique records only.
• Unique data is identified based on combination of column list in the select
statement.

34
MS SQL SERVER FULL COURSE

SELECT Statement – TOP


• TOP clause will return the top number of rows in the result based on the top_value.
• SELECT TOP (1) * FROM TableName
• SELECT TOP 10 ColumnList FROM TableName
• SELECT TOP 7 ColumnList FROM TableName WHERE Condition

35
MS SQL SERVER FULL COURSE

SELECT Statement – ORDER BY


• The ORDER BY clause is used to sort the result set in some order.
• The default order is ascending.
• ASC keyword is used to sort the result set in ascending order.
• DESC keyword is used to sort the result set in descending order.

36
MS SQL SERVER FULL COURSE

SELECT Statement – GROUP BY


• The GROUP BY Clause is used to divide(group) similar types of records as a group and
then return.
• Generally, we use GROUP BY clause in the query when we use aggregate functions such
as count(), sum(), max(), min(), and avg() etc.
• When we implement group by clause first the data of the table will be divided into the
separate group as per the column.
• Then aggregate function will execute on each group data to get the result.
• Then final result will be returned.

37
MS SQL SERVER FULL COURSE

SELECT Statement – HAVING Clause


• HAVING Clause is an additional filter that is applied to the result set produced by
GROUP BY Clause.
• Logically, the HAVING Clause filters the rows from the intermediate result set that is
built by using the FROM, WHERE, or GROUP BY clauses in the SELECT statement.

38
MS SQL SERVER FULL COURSE

Difference Between HAVING and WHERE Clause


• WHERE clause cannot be used with aggregate functions whereas HAVING clause can be used
with aggregate functions.
• WHERE clause is used for filtering individual rows on a table whereas the HAVING clause is
used to filter groups.
• WHERE comes before GROUP BY. This means the WHERE clause filters rows before
aggregate calculations are performed.
• HAVING comes after GROUP BY. This means the HAVING clause filters groups after aggregate
calculations are performed.
• So, from a performance standpoint, HAVING is slower than WHERE and should be avoided
when possible.
• WHERE clause can be used with – Select, Insert, and Update statements whereas HAVING
clause can only be used with the Select statement.

39
MS SQL SERVER FULL COURSE

Variables and Data Types


• Variable is an object that can hold a single data value of a specific type.
• Local Variable
• A user declares the local variable.
• By default, a local variable starts with @.
• Every local variable scope has the restriction to the current batch or procedure within any given session.
• Global Variable
• The system maintains the global variable. A user cannot declare them.
• The global variable starts with @@
• It stores session related information.

• Data Types are the attribute that specifies what types of data can be entered by the user
such as integer, character, decimal, date time, etc.
• In SQL Server Database, each column of a table, all the local variables, and parameters
must have a data type.

40
MS SQL SERVER FULL COURSE

Types of Data Type


• Integer Data Types
• Decimal Data Types
• Money / Currency Data Types
• Date and Time Data Types
• Character Data Types
• Binary Data Types
• Special Data Types

41
MS SQL SERVER FULL COURSE

Operators
• An operator is a symbol that performs some specific operation on operands.
• These operators are classified as follows in SQL Server
• Assignment operator
• Arithmetic operator
• Comparison operator
• Logical operator

42
MS SQL SERVER FULL COURSE

Assignment Operator
• Equal to (=) sign is known as the assignment operator.
• It is the only assignment operator in MS SQL Server.
• SQL SERVER 2008 has introduced a new concept of Compound Assignment.

43
MS SQL SERVER FULL COURSE

Arithmetic Operators
• + (Addition Operator)
• – (Minus Operator)
• * (Multiplication Operator)
• / (Division Operator)
• % (Modulo Operator)

44
MS SQL SERVER FULL COURSE

Comparison Operators
• Equal (=) Operator
• Not Equal (!= or <>) Operator
• Greater Than (>) Operator
• Less Than (<) Operator
• Greater Than or Equal To (>=) Operator
• Less Than or Equal To (<=) Operator
• Not Greater Than (!<) Operator
• Not Less Than (!>) Operator

45
MS SQL SERVER FULL COURSE

Logical Operators
• AND – TRUE if both Boolean expressions are TRUE.
• OR – TRUE if either Boolean expression is TRUE.
• NOT – Reverses the value of any other Boolean operator.

46
MS SQL SERVER FULL COURSE

BETWEEN Operator
• BETWEEN operator is used to get the values within a range.
• Between Operator returns true if the operand is within a range.
• Between Operator will return records including the starting and ending values.
• This operator support only the AND operator.
• The BETWEEN Operator takes the values from small to big range in the query.
• If we use the NOT keyword along with the BETWEEN operator, then it will return data
where the column values not in between the range values.

47
MS SQL SERVER FULL COURSE

IN Operator
• We use IN operator in WHERE clause to compare column or variable values with a set of
multiple values.
• If we use the NOT keyword along with the IN operator, then it will return data where
column value not in the set of values

48
MS SQL SERVER FULL COURSE

LIKE Operator
• The LIKE operator in SQL Server is used to search for character string with the specified
pattern using wildcards in the column.
• Pattern means its specific string of characters with wildcards to search for matched
expressions.
• Wild Card Characters
• % symbol represents any no of characters in the expression.
• _ will represent a single character in the expression.
• [] symbol indicates a set of characters in the expression.
• [^] will represent any single character, not within the specified range

49
MS SQL SERVER FULL COURSE

LIKE Operator
• Employee Name contains 3 characters.
• SELECT * FROM TableName WHERE Name LIKE ‘___’
• Employee Name contains ‘A’ character.
• SELECT * FROM TableName WHERE Name LIKE’%A%’
• Employee Name starts with ‘P’ character and ends with ‘A’ character.
• SELECT * FROM TableName WHERE Name LIKE ‘P%A’
• Employee Name starts with J, H, K, U characters.
• SELECT * FROM TableName WHERE Name LIKE'[J, H, K, U]%’
• Employee Names start with A to Z characters.
• SELECT * FROM TableName WHERE Name LIKE'[A-Z]%’
• Employee Name not start with A to Z characters.
• SELECT * FROM TableName WHERE Name NOT LIKE'[A-Z]%’

50
MS SQL SERVER FULL COURSE

ALL Operator
• The ALL Operator is used to select all records of a Select statement.
• It compares a value to every value in a list of results from a query.
• The ALL must be preceded by the comparison operators and evaluates to TRUE if the
query returns no rows.
• ALL means the maximum value.
• Suppose ALL (1, 2, 3) means 3.
• With ALL we can use different comparison operators such as = , <> , != , > , >= , !> , < , <=
, !<.

51
MS SQL SERVER FULL COURSE

ANY Operator
• The ANY Operator is used to compare a value to each value in a list of results from a
query.
• It evaluate to true if the result of an inner query contains at least one row.
• ANY must match at least one row in the subquery and must be preceded by comparison
operators.
• With ANY we can use different comparison operators such as = , <> , != , > , >= , !> , < , <=
, !<.

52
MS SQL SERVER FULL COURSE

SOME Operator
• The SOME Operator is used to compare a value to each value in a list of results from a
query.
• It evaluate to true if the result of an inner query contains at least one row.
• SOME must match at least one row in the subquery and must be preceded by
comparison operators.
• With ANY we can use different comparison operators such as = , <> , != , > , >= , !> , < , <=
, !<.

53
MS SQL SERVER FULL COURSE

EXISTS Operator
• The EXISTS operator is used to check the existence of a result of a subquery or a
database object.
• The EXISTS operator tests whether a subquery fetches at least one-row or not.
• When no data is returned then this operator returns ‘FALSE’.
• EXISTS condition improves the query inefficiency as the sub-query may run multiple
times for a row in the outer query’s table.
• It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

54
MS SQL SERVER FULL COURSE

SET Operators
• The SET Operators are mainly used to combine the result of more than 1 select
statements and return a single result set to the user.
• There are the following 4 set operators
• UNION: Combine two or more result sets into a single set, without duplicates.
• UNION ALL: Combine two or more result sets into a single set, including all duplicates.
• INTERSECT: Takes the data from both result sets which are in common.
• EXCEPT: Takes the data from the first result set, but not in the second result set (i.e., no
matching to each other)

55
MS SQL SERVER FULL COURSE

UNION and UNION ALL Operators


• The UNION and UNION ALL operators are used to combine the result-set of two or
more SELECT statements into a single result set.
• UNION removes duplicate rows whereas UNION ALL does not remove the duplicate
rows.
• For UNION and UNION ALL to work, the Number, Data types, and the order of the
columns in the select statements should be the same. If you want to sort, the
results of UNION or UNION ALL, the ORDER BY clause should be used on the last
SELECT statement.

56
MS SQL SERVER FULL COURSE

Difference between UNION and JOIN


• JOINS and UNIONS are two different things.
• UNION combines the result-set of two or more select queries into a single result-set
which includes all the rows from all the queries in the union, whereas JOINS, retrieves
data from two or more tables based on logical relationships between the tables.
• In short, UNION combines rows from 2 or more tables, where JOINS combines columns
from 2 or more tables.

57
MS SQL SERVER FULL COURSE

EXCEPT Operator
• The EXCEPT operator is used to return unique rows from the left query which isn’t
present in the right query’s results.

58
MS SQL SERVER FULL COURSE

Difference between EXCEPT and NOT IN Operator


• The EXCEPT operator filters duplicate rows and return only DISTINCT rows from the
left query that aren’t in the right query’s results.
• NOT IN does not filter the duplicates rows.
• The EXCEPT operator expects the same number of columns in both the queries.
• NOT IN, compares a single column from the outer query with a single column from the
subquery.

59
MS SQL SERVER FULL COURSE

INTERSECT Operator
• The INTERSECT operator in SQL Server is used to retrieve the common records of both
the left and the right query of the Intersect operator.
• The same result can be achieved using inner join.
• The INTERSECT Operator filters duplicate rows and return only the DISTINCT rows that
are common between the LEFT and Right Query.
• NNER JOIN does not filter the duplicates.
• We can make the INNER JOIN behave like INTERSECT operator by using the DISTINCT
operator.

60
MS SQL SERVER FULL COURSE

Joins
• Joins are used to retrieve the data from two or more related tables.
• In general, tables are related to each other using the primary key and foreign key
relationship, but it is not mandatory.
• The tables involved in the joins must have a common field and based on that common
field the joins retrieves the records.
• Type of Joins
• Inner Join
• Left Outer Join (Left Join)
• Right Outer Join (Right Join)
• Full Outer Join (Full Join)
• Self Join
• Cross Join

61
MS SQL SERVER FULL COURSE

Joins – Inner Join


• The Inner Join returns only the matching rows from both the tables involved in the join
by removing the non-matching rows.

62
MS SQL SERVER FULL COURSE

Joins – Left Outer Join


• The Left Outer Join retrieves all the records from Left table and only matching records
from Right table.
• For un-matching records in right table, data will take the null value.

OUTER Keyword is optional here.

63
MS SQL SERVER FULL COURSE

Joins – Right Outer Join


• The Right Outer Join retrieves all the records from Right table and only matching
records from Left table.
• For un-matching records in left table, data will take the null value.

OUTER Keyword is optional here.

64
MS SQL SERVER FULL COURSE

Joins – Full Outer Join


• Full Outer Join retrieves all the matching records as well as all the non-matching
records from both the tables.
• For un-matching records in left table, data will take the null value.

OUTER Keyword is optional here.

65
MS SQL SERVER FULL COURSE

Joins – Self Join


• The Self Join is nothing but a concept where we join a table by itself.
• We use Self Join when we have some relations between the columns of the same table.
• While implementing the self-join mechanism, we need to create the alias for the table.
• The Self Join is not a different type of join.
• It can be classified as any type of join, such as
• Inner Join
• Outer (Left, Right, Full) join
• Cross Join

66
MS SQL SERVER FULL COURSE

Joins – Cross Join


• When we combine two or more tables with each other without any condition (where or
on) then we call this type of joins Cartesian or cross join.
• In Cross Join, each record of a table is joined with each record of the other table
involved in the join.
• In SQL Server, the Cross Join should not have either ON or where clause.
• The Cross Join produces the Cartesian product of the tables involved in the join.

67
MS SQL SERVER FULL COURSE

OVER Clause
• OVER clause is used with PARTITION BY to break up the data into partitions.
• This is useful when we want see the row level data along with grouped data.

68
MS SQL SERVER FULL COURSE

Row_Number Function
• ROW_NUMBER() function is basically used when you want to return a sequential
number starting from 1 and then increases by 1 for the next row onwards.
• It is a built-in function in SQL Server that assigns a sequential integer number to each
row within a partition of a result set.
• PARTITION BY Clause is Optional. ORDER BY Clause is required.

69
MS SQL SERVER FULL COURSE

Indexes – What is an Index?


• Index is a database object which is used to improve the performance of search
operations in database.
• When we create an index on any column of a table, then SQL Server internally maintains
a separate table called the index table.
• When we are trying to retrieve the data from the existing table, depending on the index
table, SQL Server directly goes to the table and retrieves the data very quickly.
• A table can have a maximum of 1000 indexes.
• 1 Clustered Index.
• 999 Non-Clustered Index.

70
MS SQL SERVER FULL COURSE

Indexes – When SQL Server uses Indexes?


• The SQL Server uses indexes of a table if the Select or Update or Delete statement
contains the “WHERE” clause and the where condition column must be an indexed
column.
• If the select statement contains an “ORDER BY” clause, then also the indexes can be
used.

71
Indexes – Goal of Indexes?

• The goal of the index is to make the search


operation faster. To do so it uses something called a
B-Tree (Balanced Tree) structure internally.
• What is Balanced Tree (B-Tree) Structure?
• B-Tree structure is data structure that divides
data into three sections i.e., Root Node, Non-Leaf
Nodes, and Leaf Nodes.

MS S Q L S ER V ER FU LL COU R S E 72
MS SQL SERVER FULL COURSE

Indexes – What is Table Scan?


• When SQL Server Search Engine searches for the required information sequentially one
by one from the start to the last record of the table then it know as Table Scan.
• If the table has more rows, then it will take more time for searching the required data,
so it is a time and resource consuming process.

73
MS SQL SERVER FULL COURSE

Indexes – What is Index Scan/Seek?


• When SQL Server Search Engine uses a B-Tree structure to search the required data
which drastically improves the performance of your search query by reducing the
number of scans is known as Index Scan/Seek.

74
MS SQL SERVER FULL COURSE

Indexes – Syntax to Create Index

75
MS S Q L S ER V ER FU LL COU R S E

Indexes – Clustered Index


• Clustered Index defines the order in which the data is
physically stored in a table.
• As the leaf nodes store the actual data, a table can have
only one clustered index.
• The Clustered Index by default gets created with the
primary.
• When a table has a clustered index then the table is called
a clustered table.
• If a table has no clustered index, its data rows are stored
in an unordered structure.
• When we create a clustered index with multiple columns,
then it is called a composite clustered index.

76
MS SQL SERVER FULL COURSE

Indexes – Non-Clustered Index


• Non-Clustered Index defines the logical order/arrangement of data in a table.
• In the Non-Clustered Index, the arrangement of data in the index table will be different
from the arrangement of data in the actual table.
• The data is stored in one place and the index table is stored in another place.
• The index table will have pointers to the storage location of the actual data.
• Case 1: If your table does not have a clustered index
• Then the Row Identifier (RID) of the non-clustered index points to the heap table. A heap table
is nothing but a table without indexes. In the heap table, it will search the record row by row
until it finds the data.
• Case 2: If your table has a clustered index
• Then the Row Identifier (RID) of the non-clustered index will point to the clustered index key
and that indexed key is used to search the data.

77
MS SQL SERVER FULL COURSE

Indexes – Clustered vs Non-Clustered Index


• We can create only one clustered index per table whereas we can create more than
one(up to 999) non-clustered index per table in SQL Server.
• In the clustered index, the leaf node holds the data and in the case of a non-clustered
index, the leaf node points to the leaf node of a clustered index or points to the heap
table if the table does not have any clustered index.
• Clustered Index determines the order in which the data is physically stored in a table
and hence does not require additional disk space whereas a Non-Clustered Index is
stored separately from the actual table, so additional disk space is required.

78
MS SQL SERVER FULL COURSE

Indexes – When should we create indexes on a table?


• We should create indexes on table columns when those columns are frequently used in
where clause conditions or order by clause in a select query.
• It is not advised to create an index on each column because several indexes can degrade
the performance of the database also.
• This is because every modification we make to the data should be reflected in all the
index tables.

79
MS SQL SERVER FULL COURSE

Indexes – Which index is faster?


• Clustered Index is slightly faster than the Non-Clustered Index in SQL Server.
• In the case of the clustered index, the leaf node holds the actual data, and hence when
we search for any data, it directly gets the data from the leaf node.
• In the case of a Non-Clustered Index, the leaf node points to the leaf node of clustered
index or to the heap table and hence there is an extra look-up from the Non-Clustered
Index to the actual table (leaf node of a clustered index or heap table) to fetch the actual
data.

80
MS SQL SERVER FULL COURSE

Temporary Tables
• A temporary table exists only temporarily on the database server for a fixed amount of
time, a temporary table generally maintains a subset of data from a normal table.
• Temporary tables generally know as temp tables.
• Temporary tables are kept in the tempDB database.
• They function similarly to the conventional tables in which you can select, insert, and
delete data as per your requirements.
• Type of Temp Tables
• Local Temp Tables
• Only accessible to the session that created in.
• They are identified by the prefix # (e.g., #myTempTable)
• Global Temp Tables
• Accessible to all sessions and users simultaneously.
• They are identified by the prefix ## (e.g., ##myTempTable)
81
MS SQL SERVER FULL COURSE

Checking for Temporary Tables

82
MS SQL SERVER FULL COURSE

Stored Procedures – Need of Stored Procedure?


First Time Query Executed
Execution
Syntaxes Query Result
Plan is
are checked Executed Returned
selected

Next Time Query Executed

Execution
Syntaxes Query Result
Plan is
are checked
Syntax Check and Execution Pan Executed Returned
selected
are Cached

83
Stored Procedures –

MS SQL SERVER FULL COURSE


Definition

• A Stored Procedure is a database object


which contains pre-compiled queries (a
group of T-SQL Statements).
• We can also say that the Stored
Procedures are a block of code designed
and created to perform certain task
whenever called.

84
MS SQL SERVER FULL COURSE

Stored Procedures – Changing Name and Body


• We use ALTER keyword to change the body of a stored procedure.
• To change the name of stored procedure we use sp_rename.
• sp_rename is a system defined stored procedure.

85
MS SQL SERVER FULL COURSE

Stored Procedures – Delete (DROP) a Stored Procedure.


• We use DROP PROCEDURE keyword to drop (delete) a stored procedure.

86
MS SQL SERVER FULL COURSE

Stored Procedures – Type of Parameters in a SP


• We can have two types of parameters in a stored procedure.
• Input Parameters
• Output Parameters
• Stored Procedure created with any type of parameters are known as Stored Procedures
with parameters.
• The number of parameters are dependent on our business need.

87
MS SQL SERVER FULL COURSE

Stored Procedures – Understanding Input Parameters


• If the parameters are given in the EXEC
Statement, then these parameters are known
as input parameters.
• The input parameters are used to send data
into the stored procedure while execution.

88
Stored Procedures –

MS SQL SERVER FULL COURSE


Understanding
Output Parameters
• If the parameters in SQL Server can be
declared either by using OUT or OUTPUT
keyword.
• The output parameters are used to carrying
data out of the stored procedure after the
execution.
• If we don’t specify OUT/OUTPUT keyword
while executing the stored procedure, then
@result will be null.

89
MS SQL SERVER FULL COURSE

Stored Procedures – Default values to Parameters


• Default values are the values that will be used in processing when no value is supplied to the
parameters.
• If you don't provide a default value and you miss to supply the value to the parameter, then you will
get and error - SQL Server stored procedure expects parameter which was not supplied.
• We can specify some default values to parameters as shown below

90
MS SQL SERVER FULL COURSE

Views – What is a view in SQL Server?


• Views are just complied SQL Query.
• They are popularly known as Virtual Table as by default, they do not store any data physically.
• So, when we query a view, it gets the data from the underlying database tables.

View Tables

91
MS SQL SERVER FULL COURSE

Views – Difference between a table and a view


• A table is physical whereas a view is logical or virtual.
• A table is an independent object whereas a view is a dependent object.
• A view depends on a table or multiple tables from which it loads the data.
• When a new table is created from an existing table the new and old tables are independent
themselves that is the changes of one table will not be reflected into the other table.
• When a view is created based on a table, any changes that are performed on the table reflects into
the view and any changes performed on the view reflected in the table.

92
MS SQL SERVER FULL COURSE

Views – Types of Views


• There are two types of views
• Simple Views
• The views created based on a single table is known as Simple Views.
• Simple Views supports all the DML operations like a table.
• These are also known as updatable views.
• Complex Views
• The views created based on multiple tables are known as Complex Views.
• Complex View may or may not support the DML operations.
• Complex View may not update the data correctly in underlying tables, if we do update on Complex Views.
• These are also known as non-updatable or static views.

93
MS SQL SERVER FULL COURSE

Views – Common Questions


• Can we drop a table that has dependent views on it?
• Yes, we can drop but the views associated with that table will not be dropped.
• They will still be in the database. There status will be changed as inactive objects.
• Those views will become active once the table is recreated.
• Can we create a view based on another view?
• Yes, we can.
• Can we update the views in MS SQL Server?
• Yes, we can but while updating the views based on multiple table may not update the base tables correctly.

94
MS SQL SERVER FULL COURSE

Triggers – What are triggers ?


• Triggers are grouped SQL Statements/logics like stored procedures that can be executed
automatically.
• They can be executed before or after the Insert, Update or Delete in a table.
• In simple words, we can say that, if you want to execute some processing logic before or after the
Insert, Update, or Delete in a table then we need to use Triggers in SQL Server.
• Type of Triggers
• DML Triggers
• DDL Triggers
• CLR Triggers
• Logon Triggers

95
MS SQL SERVER FULL COURSE

Triggers – DML Triggers


• DML stands for Data Manipulation Language, and it provides Insert, Update and Delete statements
to perform the respective operation on database table/view.
• The triggers which are executed automatically in response to DML events (Insert, Update, and
Delete statements) are called DML Triggers.
• Type of DML Triggers
• After Triggers
• Fires after the triggering action, means once the DML statement (Insert, Update, and Delete) completes its execution, this
trigger is going to be fired.
• Instead of Triggers
• Going to be executed instead of the corresponding DML operations, means instead of the DML operations (Insert, Update,
and Delete) the Instead Of Triggers are going to be executed.

96
MS SQL SERVER FULL COURSE

Triggers – DML Triggers Syntax


• CREATE/ALTER – Specify if you are creating a new trigger or modifying an existing trigger.
• ON TableName/ViewName – Specifies the target table/view for trigger.
• For/After – Specifies that the trigger fires only after the SQL statements are executed.
• InsteadOf – Specifies that the trigger is executed on behalf of the triggering SQL statement.
• INSERT, UPDATE, DELETE – Specify which SQL statement will fire the trigger.

97
MS SQL SERVER FULL COURSE

Triggers – Need of DML Triggers


• DML Triggers are used to enforce business rules and data integrity.
• Triggers are very much like constraints in the way they enforce integrity.
• So, with the help of DML Triggers, we can enforce data integrity which cannot be done with the
help of constraints that is comparing values with values of another table, etc.

98
MS SQL SERVER FULL COURSE

Triggers – Inserted and Deleted Tables


• Inserted and Deleted tables are temporary tables that are created by SQL Server in the context of
a trigger.
• These tables can only be available as part of a trigger.
• If you try to access these tables outside of a trigger, then you will get an error.
• The table structure of both inserted and deleted tables will be the same as the table structure of
the table on which the trigger is created.
• Whenever we fire any INSERT, UPDATE, and DELETE statement on a table, all the new records are
going to the inserted table i.e., all the updated and new records are present in the inserted table.
• On the other hand, all the old values are present in the deleted table.
• For INSERT, data is available in INSERTED Table.
• For DELETE, data is available in DELETED Table
• For UPDATE, new data is available in INSERTED Table and old data is available in DELETED Table.

99
MS SQL SERVER FULL COURSE

Transaction Management – What is a Transaction?


• A transaction is a set of SQL statements that should be executed as one unit.
• That means a transaction ensures that either all the command succeeds or none of them.
• If one of the commands in the transaction fails, all the commands fail and any data that is modified
in the database is rolled back.
• Example – Money Transfer from one bank account to other bank account.

100
MS SQL SERVER FULL COURSE

Transaction Management
• The process of combining a set of related operations into a single unit and executing those
operations by applying to execute whole or execute none principle is called transaction
management.
• When we need to execute operations by applying execute whole or execute none principle then
every transaction has two boundaries – Beginning and Ending.

101
MS SQL SERVER FULL COURSE

Transaction Management – Process


• Begin the Transaction
• Process SQL Commands
• Check for Errors
• If error occurs – Rollback the Transaction
• Else – Commit the Transaction

102
MS SQL SERVER FULL COURSE

Transaction Management – Process


• Begin Transaction – It indicates that the transaction is started.
• Commit Transaction – It indicates that the transaction was completed successfully, required DML
operations was completed successfully, and the resources held by the transaction is released.
• Rollback Transaction – It indicates that the transaction was failed and will roll back the database
to its previous state.
• Save Transaction – This is used for dividing or breaking a transaction into multiple units so that
the user has a chance of roll backing a transaction up to a point or location.

• NOTE – Transactional Control Language commands are only used with the DML statements
such as INSERT, UPDATE, and DELETE only. They cannot be used with DDL statements while
creating tables or dropping them because these operations are automatically committed to
the database.

103
MS SQL SERVER FULL COURSE

Transaction Management?
• Why do we need Transaction Management?
• Share you answers in comment box.

• What is the main goal of Transaction Management?


• Share you answers in comment box.

104
MS SQL SERVER FULL COURSE

Transaction Management – ACID Properties


• Atomicity
• Ensures that either all the DML Statements inside a transaction are completed successfully or all of them are
rolled back.
• Consistency
• Ensures that the database data is in a consistent state before the transaction started and left the data in a
consistent state after the transaction is completed. If the transaction violates the rules, then it should be
rolled back.
• Isolation
• Ensures that the intermediate state of a transaction is invisible to other transactions. The Data modifications
made by one transaction must be isolated from the data modifications made by all other transactions. Most
databases use locking to maintain transaction isolation.
• Durability
• Ensures that once the transaction is successfully completed, then the changes it made to the database will be permanent.
Even if there is a system failure or power failure or any abnormal changes, it should safeguard the committed data.

105
MS SQL SERVER FULL COURSE

Exception Handling
• An error condition during program execution is called an exception.
• The mechanism to resolve such an exception is known as exception handling.

• Example – Divide Two Numbers (a/b) where b is 0.

106
MS SQL SERVER FULL COURSE

Exception Handling – What happens when exception occurs?


• In SQL Server, whenever an exception occurred, it displays the exception message and then
continues the program execution. The execution will not stop even when the error statements are
related with the error.
• Ideally, it should not be happening. It should not execute the statements related to error.

107
MS SQL SERVER FULL COURSE

Exception Handling – Handling Exceptions


• Handling an error in SQL Server means stopping the execution of the statements which are related
to the error.
• We can use try-catch block which was introduced in SQL Server 2005.
• We can also use RAISERROR and @@ERROR to handle exceptions /errors.
• RAISERROR
• It is a system defined function. RAISERROR(‘ErrorMessage’, ‘ErrorSeverity’, ErrorState)
• Error Message – Custom Error Message.
• Error Severity – Type off error. Error Severity Level 16 indicate a general error that can be corrected by
user.
• Error State – It is a number between 1 and 255. RAISERROR function can only generate custom error is we
set Error State value between 1 and 127.
• @@ERROR
• It is a system defined function.
• If there is an error, it returns a NON-ZERO value
• If there us no error, it returns ZERO.

108
MS SQL SERVER FULL COURSE

Exception Handling – Predefined Terms


• Error Number
• The Error number is a unique identifier given for each error. It will be below 50,000 for predefined errors
and above or equals to 50,000 for errors defined by the user.
• While raising custom errors, if we don’t specify the error number, then the default will be 50000.
• Error Message
• Description of the error that occurred. Max characters limit 2047.
• Severity Level
• Tells about the importance of the error which can be ranging between 0 to 24.
• 0 to 9 – Not serves which can be considered as information or status messages.
• 11 to 16 – Indicates these errors can be corrected by the user.
• 17 to 19 – Indicates software errors. Cannot be corrected by user. Must be reported to system admin.
• 20 to 24 – Indicates fatal errors and if these errors occur, they can damage the system or database.
• Error State
• It is an arbitrary value that is not that important can be ranging between 0 to 127.
• We use this whenever the same error must occur in multiple places.

109
MS SQL SERVER FULL COURSE

Exception Handling – Raising Errors Explicitly


• RAISERROR
• THROW (new feature to SQL Server 2012)
• RAISERROR vs THROW
• Both statements is used for raising a custom error with or without try and catch blocks.
• The RAISERROR statement after raising the error will continue the execution of the program whereas the
throw statement will terminate the program abnormally on that line.
• They behave the same in try block and will jump directly to catch block from the line of error got raised.
• The RAISERROR has an option for ERROR SEVERITY Level whereas THROW doesn’t. All error messages will
have a default ERROR SEVERITY level as 16 in case of THROW.
• With RAISERROR, there is a chance of recording error message into the server log file by using the with log
option whereas we cannot do this in case of a THROW statement.

110
MS SQL SERVER FULL COURSE

Exception Handling – TRY – CATCH Block


• NOTE – Errors captured by CATCH block will not be returned to the calling application.
• If you want to return the error information to the calling application, then you need to use the RAISERROR()
function explicitly with the catch block.

111
112

THANK YOU

You might also like