6710cb971a4a7 1729153943 Ms SQL Server Simplified
6710cb971a4a7 1729153943 Ms SQL Server Simplified
Simplified:
Your Gateway to
T-SQL
Index
About the Author .......................................................................................... 4
Who This Book Is For .................................................................................. 5
Chapter 1: Introduction to RDBMS and Getting Started with SQL Server
2022 Express Edition .................................................................................... 9
Chapter 2: Introduction to SQL Server and Database Management ........... 22
Chapter 3: Data Types in MS SQL Server .................................................. 26
Chapter 4: Database Creation in MS SQL .................................................. 32
Chapter 5: Transact-SQL (T-SQL) Essentials: Understanding SQL and
Query Writing ............................................................................................. 44
Chapter 6: Data Retrieval and Manipulation .............................................. 49
Chapter 7: SQL Functions and Data Processing ......................................... 69
Chapter 8: Advanced Querying Techniques ................................. 102
Chapter 9. The 3 Key Rules of Database Design Techniques - Writing Join
Queries on 3 or More Tables ..................................................................... 112
Chapter 10: Introduction ........................................................................... 115
Chapter 11 - Simple Sub Queries (Scalar, Multi-Valued) - Nested Sub
Queries - Correlated Sub Queries - CTE .................................................. 121
Chapter 12 - Views - DML On Views - Stored Procedures - With Input and
Output Parameters - If Else and Else If Ladder ........................................ 131
Chapter 13 - Functions - Try ... Catch - Transactions ............................... 141
Chapter 14 - Realtime Scenarios For Transaction -
Scope_Identity() - Triggers Introduction ...................................... 155
Chapter 15 - Triggers - Inserted and Deleted Temp Tables - Self Join -
Union Concept - DB BackUp - DB Restore - DBScript - DB Design Tasks
.................................................................................................................. 162
MS SQL Server Simplified | 4
By the end of this book, readers will have gained the knowledge
and skills necessary to work effectively with SQL Server in
various professional settings.
Key Features
4. Security:
5. Data Integrity:
6. Advanced Analytics:
7. Business Intelligence:
8. Integration Services:
9. Multiple Editions:
Usage Scenarios
• Web Applications: Used as the backend database for web
applications, ensuring data persistence and accessibility.
Conclusion
Overall, MS SQL Server is a powerful and versatile RDBMS that
is widely used in different industries and applications. Its
combination of performance, security, and advanced analytics
capabilities makes it a preferred choice for organizations
looking to manage their data effectively.
MS SQL Server Simplified | 13
https://www.microsoft.com/en-in/sql-server/sql-server-
downloads
After downloading, you will find the setup file in your File
Explorer's 'Downloads' folder. Open this folder, locate the
executable file, and run it to begin the installation. Choose the
basic installation option and accept the license terms to install
the Express Edition.
MS SQL Server Simplified | 14
MS SQL Server Simplified | 15
https://learn.microsoft.com/en-us/sql/ssms/download-sql-
server-management-studio-ssms?view=sql-server-ver16
Download the SSMS setup file, and once complete, open the file
from your downloads. The installation wizard will guide you
through a straightforward process: simply click 'Next', and then
'Install'.
MS SQL Server Simplified | 16
Conclusion
By following these steps, you have successfully installed SQL
Server 2022 Express Edition and SQL Server Management
Studio. You should now be able to create, manage, and query
databases, setting the foundation for more advanced SQL
Server tasks.
MS SQL Server Simplified | 22
Database Development
You should aim to develop skills to query databases effectively.
This involves learning to write queries that can extract
information from databases with multiple tables.
Understanding database architecture is also crucial, as it
enables one to not only query efficiently but eventually design
databases to meet specific requirements.
Database Querying
By mastering SQL queries, even within structures containing
thousands of tables, you can pull necessary data efficiently. The
importance of understanding and designing databases is
stressed—once you comprehend database requirements, you
can contribute significantly to application development.
MS SQL Server Simplified | 23
Composite Keys
In scenarios where a single attribute does not suffice to uniquely
identify a record, composite keys—comprising two or more
attributes—are used. Understanding composite keys is crucial
for handling relationships in complex databases.
MS SQL Server Simplified | 25
Practical Exercises
Database and Table Management
The chapter includes step-by-step instructions on creating
databases and tables, setting primary keys, and introducing
constraints to enforce business rules within the data. Emphasis
is placed on using SQL Server Management Studio's (SSMS)
GUI for these tasks.
Conclusion
The session concludes with a recap of essential database
concepts covered, encouraging participants to review SQL
tutorials and practice assignments to enhance their familiarity
with SQL Server tools and techniques. This ensures participants
are well-prepared for more advanced topics in subsequent
modules.
MS SQL Server Simplified | 26
1.1. char(n)
Description: The char(n) data type is used for fixed-length non-
Unicode character strings. The "n" specifies the string length,
which means that a char (10) will always store 10 characters. If
the string is shorter than the specified length, it will be padded
with spaces.
Use Case: Ideal for storing values that have a consistent length,
such as fixed-length codes (e.g., country codes or product ID).
1.2. varchar(n)
Description: The varchar(n) data type stands for variable-
length non-Unicode character strings. The "n" specifies the
maximum length of the string. Unlike char, varchar only uses
MS SQL Server Simplified | 27
1.3. nchar(n)
Description: Similar to char, but nchar(n) is used for fixed-
length Unicode character strings. This allows for storage of
characters from various languages and scripts.
Use Case: Ideal for cases where you need a fixed-length string
with international character support, such as names in different
languages.
bigint: An 8-byte integer data type that can hold larger integer
values, with a range from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
tinyint: A 1-byte integer data type that can store values from 0
to 255, most useful for storing small numbers.
real: Similar to float, but with less precision (4 bytes). It's used
when less precision is acceptable.
3.1. date
Description: Stores date values (year, month, day) without
time, taking up 3 bytes. It can hold dates ranging from 0001-01-
01 to 9999-12-31.
Use Case: Suitable for scenarios where only the date is relevant,
such as birthdays or event dates.
3.2. time
Description: Stores time values (hours, minutes, seconds, and
fractions of a second) without date, using 3 to 5 bytes
depending on precision (fractions of a second).
Use Case: Useful when you need to capture time of day without
the associated date, such as clock-in and clock-out times.
3.3. datetime
Description: Combines date and time into one data type, using
8 bytes. It can represent dates between 1753-9999 and precise to
3.33 milliseconds.
MS SQL Server Simplified | 30
3.4. datetime2
Description: An extension of the datetime type, allowing for a
larger range of dates (0001-01-01 to 9999-12-31) and greater
precision (up to 7 decimal places for seconds).
3.5. smalldatetime
Description: Combines date and time but with a limited range.
It takes 4 bytes and can represent dates from 1900-2079, with
minute precision (no seconds).
4.1. Uniqueidentifier
Description: This data type is used to store globally unique
identifiers (GUIDs). It takes 16 bytes and is often used for
primary keys in distributed systems.
4.2. Bit
Description: A Boolean data type that can store one of three
states: 0 (false), 1 (true), or NULL. It uses only 1 bit of storage.
Conclusion
Understanding the various data types in MS SQL Server is
crucial for effective database design. Choosing the appropriate
data type can greatly affect performance, storage efficiency, and
data integrity. From string data types for textual information to
specialized types for date and time, MS SQL Server offers a
comprehensive set of options to meet a wide range of
application requirements. For ranges of the various data types,
you can refer to additional resources such as W3Schools SQL
Data Types.
MS SQL Server Simplified | 32
o EmpId: Type EmpId, set its data type to int, and ensure
"Allow Nulls" is unchecked.
o Name: Enter Name, with a data type of nvarchar (50).
o Email: Add Email, with a data type of nvarchar (100).
o Gender: Enter Gender, using a data type such
as char(1) or nvarchar(10).
MS SQL Server Simplified | 38
o Choose "Relationships...".
o In the Foreign Key Relationships dialog, click "Add".
o Select "Tables and Columns Specification", and then
click the ellipsis (...) button.
o In the dialog, set the "Primary key table"
to Department and "Foreign key table" to Employee.
o Map DId in the Employee table to Did in
the Department table.
o Click OK to confirm and close the dialog.
Explanation:
('Susan G','[email protected]','F',59000,'1986-06-19','555-0108',2),
('Robert K','[email protected]','M',62000,'1989-01-31','555-0109',3),
MS SQL Server Simplified | 43
('Nancy Y','[email protected]','F',61500,'1993-09-12','555-0110',1),
('Charles','[email protected]','M',46500,'1978-07-27','555-0111',2),
('Mary Lok','[email protected]','F',47000,'1982-02-05','555-0112',3),
('Thomas J','[email protected]','M',54000,'1987-04-14','555-0113',1),
('Hobes A','[email protected]','F',34000,'1997-01-14','555-0114',3),
Explanation:
Introduction
In this chapter, we will explore various Structured Query
Language (SQL) operations such as INSERT, DELETE,
TRUNCATE, and UPDATE, and conduct a detailed
examination of concurrency control techniques like Optimistic
Concurrency Control and Last-In-Win. Through practical
examples and dummy data, you will gain a comprehensive
understanding of how these operations function and their
practical applications in database management.
1. INSERT Query
Department Table:
DName Description
IT Information Technology
FIN Finance
MARK Marketing
OPS Operations
LEG Legal
Employee Table:
Emp Dept
Name Email Gen DOB Phone
Id Id
mohan
12/12/1 92345
4 Mohan @gmail. M 1003
997 67890
com
DELETE Query:
TRUNCATE Query:
TRUNCATE vs DELETE
TRUNCATE is more efficient for deleting all records due to less
log space usage, whereas DELETE can be used with conditional
statements to remove specific records.
3. UPDATE Query
The UPDATE statement modifies existing data within a table.
Below is how it is applied to the Employee table:
UPDATE Employee
SET Name='Ravi', Email='[email protected]', Salary=87000
WHERE EmpId=2;
Explanation: This updates the Name, Email, and Salary for the
employee with EmpId 2.
MS SQL Server Simplified | 48
Concurrency Control
Concurrency control is crucial for managing simultaneous
transactions in a database to ensure consistency.
1. Optimistic Concurrency Control
UPDATE Employee
SET Salary = 65000
WHERE EmpId = 2 AND Salary = 87000;
2. Last-In-Win
UPDATE Employee
SET Salary = 73000
WHERE EmpId = 2;
Conclusion
This chapter provided an in-depth look at SQL operations for
manipulating database entries, outlining the differences
between DELETE and TRUNCATE, and offering insights into
concurrency control mechanisms. Understanding these
concepts is fundamental for efficient database management and
handling multi-user environments. By practicing with these
operations and exploring scenarios like concurrency handling,
database administrators can maintain data integrity and
performance.
MS SQL Server Simplified | 49
Introduction
Data retrieval and manipulation are crucial processes in
managing information within databases. They enable users to
query, format, and analyze data efficiently using SQL
(Structured Query Language). This chapter delves into various
SQL SELECT statements, illustrating how to retrieve specific
aspects of data from a hypothetical Employee table. Each
section provides multiple queries, detailed explanations, and
example records to facilitate understanding.
SQL Queries Explained
1. Selecting All Columns
raju@gmail 2000-
1 Raju M 9000 101
.com 03-24
prakash@g 2000-
2 Prakas M 90000 102
mail.com 03-24
anita@gmai 1998-
3 Anita F 50000 101
l.com 06-15
leena@gma 1994-
4 Leena F 62000 103
il.com 09-01
MS SQL Server Simplified | 50
1 Raju [email protected]
2 Prakash [email protected]
3 Anita [email protected]
4 Leena [email protected]
5 Mohan [email protected]
1 Raju [email protected]
2 Prakash [email protected]
3 Anita [email protected]
4 Leena [email protected]
5 Mohan [email protected]
1 Raju 9000
2 Prakash 90000
3 Anita 50000
4 Leena 62000
5 Mohan 55000
MS SQL Server Simplified | 52
Gender
Gender
M
MS SQL Server Simplified | 53
Did
101
102
103
Did Gender
101 M
101 F
102 M
MS SQL Server Simplified | 54
103 F
9. Selecting EmpId, Name, and Salary
1 Raju 9000
2 Prakash 90000
3 Anita 50000
4 Leena 62000
5 Mohan 55000
1 Mr.Raju M
2 Mr.Prakash M
3 Ms.Anita F
4 Ms.Leena F
5 Mr.Mohan M
1 Mr.Raju M
2 Mr.Prakash M
3 Ms.Anita F
4 Ms.Leena F
5 Mr.Mohan M
2 Prakash 90000 A
3 Anita 50000 B
4 Leena 62000 A
5 Mohan 55000 A
MS SQL Server Simplified | 58
1 Raju 9000 B
2 Prakash 90000 A
3 Anita 50000 A
4 Leena 62000 A
5 Mohan 55000 A
Explanation: This query fetches all data while sorting the result
set alphabetically by the employee names, facilitating easier
navigation through employee details.
MS SQL Server Simplified | 59
199
[email protected] 5000 8- 10
3 Anita F
m 0 06- 1
15
199
[email protected] 6200 4- 10
4 Leena F
m 0 09- 3
01
199
Moha [email protected] 5500 7- 10
5 M
n om 0 12- 2
12
200
0- 10
1 Raju [email protected] M 9000
03- 1
24
200
Praka prakash@gmail. 9000 0- 10
2 M
sh com 0 03- 2
24
MS SQL Server Simplified | 60
200
Prakas [email protected] 0-
2 M 9000 102
h om 03-
24
199
[email protected] 4-
4 Leena F 6200 103
m 09-
01
199
Moha [email protected] 7-
5 M 5500 102
n m 12-
12
199
8-
3 Anita [email protected] F 4500 101
06-
15
200
0-
1 Raju [email protected] M 4000 101
03-
24
MS SQL Server Simplified | 61
101 M 1 Raju
101 F 3 Anita
102 M 2 Prakash
102 M 5 Mohan
103 F 4 Leena
[email protected] 90 2000-
1 Raju M 101
m 00 03-24
[email protected] 75 1998-
3 Anita F 101
om 00 06-15
[email protected] 62 1994-
4 Leena F 103
om 00 09-01
SELECT NEWID();
NewId
6C8AA129-9F05-4B72-B4C7-8A67B0514FAF
A08A2E3F-B961-4B41-820F-7E6C6F734A5E
MS SQL Server Simplified | 63
Em
Di
pI Name Email Gender Salary DOB
d
d
prakash@gm 2000-
2 Prakash M 9000 102
ail.com 03-24
leena@gmail. 1994-
4 Leena F 9000 103
com 09-01
Emp
Name Email Gender Uid
Id
3B3C3FF8-FD56-
[email protected]
1 Raju M 43DA-B271-
m
365AFA196D17
48825B1F-6A93-
Prakas prakash@gma
2 M 4988-BA77-
h il.com
E5BE4F5D2BC4
E8EAD8F7-DF29-
[email protected]
3 Anita F 4496-8A9E-
om
BA521F4C74D6
20EC664C-FD45-
[email protected]
4 Leena F 41BC-9CFC-
om
60B7BF20298D
6D9A420A-045A-
mohan@gmail
5 Mohan M 475E-B3DA-
.com
993FA47C5FFC
MS SQL Server Simplified | 66
Emp
Name Email Gender Uid
Id
3B3C3FF8-FD56-
[email protected]
1 Raju M 43DA-B271-
om
365AFA196D17
48825B1F-6A93-
prakash@g
2 Prakash M 4988-BA77-
mail.com
E5BE4F5D2BC4
E8EAD8F7-DF29-
anita@gmail.
3 Anita F 4496-8A9E-
com
BA521F4C74D6
20EC664C-FD45-
leena@gmail
4 Leena F 41BC-9CFC-
.com
60B7BF20298D
6D9A420A-045A-
mohan@gm
5 Mohan M 475E-B3DA-
ail.com
993FA47C5FFC
MS SQL Server Simplified | 67
Emp
Name Email Gender Uid
Id
3B3C3FF8-
FD56-43DA-
1 Raju [email protected] M
B271-
365AFA196D17
48825B1F-6A93-
prakash@gmail.
2 Prakash M 4988-BA77-
com
E5BE4F5D2BC4
E8EAD8F7-
[email protected] DF29-4496-
3 Anita F
m 8A9E-
BA521F4C74D6
20EC664C-
[email protected] FD45-41BC-
4 Leena F
m 9CFC-
60B7BF20298D
6D9A420A-
[email protected] 045A-475E-
5 Mohan M
om B3DA-
993FA47C5FFC
MS SQL Server Simplified | 68
Conclusion
This chapter provided an in-depth look at SQL operations for
manipulating database entries, outlining the differences
between DELETE and TRUNCATE, and offering insights into
concurrency control mechanisms. Understanding these
concepts is fundamental for efficient database management and
handling multi-user environments. By practicing with these
operations and exploring scenarios like concurrency handling,
database administrators can maintain data integrity and
performance.
MS SQL Server Simplified | 69
The usage of the LIKE operator fetches names starting with 'A',
allowing for specific categorization.
EmpId Name Gender Salary Did
SELECT LEN('ASP.Net');
Length
7
29. Select Employees with Character Length of Their
Names
1 John Smith 10
2 Jane Doe 8
3 Alan Brown 10
4 Lisa White 10
5 Mark Lee 8
1 John Smith 10
3 Alan Brown 10
4 Lisa White 10
2 Jane Doe 8
5 Mark Lee 8
MS SQL Server Simplified | 82
1 john smith
2 jane doe
3 alan brown
4 lisa white
5 mark lee
32. Convert Names to Uppercase
1 JOHN SMITH
2 JANE DOE
3 ALAN BROWN
4 LISA WHITE
MS SQL Server Simplified | 83
Trimmed Name
Manzoor
34. Employees Where Name Equals Trimmed Value
This function extracts the first three characters from the string
'Manzoor'.
Substring
Man
37. Reverse and Substring Manipulation
Ooz
38. Employee Password Generation
C++
C#
40. String Split with Dynamic Contact
DECLARE @contact AS VARCHAR (50);
SELECT @contact=Contact FROM Employee WHERE EmpId=56;
SELECT * FROM STRING_SPLIT (@contact, '-');
1234567890
john.doe@
41. Basic Arithmetic Example
SELECT 1+1;
This command performs a basic mathematical operation.
Result
2
MS SQL Server Simplified | 86
SELECT 1+'5';
Result
SELECT '1'+'5';
Result
15
44. Concatenation of Characters
SELECT 'A'+'B';
Result
AB
MS SQL Server Simplified | 87
Result
124678i
SELECT 5.0/2;
Result
2.5
48. Cast Integer to Float Division
Result
2.5
49. Employees Where Did is NULL
SELECT CEILING(122.1);
123
54. CEILING() on Negative Numbers
SELECT CEILING(-3.2);
-3
55. FLOOR() Function Example
SELECT FLOOR(122.1);
Result
122
MS SQL Server Simplified | 91
SELECT FLOOR(-3.2);
-4
32.4464
58. Rounding Division Example
Result
3.333
MS SQL Server Simplified | 92
SELECT FLOOR(RAND()*1000);
Result
563
60. Counting Employees
NOE
10
61. Count Employees with Did Values
NOE
8
MS SQL Server Simplified | 93
NOE
5
63. Summing Salaries
SOS
542000
64. Average Salary Calculation
54200
MS SQL Server Simplified | 94
Result
72000
66. Minimum Salary Determination
Result
33000
67. Current Date and Time Retrieval
SELECT GETDATE();
This command fetches the current date and time, beneficial for
logging operations.
09/06/2024 10:45:30 PM
MS SQL Server Simplified | 95
SELECT YEAR(GETDATE());
2024
69. Static Year Extraction
SELECT YEAR('05/23/2002');
2002
70. Extracting Month from Date
SELECT MONTH('05/23/2002');
5
71. Extracting Day from Date
SELECT DAY('05/23/2002');
This command extracts the day of the month from a specified date.
Result
23
MS SQL Server Simplified | 96
2
74. Salary Calculation Based on Birth Month
2500
MS SQL Server Simplified | 97
3 3750
76. Employees Born in 2000
SELECT DATEDIFF(YY,'11/06/1984',GETDATE());
39
79. Month Difference Calculation
SELECT DATEDIFF(MM,'11/06/1984',GETDATE());
474
80. Days Difference Calculation
SELECT DATEDIFF(DD,'11/06/1984',GETDATE());
This shows the total day count between two specified dates.
Result
14310
81. Hour Difference Calculation
SELECT DATEDIFF(HOUR,'11/06/1984',GETDATE());
This calculates the number of hours between two timestamp values.
Result
858600
MS SQL Server Simplified | 99
SELECT DATEDIFF(SECOND,'11/06/1984',GETDATE());
51516012
83. Age Calculation of Employees
Result
09/26/2024
MS SQL Server Simplified | 100
Result
10/08/2024
86. Date of Retirement Calculation
Result
Sep 6, 2024
MS SQL Server Simplified | 101
Conclusion
In this chapter, we explored a wide range of SQL functions and
queries that are essential for effective data processing in
relational databases. Each SQL query demonstrated how to
retrieve, manipulate, and analyze data across various
dimensions such as employee demographics, salary
distributions, and department assignments. Understanding
these functions will allow you to efficiently interact with
databases and draw meaningful insights from your data. As
you've seen, SQL is not just a language for querying databases,
but a powerful tool for data analysis and decision-making. With
practice and exploration, You will gain proficiency in
harnessing SQL's capabilities to meet your data processing
needs.
MS SQL Server Simplified | 102
Introduction
Take your querying skills to the next level. Master different
types of JOINs to combine data from multiple tables, write
complex multi-table queries and implement subqueries and
Common Table Expressions. These advanced techniques will
allow you to handle complex data retrieval scenarios. Learn the
art and science of database design. You will understand key
design principles, analyze and implement complex database
structures, and design efficient schemas for real-world
scenarios. This module will help you create databases that are
performant, scalable, and maintainable.
Count
50
2. Count the Number of Female Employees
Count
45
3. Count of Employees by Gender (Error Example)
Error Msg
M 50
F 45
MS SQL Server Simplified | 104
1 25
2 20
3 10
6. Count by Department and Gender
1 M 15
1 F 10
2 M 20
2 F 10
MS SQL Server Simplified | 105
1 M 15 450000
1 F 10 300000
2 M 20 600000
2 F 10 250000
8. Count Female Employees and Sum Salaries
1 F 10 300000
2 F 10 250000
MS SQL Server Simplified | 106
- - - -
10. Average Salary of Male Employees by Department
1 M 30000
2 M 35000
MS SQL Server Simplified | 107
1 Alice 1 HR
2 Bob 2 IT
12. Left Outer Join
1 Alice 1 HR
2 Bob 2 IT
Explanation: This full outer join fetches all employees and all
departments, providing a complete view of the organizational
framework and staffing.
1 Alice 1 HR
2 Bob 2 IT
HR 25
IT 20
Sales 0
16. Cartesian Product Due to Missing Join Condition
1 Alice 1 ... HR
2 Bob 2 ... IT
HR 25
IT 20
Conclusion
In this chapter, we delved into the various SQL functions and
techniques essential for effective data processing and analysis
in relational databases, particularly focusing on employee
information management. We examined different aggregate
functions, such as counting and summing, to derive meaningful
insights about employee demographics and departmental
structures.
Example 1:
Customer Table:
• Attributes: CustomerID (Primary Key), Name,
Email, Phone
Example 2:
Orders Table:
• Attributes: OrderID (Primary Key), CustomerID
(Foreign Key), OrderDate, TotalAmount
2. 1:M Relationships
In a one-to-many (1:M) relationship, one record in the first table
can relate to multiple records in the second table. The primary
key of the "one" (master) table becomes a foreign key in the
"many" (child) table.
Example 1:
Department Table:
MS SQL Server Simplified | 113
Example 2:
Authors Table:
• Attributes: AuthorID (Primary Key), AuthorName
Books Table:
• Attributes: BookID (Primary Key), Title, AuthorID
(Foreign Key links to AuthorID)
3. M:M Relationships
Example 1:
Students Table:
• Attributes: StudentID (Primary Key),
StudentName
Subjects Table:
• Attributes: SubjectID (Primary Key), SubjectName
Example 2:
Products Table:
• Attributes: ProductID (Primary Key),
ProductName
Categories Table:
• Attributes: CategoryID (Primary Key),
CategoryName
Summary
In summary, database design follows structured rules to
maintain integrity and relationships among entities. Each
distinct entity is represented in its own table. In a 1:M
relationship, the primary key of the master table is used as a
foreign key in the child table. For M:M relationships, a junction
table is created to contain foreign keys that link the two master
tables. This approach is critical in ensuring data accuracy and
ease of retrieval in a relational database.
MS SQL Server Simplified | 115
Sid SName
1 John Doe
2 Jane Smith
3 Alice Lee
4 Bob Brown
5 Carol White
Cid CName
101 Mathematics
102 Science
103 History
104 Literature
1 101 Midterm 85
2 102 Final 90
3 103 Midterm 75
5 104 Midterm 95
MS SQL Server Simplified | 117
This query selects specific details like student IDs, names, exam
types, course names, and marks through joining three tables.
from StudentCourse SC
This query identifies the student who has achieved the highest
average marks in any exam, showcasing academic excellence.
from StudentCourse SC
This query filters for students who have missing marks, helping
to identify potential issues in tracking academic performance.
from StudentCourse SC
Conclusion
In this chapter, we've explored the essential techniques for
writing join queries involving three or more tables. By
understanding how to retrieve, manipulate, and analyze data
through these techniques, database designers and users can
gain deeper insights into their data relationships and effectively
evaluate student performance. Mastery of such queries not only
enhances database functionality but also supports informed
decision-making based on accurate data representations.
MS SQL Server Simplified | 121
1 Emma 20 F
3 Liam 21 M
5
4.Students whose IDs are in the set of student IDs
with NULL marks
2 Sophia 22 F
4 Oliver 23 M
5 Ava 20 F
Did
1000
1001
1002
1003
MS SQL Server Simplified | 124
Did DName
1001 Marketing
1003 Finance
Nesting Queries
Did DName
1000 HR
1001 Marketing
1002 Engineering
MS SQL Server Simplified | 125
Correlated Subqueries
1.Employee with the highest salary from department
1000
DECLARE @n AS INT
SET @n = 2
1 John M HR
2 Alice F Marketing
3 Maria F Engineering
4 James M Finance
1 Emma 85.0
2 Sophia 75.0
3 Liam 90.0
4 Oliver 70.0
5 Ava 92.0
Conclusion
In this chapter, we explored various forms of subqueries –
scalar, multi-valued, nested, and correlated – emphasizing their
application in complex data retrieval. Additionally, we
introduced Common Table Expressions (CTEs) as a clean
approach to organizing SQL queries for improved readability
and functionality. By mastering these constructs, you can
enhance your SQL skills, making data manipulation and
reporting significantly more efficient. Understanding these
queries and their outputs empowers you to handle real-world
data challenges with confidence.
MS SQL Server Simplified | 131
Introduction
In this chapter, we delve into the intricacies of database
manipulation using SQL, particularly focusing on views and
stored procedures. Views serve as virtual tables that allow users
to simplify complex queries, while stored procedures enable the
encapsulation of business logic on the server side. By
understanding how to create, modify, and manipulate views
alongside utilizing stored procedures with both input and
output parameters, readers can enhance their data management
capabilities while ensuring efficient and effective database
interactions.
2.Dropping a View
1 Alice 81.5
2 Bob 91.0
3 Charlie 76.0
CName Avg
Introduction to CS 80.5
vw_StudentsDetailsMVC
MS SQL Server Simplified | 136
CName NOS
Operating Systems 2
12.Creating a Stored Procedure for Employee Details
Department.DName, Department.Description,
EXEC sp_EmployeeDetailsMVC;
MS SQL Server Simplified | 137
(@Did AS INT) AS
Department.DName, Department.Description,
AS
IF (@Did IS NULL)
BEGIN
MS SQL Server Simplified | 138
ELSE
BEGIN
SELECT Emp.Eid, Emp.Name, Emp.Email, Emp.Gender,
Emp.Salary, Emp.DOB, Dept.DName, Dept.Description,
Dept.IsActive FROM Employee Emp
BEGIN
SELECT Emp.Eid, Emp.Name, Emp.Email, Emp.Gender,
Emp.Salary, Emp.DOB, Dept.DName, Dept.Description,
Dept.IsActive FROM Employee Emp
INNER JOIN Department ON Emp.DId = Dept.Did;
END
ELSE IF (@Did IS NOT NULL AND @Gender IS NULL)
BEGIN
...
END
-- Additional conditions here...
Conclusion
This chapter explored the fundamental operations of views and
stored procedures in SQL. We demonstrated how to create,
manipulate, and query views effectively while encapsulating
complex logic within stored procedures. By leveraging input
and output parameters, you can craft flexible and robust data
retrieval mechanisms, ultimately optimizing database
interactions. Moving forward, mastering these concepts will
enhance your proficiency in SQL and empower you to design
more effective data-driven applications.
MS SQL Server Simplified | 141
Select GetDate()
2024-09-06 10:25:30.123
2024-09-06 10:25:30.456
MS SQL Server Simplified | 142
2024-09-06 10:25:30.789
2024-09-06 10:25:31.000
2024-09-06 10:25:31.321
2.Calculating Gross Salary
From Employee
Gross Salary
966309.87
MS SQL Server Simplified | 144
Select [dbo].[GetGradeMVC](78)
A++
8.Average Marks and Grade Assignment
2 Bob 65.0 A
3 Charlie 40.0 C
4 David 55.0 B
This CTE computes grades for students and counts how many
belong to each grade classification. The use of CTE simplifies
query logic, improves readability, and enhances
maintainability, making it easier to analyze educational
outcomes.
A++ 2
A 1
B 1
C 1
10.Handling Pass/Fail Status
Grade NOS
Pass 3
Fail 2
11.Average Marks and Pass/Fail Grade
Case
1 Alice 80 Pass
2 Bob 73 Pass
3 Charlie 65 Fail
4 David 84 Pass
5 Emily 49 Fail
12.Summarizing Pass/Fail Results Across Students
SELECT
Case
FROM StudentCourse
Group by Case
end
MS SQL Server Simplified | 150
Pass 4
Fail 1
13.Function to Get Employees by Department
1 Adam 25000
2 Eve 30000
3 John 15000
4 Sarah 40000
5 Tom 50000
MS SQL Server Simplified | 152
Begin Try
End Try
Begin Catch
End Catch
Example Output:
Output: 'Admin is working on it' if an error occurs.
Begin Try
End Try
Begin Catch
End Catch
MS SQL Server Simplified | 153
Begin Try
End Try
Begin Catch
End Catch
Begin Try
End Try
Begin Catch
Conclusion
In this chapter, we covered critical SQL concepts such as
functions, error handling with Try...Catch, and transaction
management. By implementing functions, not only did we
enhance our ability to process data efficiently, but we also set a
precedent for error handling that promotes a user-friendly
experience. Moreover, through transactions, we learned how to
protect our data's integrity during failures in execution. These
techniques empower developers to create reliable systems that
maintain data consistency and uphold business logic.
Mastering these practices is essential for anyone looking to
excel in database management and application development.
MS SQL Server Simplified | 155
Introduction
In the realm of database management systems, ensuring data
integrity and consistency is paramount, particularly when
handling transactions that involve multiple operations. This
chapter delves into the practical applications of
the Scope_Identity() function in SQL transactions, as well as the
implementation of triggers to enhance functionality within
databases. By understanding these components through real-
world scenarios, developers and database administrators can
leverage these features to maintain robust and reliable data
operations in any application.
5 HR Human Resources
Information
3 IT
Technology
Financial
1 Finance
Department
This SQL command fetches all records from the Employee table
and organizes them by the first column in descending order.
The typical output might look like this:
Jane [email protected]
3 F 8000 2
Doe om
John
[email protected]
2 Smit M 7000 1
om
h
@EmpId AS INT,
@Salary AS FLOAT,
@DOB AS DATE,
Emp Table
4 Jack 7000
MS SQL Server Simplified | 160
EmpSalary Table
1 4 8000 2024-09-06
In this example, Jack's details, including his salary, are
recorded successfully thanks to the SCOPE_IDENTITY().
Conclusion
In conclusion, the chapter has provided insights into the
practical applications of transactions,
the SCOPE_IDENTITY() function, and triggers within SQL
Server. By leveraging these features, developers and database
administrators can ensure robust data integrity and
performance within their applications. Understanding how to
efficiently manage employee records, department alignments,
and timely feedback via triggers reinforces the importance of
transactional integrity in modern database systems. This
knowledge empowers professionals to implement best
practices in database management, leading to more reliable and
maintainable systems.
MS SQL Server Simplified | 162
Introduction
In the realm of database management, understanding the inner
workings of triggers, joins, and union operations is crucial for
maintaining data integrity and enriching data interaction. This
chapter delves into various SQL features that enhance how we
work with relational databases, particularly focusing on the
utilization of triggers, temporary tables, self-joins, and union
queries. These concepts are exemplified through different
scenarios involving employee and customer data, showcasing
not just the queries themselves, but also the practical
implications of each.
2 Alice 75000 1
3 Bob 45000 1
MS SQL Server Simplified | 163
The trigger not only registers the new entry but is pivotal in
ensuring that secondary actions such as logging or notification
follow.
SP_Help Emp
This command invokes a system stored procedure to present
detailed information about the structure of the Emp table, such
as column names, data types, and constraints. The output may
include:
Eid int 4 NO
Name varchar 50 NO
Salary float 8 NO
MS SQL Server Simplified | 165
1 Alice 123-456-7890
2 Bob 234-567-8901
3 Charlie 345-678-9012
4 David 456-789-0123
5 Ella 567-890-1234
MS SQL Server Simplified | 168
1 Alice 098-765-4321
2 Frank 876-543-2109
3 Charlie 345-678-9012
4 Grace 678-901-2345
5 Bob 234-567-8901
Consolidating different customer data aids in comparative
analysis between customer groups.
Name Contact
Alice 123-456-7890
Alice 098-765-4321
Bob 234-567-8901
Bob 234-567-8901
Charlie 345-678-9012
Charlie 345-678-9012
David 456-789-0123
Ella 567-890-1234
Frank 876-543-2109
Grace 678-901-2345
Utilizing UNION ALL allows comprehensive data analysis
without excluding any entries.
Name Contact
Alice 123-456-7890
Bob 234-567-8901
Charlie 345-678-9012
David 456-789-0123
Ella 567-890-1234
Frank 876-543-2109
Grace 678-901-2345
The UNION operation ensures that duplicate customer entries
from both tables do not skew analyses.
Name Contact
Charlie 345-678-9012
Bob 234-567-8901
By leveraging INTERSECT, organizations can pinpoint shared
customers, facilitating integrated marketing strategies.
Name Contact
Alice 123-456-7890
David 456-789-0123
Ella 567-890-1234
Utilizing EXCEPT allows businesses to identify exclusive
customers, aiding targeted outreach efforts.
Name
Alice
Bob
Conclusion
In this chapter, we explored pivotal SQL features such as
triggers, joins, union operations, and specialized queries that
facilitate effective data analysis and management. By
understanding and implementing these techniques, database
users can significantly improve their efficiency and accuracy in
handling relational data. With adaptable trigger management,
robust data querying, and insightful union queries, the mastery
of these concepts prepares individuals for more complex
database tasks and optimizes overall data workflows.