Basics of SQL Server
Basics of SQL Server
Ishika Tiwari
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. Although the author/co-author and publisher have made every effort to ensure
that the information in this book was correct at press time, the author/co-author and publisher do
not assume and hereby disclaim any liability to any party for any loss, damage, or disruption
caused by errors or omissions, whether such errors or omissions result from negligence,
accident, or any other cause. The resources in this book are provided for informational purposes
only and should not be used to replace the specialized training and professional judgment of a
health care or mental health care professional. Neither the author/co-author nor the publisher
can be held responsible for the use of the information provided within this book. Please always
consult a trained professional before making any decision regarding the treatment of yourself or
others.
https://www.c-sharpcorner.com/ebooks/ 2
Table of Contents:
Introduction to SQL Server ............................................................................................................ 4
SQL Server Management Studio (SSMS) ......................................................................................... 6
Basics of SQL Server .....................................................................................................................11
Creating and Managing Databases ................................................................................................14
Tables and Relationships..............................................................................................................17
Data Manipulation ......................................................................................................................21
Advanced SQL Queries .................................................................................................................23
Stored Procedures and Functions..................................................................................................33
Database backup With Table and Data ..........................................................................................40
https://www.c-sharpcorner.com/ebooks/ 3
1
Introduction to SQL Server
Overview
https://www.c-sharpcorner.com/ebooks/ 4
What is SQL Server?
Microsoft created SQL Server, a relational database management system (RDBMS). It is
intended to store and retrieve information that other software programs, whether they operate on
the same computer or on a different machine connected to a network, request. Because of its
great scalability and support for a wide range of data operations,
SQL Server is appropriate for applications ranging from small to corporate.
• SQL Server 2000: Paved the way for smoother interaction with web-based applications
by introducing support for XML and HTTP.
• SQL Server 2005: Marked the introduction of SQL Server Management Studio (SSMS),
dynamic management views, and enhanced XML capabilities.
• SQL Server 2008: Ushered in advancements like policy-based management, novel data
types, and improved performance.
• SQL Server 2012: Introduced AlwaysOn Availability Groups, streamlined integration
services, and fortified security features.
• SQL Server 2016: Broadened its reach by offering support for Linux, introduced real-
time operational analytics, and incorporated new security features like Always Encrypted.
• SQL Server 2019: Added functionalities like big data clusters, data virtualization, and
further advancements in intelligent query processing.
• SQL Server 2022 (latest version): Introduced features focused on enhanced
performance, security, and manageability. Some of these include Accelerated Database
Recovery, Online Index Rebuild, and Confidential Ledger.
Key Features
• High Availability: Always On Availability Groups and other similar solutions make sure
databases are highly available.
• Security: Sensitive data is protected by advanced security features like row-level
security, always encrypted, and transparent data encryption.
• Performance: Database performance can be enhanced with the use of tools such as the
Query Store and performance tuning advisers.
• Scalability: SQL Server has the capacity to process massive volumes of data and
thousands of concurrent users.
• Integration: SQL Server Reporting Services (SSRS) offers strong reporting capabilities,
while SQL Server Integration Services (SSIS) enables reliable ETL procedures.
• Cloud Support: SQL Server can be used in hybrid cloud settings because of its smooth
integration with cloud services such as Microsoft Azure.
https://www.c-sharpcorner.com/ebooks/ 5
2
SQL Server Management
Studio (SSMS)
Overview
https://www.c-sharpcorner.com/ebooks/ 6
Introduction to SSMS
For administering SQL infrastructure, SQL Server Management Studio (SSMS) offers a potent
integrated environment. It offers a suite of tools for configuring, monitoring, and managing SQL
Server and database instances in addition to an easy graphical user interface. With its tools for
query execution, database architecture, and performance tuning, SSMS is a must for database
developers, administrators, and analysts.
using System.Data.SqlClient;
using System;
class Program
{
static void Main()
{
https://www.c-sharpcorner.com/ebooks/ 7
string connectionString =
"Server=myServerAddress;Database=myDataBase;User
Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new
SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("Connected to SQL Server");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
• Once connected, you can test the connection by running queries or performing database
operations.
Connecting to SQL Server is a crucial step in managing databases and performing data
operations. Make sure to handle connection strings and credentials securely to prevent
unauthorized access.
Object Explorer
Location: On the left side of the SSMS window.
Purpose: Provides a hierarchical view of your SQL Server instances and databases. It is the
primary navigation tool for managing server objects.
https://www.c-sharpcorner.com/ebooks/ 8
Key Functions:
Query Editor
Location: The central area of the SSMS window, opens when you start a new query.
Key Features: Syntax Highlighting: Differentiates SQL keywords, functions, and variables with
colours for easier reading.
Example Usage:
Properties Window
Location: Typically found at the bottom right of the SSMS window.
Purpose: Displays detailed properties of the selected object in Object Explorer. Allows you to
view and edit object properties.
Example Usage:
Solution Explorer
Location: Can be opened from the "View" menu.
Purpose: Helps you manage SQL Server projects and organize scripts and other files into
solutions.
https://www.c-sharpcorner.com/ebooks/ 9
Example Usage:
Registered Servers
Location: Can be accessed from the "View" menu.
Purpose: Allows you to register and manage multiple SQL Server instances. Useful for
administrators managing multiple servers.
Example Usage:
• Register a new server by right-clicking on "Local Server Groups" and selecting "New
Server Registration".
• Switch between different registered servers for management tasks.
Template Explorer
Location: Can be accessed from the "View" menu or by pressing Ctrl+Alt+T.
Purpose: Provides a collection of predefined SQL templates for common tasks. These
templates can be customized and used as starting points for your SQL scripts.
Example Usage:
https://www.c-sharpcorner.com/ebooks/ 10
3
Basics of SQL Server
Overview
In this chapter, we explore SQL Server data types and basic SQL
commands, providing a comprehensive guide to defining and
manipulating data within your database. Prepare yourself for an in-
depth understanding of how to categorize and manage data efficiently,
as well as how to perform essential database operations using SQL
commands.
https://www.c-sharpcorner.com/ebooks/ 11
Data Types
In SQL Server, data types are essential for defining the kind of data that can be stored in each
column of a table. Here's an overview of all the data types available in SQL Server:
https://www.c-sharpcorner.com/ebooks/ 12
• VARBINARY(n): Variable-length binary data with a maximum length of n bytes.
• IMAGE: Variable-length binary data for large binary objects (deprecated, use
VARBINARY(MAX)).
SQL Server supports standard SQL commands along with some proprietary extensions. Here
are some basic SQL commands in SQL Server:
https://www.c-sharpcorner.com/ebooks/ 13
4
Creating and Managing
Databases
Overview
https://www.c-sharpcorner.com/ebooks/ 14
In this chapter, we'll delve into the fundamental concepts of creating and managing databases in
SQL Server, catering specifically to beginners. Whether you're new to SQL Server or database
management in general, this chapter will provide you with a solid foundation to start working with
databases effectively.
Understanding Databases
Let's begin by understanding what databases are and why they are crucial in the world of
information technology. Simply put, a database is a structured collection of data that is
organized and stored for easy access, retrieval, and management. Think of it as a digital filing
cabinet where you can store and organize your data in a systematic manner.
https://www.c-sharpcorner.com/ebooks/ 15
Monitoring and Maintenance
Regular monitoring and maintenance are vital for ensuring the health and performance of your
database. SQL Server offers built-in tools for monitoring database activity, checking database
integrity, and optimizing performance through index maintenance and query tuning.
Database Security
Database security is a critical aspect of database management. You can control access to your
database by managing permissions, roles, and users. Additionally, you can implement
encryption to protect sensitive data and audit database activities for compliance purposes.
https://www.c-sharpcorner.com/ebooks/ 16
5
Tables and Relationships
Overview
https://www.c-sharpcorner.com/ebooks/ 17
Creating Tables
In SQL Server, you use the CREATE TABLE statement to create a new table. Here's a basic
example:
This creates a table named Users with columns UserID, UserName, and Email. UserID is
defined as the primary key.
Primary Key
• Definition: A primary key uniquely identifies each record in a table. It must contain
unique values and cannot contain NULL values.
• Syntax: Defined when creating a table using the PRIMARY KEY constraint.
CREATE TABLE Users (
UserID INT PRIMARY KEY,
UserName NVARCHAR(50) NOT NULL,
Email NVARCHAR(100)
);
Foreign Key
• Definition: A foreign key establishes a link between two tables. It ensures referential
integrity by enforcing a link between a column in one table and a primary or unique key
in another table.
• Syntax: Defined using the FOREIGN KEY constraint.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
UserID INT,
FOREIGN KEY (UserID) REFERENCES Users(UserID)
);
In this example, UserID in the Orders table references the UserID column in the Users table.
Unique Key
• Definition: A unique key ensures that all values in a column or a set of columns are
unique (no duplicates), like a primary key but does allow NULL values (in SQL Server, a
unique constraint allows one NULL value).
• Syntax: Defined using the UNIQUE constraint.
https://www.c-sharpcorner.com/ebooks/ 18
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName NVARCHAR(50) NOT NULL,
SKU NVARCHAR(20) UNIQUE
);
Composite Key
• Definition: A composite key consists of multiple columns that together uniquely identify a
record in a table.
• Syntax: Defined by including multiple columns in the PRIMARY KEY constraint.
CREATE TABLE OrderDetails (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID),
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID),
FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
);
In this example, (OrderID, ProductID) form a composite primary key in the OrderDetails table.
Alternate Key
• Definition: An alternate key is a column or set of columns that can also uniquely identify
a record in a table, similar to a candidate key.
• Example: If a table has both a primary key and another unique key, the unique key is an
alternate key.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Email NVARCHAR(100) UNIQUE,
Phone NVARCHAR(20) UNIQUE
);
In this example, both Email and Phone can serve as alternate keys for the Customers table.
Surrogate Key
• Definition: A surrogate key is a unique identifier generated by the database system,
often an auto-incremented integer, to uniquely identify each row in a table.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY IDENTITY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
...
);
https://www.c-sharpcorner.com/ebooks/ 19
These key types play crucial roles in defining relationships, ensuring data integrity, and
optimizing database performance in SQL Server.
Normalization
Normalization in SQL Server involves structuring database tables to minimize redundancy and
dependency, enhancing data integrity and query performance. This process typically includes
organizing data into separate tables and establishing relationships using primary keys, foreign
keys, and normalization forms such as 1NF, 2NF, and 3NF. By eliminating duplicate data and
ensuring each table stores information relevant to a single entity, normalization optimizes
storage efficiency and reduces the risk of anomalies during data modification and retrieval
operations.
https://www.c-sharpcorner.com/ebooks/ 20
6
Data Manipulation
Overview
https://www.c-sharpcorner.com/ebooks/ 21
Data Manipulation covers essential operations such as inserting, updating, deleting, and
selecting data. Here’s a brief explanation of each using SQL Server syntax:
Inserting Data
To insert data into a table, use the INSERT INTO statement:
Example:
INSERT INTO Users (UserName, Email)
VALUES ('JohnDoe', 'johndoe@example.com');
Updating Data
To update existing data in a table, use the UPDATE statement:
UPDATE TableName
SET Column1 = Value1, Column2 = Value2, ...
WHERE Condition;
Example:
UPDATE Users
SET Email = 'newemail@example.com'
WHERE UserID = 1;
Deleting Data
To delete data from a table, use the DELETE FROM statement:
Example:
DELETE FROM Users
WHERE UserID = 1;
Selecting Data
To retrieve data from a table, use the SELECT statement:
Example:
SELECT * FROM Users;
These operations are fundamental for manipulating data in SQL Server, allowing you to add,
modify, remove, and retrieve records efficiently based on specified conditions.
https://www.c-sharpcorner.com/ebooks/ 22
7
Advanced SQL Queries
Overview
https://www.c-sharpcorner.com/ebooks/ 23
Joins
Joins in SQL Server are used to retrieve data from two or more tables based on a related
column between them. Here are the main types of joins, along with examples for each:
INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
Customers Table:
CustomerID CustomerName
1 John Doe
2 Jane Smith
3 Sam Johnson
Orders Table:
Query:
Result:
Query:
https://www.c-sharpcorner.com/ebooks/ 24
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Result:
Result:
Result:
https://www.c-sharpcorner.com/ebooks/ 25
CustomerID CustomerName OrderID OrderDate
3 Sam Johnson NULL NULL
NULL NULL 104 2023-01-04
CROSS JOIN
The CROSS-JOIN keyword returns the Cartesian product of the two tables. This means that it
returns all possible combinations of rows from both tables.
Query:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders;
Result:
CustomerName OrderID
John Doe 101
John Doe 102
John Doe 103
Jane Smith 101
Jane Smith 102
Jane Smith 103
Sam Johnson 101
Sam Johnson 102
Sam Johnson 103
SELF JOIN
A SELF JOIN is a regular join, but the table is joined with itself.
Example: Suppose we have a table Employees with a ManagerID that references the
EmployeeID of their manager.
Employees Table:
Query:
SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager
https://www.c-sharpcorner.com/ebooks/ 26
FROM Employees e1
LEFT JOIN Employees e2 ON e1.ManagerID = e2.EmployeeID;
Result:
Employee Manager
John Doe NULL
Jane Smith John Doe
Sam Johnson John Doe
Anna Brown Jane Smith
These examples cover the main types of joins in SQL Server. Each type of join serves a
different purpose and can be used depending on the requirements of your query.
Aggregate Functions
Aggregate functions in SQL are functions that perform calculations on a set of values and return
a single value as a result. These functions are commonly used in conjunction with the SELECT
statement to summarize data from tables. Here's an overview of some common aggregate
functions
Except for COUNT(*), all aggregation functions in SQL Server are built-in functions that do not
accept NULL data. An aggregate function returns a single value after calculating a set of values.
These functions are mostly used in database query languages' SELECT statements' GROUP
BY and HAVING clauses.
It must be noted that the aggregate functions cannot be nested, and that the expression cannot
be a subquery.
• SUM
• MAX
• MIN
• AVG
• COUNT
• APPROX_COUNT_DISTINCT
• CHECKSUM_AGG
• GROUPING
• GROUPING_ID
• VAR
• VARP
• COUNT_BIG
• STDEV
• STDEVP
• STRING_AGG
https://www.c-sharpcorner.com/ebooks/ 27
Note: To understand these aggregate functions, create a table in SQL Server name as simple.
Result
Result
Result
https://www.c-sharpcorner.com/ebooks/ 28
AVG function in SQL Server
A built-in function called AVG() is frequently used with the SELECT statement. The average
value of an expression is determined with this function. This function ignores the values for
NULL. The WHERE, GROUP BY, ORDER BY, and HAVING clauses can also acquire the
filtered output.
Result
Result
Result
Result
https://www.c-sharpcorner.com/ebooks/ 29
VARP function in SQL Server
A statistical function called VARP in SQL Server provides the variance of a collection of
integers. The VARP function returns the values' variance in the column or expression that has
been supplied. The variance measures how far apart the values are from the average value.
The variance is aThe values are more evenly distributed when the variation is bigger, and they
are more closely spaced when the variance is lower.
Result
Result
Result
https://www.c-sharpcorner.com/ebooks/ 30
Result
Result
Subqueries
A subquery, also known as a nested query or inner query, is a query nested within another SQL
statement. It allows you to execute a query inside another query. Subqueries can be used in
various SQL statements such as SELECT, INSERT, UPDATE, or DELETE to retrieve or
manipulate data.
In this example, (SELECT column1 FROM table2 WHERE condition) is a subquery that
retrieves data from table2 based on a condition, and the outer query uses this result to filter
rows from table1.
Indexes
Indexes in SQL Server are database objects that improve the speed of data retrieval operations
on database tables at the cost of additional storage space and decrease performance on data
modification operations (such as INSERT, UPDATE, DELETE). Indexes are created on columns
in tables or views.
In this example, EmployeeID is likely a unique identifier for each employee. By creating a
clustered index on EmployeeID, SQL Server physically orders the rows in the Employees table
by EmployeeID.
• Non-clustered Index: A separate structure from the data rows that contains pointers to
the data rows in a specific order, based on the indexed column(s).
https://www.c-sharpcorner.com/ebooks/ 31
CREATE NONCLUSTERED INDEX idx_LastName ON Employees (LastName);
This creates a non-clustered index on the LastName column. Non-clustered indexes are useful
for columns that are frequently used in search conditions or join operations.
• Unique Index: Ensures that the indexed columns contain unique values, similar to a
clustered or non-clustered index but with the uniqueness constraint.
CREATE UNIQUE INDEX idx_Email ON Employees(Email);
This ensures that each email address in the Employees table is unique. Attempting to insert or
update a row with a duplicate email address would result in an error.
Indexes are crucial for improving query performance, especially for tables with large amounts of
data.
https://www.c-sharpcorner.com/ebooks/ 32
8
Stored Procedures and
Functions
Overview
https://www.c-sharpcorner.com/ebooks/ 33
Introduction to Stored Procedures
SQL Server stored procedures are robust database objects that hold one or more SQL
statements. These processes are effective and reusable because they are assembled and
saved within the database itself. An overview of SQL Server stored procedures is given here:
Definition
A set of SQL statements used to carry out a particular operation is called a stored procedure. It
can execute other stored procedures, receive input arguments, execute operations like
SELECT, INSERT, UPDATE, and DELETE, and return output parameters or result sets.
Advantages:
• Code Reusability: Once created, stored procedures can be executed multiple times
without rewriting the same code.
• Performance: Stored procedures are precompiled and stored in the database, reducing
overheads and improving performance.
• Security: You can grant permissions to execute stored procedures without giving direct
table access to users.
• Maintainability: Changes can be made to a single stored procedure rather than
updating the same logic in multiple places.
https://www.c-sharpcorner.com/ebooks/ 34
@ClientName,
@ProjectManagerId,
GETUTCDATE(),
@ProjectDescription,
@StartDate
)
END
EXEC InsertProject
@ProjectName = 'Management Software',
@ClientName = 'Shubham Mishra',
@ProjectManagerId = 'A51DC085-073F-4D3A-AFC8-ACE61B89E8C8',
@ProjectDescription = 'This is a sample Management Software.',
@StartDate = '2023-01-20 12:45:00.000';
AS
BEGIN
SET NOCOUNT ON;
SELECT Id, ProjectName,
ClientName,ProjectDescription,StartDate,EndDate,CreatedDate from
Projects
END
EXEC GetAllProject
Output
Use a WHERE clause with the proper condition to retrieve a specific row from the table using a
unique identifier (such as Id) within a stored procedure.
CREATE PROCEDURE GetProjectByProjectId
@Id INT
AS
BEGIN
SET NOCOUNT ON;
SELECT ProjectName,ClientName,ProjectDescription,CreatedDate from
Projects
WHERE Id = @Id;
END
EXEC GetProjectByProjectId @Id=2
https://www.c-sharpcorner.com/ebooks/ 35
Output
EXEC UpdateProject
@Id=1,
@ProjectName = 'TimeSystem Software',
@ClientName = 'Shubham Mishra',
@ProjectManagerId = 'A51DC085-073F-4D3A-AFC8-ACE61B89E8C8',
@ProjectDescription = 'This is a sample TimeSystem Software.',
@StartDate = '2023-01-20 12:45:00.000',
@EndDate = '2023-04-20 12:45:00.000',
@UpdatedDate= getutcdate();
Output
https://www.c-sharpcorner.com/ebooks/ 36
CREATE PROCEDURE DeleteProjectById
@id int
AS
BEGIN
SET NOCOUNT ON;
Output
To preserve accurate information and past information, gentle deletion rather than hard deletion
is frequently used in database designs. Instead of physically removing records from the
database, soft delete involves listing them as inactive or removed. This strategy enables
previous tracking and data retrieval.
CREATE PROCEDURE [DeleteProject]
@id int
AS
BEGIN
END
EXEC DeleteProject @Id=2
Output
Custom Functions
creating custom functions using T-SQL in SQL Server, both scalar-valued and table-valued
functions, along with examples and how to use them in queries.
https://www.c-sharpcorner.com/ebooks/ 37
This example demonstrates how to create and use both scalar-valued and table-valued
functions in SQL Server. The CalculateBonus function calculates a 10% bonus based on the
salary, and the HighEarningEmployees function returns all employees earning more than a
specified amount.
Create the Employees table
SELECT
EmployeeID,
Salary,
dbo.CalculateBonus(Salary) AS Bonus
FROM
Employees;
https://www.c-sharpcorner.com/ebooks/ 38
Salary
FROM
Employees
WHERE
Salary > @MinSalary
);
SELECT
*
FROM
dbo.HighEarningEmployees(50000);
https://www.c-sharpcorner.com/ebooks/ 39
9
Database backup With
Table and Data
Overview
https://www.c-sharpcorner.com/ebooks/ 40
Create Database backup With Table and Data In SQL Server
A script is created for all the tables, views, functions, stored procedures, indexes, and other
objects of a chosen database when you do generate script actions. When backup failed to
restore a database from a lower version database to an upper version due to different versions,
it might be helpful in such a situation. In this situation, you can create a script using the
database schema and data using generate scripts, then run that script against the target
database. It can also be helpful if you only require one table's worth of data. You can script just
one table's worth of data using the produce scripts option. Let's look at how to create a script for
a whole database or just a few database objects.
https://www.c-sharpcorner.com/ebooks/ 41
• Step 3: Right-click on Task and select generate Scripts
• Step 5: Firstly, select save as script file and then click on the advanced option
https://www.c-sharpcorner.com/ebooks/ 42
• Step 6: Now there is an option to select Types of Data to script which contains three
options - Schema only, Data only, and Schema and Data choice depending on
requirements. Currently, I am choosing Schema and Data and clicking the ok button
• Step 7: After selecting save as script file, click on the first option to save the file.
https://www.c-sharpcorner.com/ebooks/ 43
• Step 8: We must provide the script file name and click on the save button.
• Step 9: Now after all the steps, we move forward and click on the next button
https://www.c-sharpcorner.com/ebooks/ 44
• Step 10: Again, click on the next button
• Step 11: In this final step save and generate the script
https://www.c-sharpcorner.com/ebooks/ 45
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.
ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner
MORE BOOKS