SQL Server Full Course
SQL Server Full Course
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
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
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
11
MS SQL SERVER FULL COURSE
12
MS SQL SERVER FULL COURSE
13
MS SQL SERVER FULL COURSE
14
MS SQL SERVER FULL COURSE
15
MS SQL SERVER FULL COURSE
16
MS SQL SERVER FULL COURSE
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
19
MS SQL SERVER FULL COURSE
20
MS SQL SERVER FULL COURSE
21
MS SQL SERVER FULL COURSE
22
MS SQL SERVER FULL COURSE
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
29
MS SQL SERVER FULL COURSE
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
32
MS SQL SERVER FULL COURSE
33
MS SQL SERVER FULL COURSE
34
MS SQL SERVER FULL COURSE
35
MS SQL SERVER FULL COURSE
36
MS SQL SERVER FULL COURSE
37
MS SQL SERVER FULL COURSE
38
MS SQL SERVER FULL COURSE
39
MS SQL SERVER FULL COURSE
• 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
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
56
MS SQL SERVER FULL COURSE
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
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
62
MS SQL SERVER FULL COURSE
63
MS SQL SERVER FULL COURSE
64
MS SQL SERVER FULL COURSE
65
MS SQL SERVER FULL COURSE
66
MS SQL SERVER FULL COURSE
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
70
MS SQL SERVER FULL COURSE
71
Indexes – Goal of Indexes?
MS S Q L S ER V ER FU LL COU R S E 72
MS SQL SERVER FULL COURSE
73
MS SQL SERVER FULL COURSE
74
MS SQL SERVER FULL COURSE
75
MS S Q L S ER V ER FU LL COU R S E
76
MS SQL SERVER FULL COURSE
77
MS SQL SERVER FULL COURSE
78
MS SQL SERVER FULL COURSE
79
MS SQL SERVER FULL COURSE
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
82
MS SQL SERVER FULL COURSE
Execution
Syntaxes Query Result
Plan is
are checked
Syntax Check and Execution Pan Executed Returned
selected
are Cached
83
Stored Procedures –
84
MS SQL SERVER FULL COURSE
85
MS SQL SERVER FULL COURSE
86
MS SQL SERVER FULL COURSE
87
MS SQL SERVER FULL COURSE
88
Stored Procedures –
89
MS SQL SERVER FULL COURSE
90
MS SQL SERVER FULL COURSE
View Tables
91
MS SQL SERVER FULL COURSE
92
MS SQL SERVER FULL COURSE
93
MS SQL SERVER FULL COURSE
94
MS SQL SERVER FULL COURSE
95
MS SQL SERVER FULL COURSE
96
MS SQL SERVER FULL COURSE
97
MS SQL SERVER FULL COURSE
98
MS SQL SERVER FULL COURSE
99
MS SQL SERVER FULL COURSE
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
102
MS SQL SERVER FULL COURSE
• 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.
104
MS SQL SERVER FULL COURSE
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.
106
MS SQL SERVER FULL COURSE
107
MS SQL SERVER FULL COURSE
108
MS SQL SERVER FULL COURSE
109
MS SQL SERVER FULL COURSE
110
MS SQL SERVER FULL COURSE
111
112
THANK YOU