Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
360 views

SIMPLE SQL SQL Begginers Guide To Master SQL and Boost Career

Uploaded by

Sowda Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
360 views

SIMPLE SQL SQL Begginers Guide To Master SQL and Boost Career

Uploaded by

Sowda Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 369

SIMPLE SQL

Beginner’s Guide To Master SQL And


Boost Career
(Zero To Hero)
COPYRIGHT
All rights reserved. No part or section of this book is allowed to be reproduced or used in any
way with-out the documented consent and permission of the copyright owner except for the use
of references in a book review.

This is an intellectual work by author Dane Wade to help people learn SQL programming
language.

First Paperback Edition Published on June, 2022


Revised Edition Published on September, 2022

ISBN-13: 979-8833376164 (Paperback)


ASIN: B0B357WNV1 (Kindle eBook)
ISBN-13: 979-8840601259

Book Designed By Dane Wade

For more information, Email the author at : danewade@dataceps.com.

Copyright © 2022 by dataceps.com

www.dataceps.com
SQL
Table of Contents

INTRODUCTION................................................................................................................... 1

PART 1: THE FUNDAMENTALS........................................................................................................... 5

CHAPTER 1: MASTERING THE FUNDAMENTALS & DATABASES.................................. 7


THE EVOLUTION OF DATABASES.................................................................................. 9
DIFFERENT TYPES OF DATABASES............................................................................... 11
UNDERSTANDING DATABASE MANAGEMENT SYSTEMS......................................... 16
DIVING INTO THE CONCEPT OF DATA MODELLING.............................................. 18
ONE TO ONE............................................................................................................. 20
ONE TO MANY AND MANY TO ONE.................................................................... 21
MANY-TO-MANY...................................................................................................... 21
SELF-REFERENCING RELATIONSHIPS................................................................... 22
ENTITY-RELATIONSHIP MODEL.................................................................................. 23
ENTITY....................................................................................................................... 23
ATTRIBUTES............................................................................................................... 23
RELATIONSHIP.......................................................................................................... 24
ONE............................................................................................................................. 24
MANY......................................................................................................................... 24
1 AND ONLY 1........................................................................................................... 24
1 OR MANY............................................................................................................... 25
ZERO OR ONE........................................................................................................... 25
0 OR MANY............................................................................................................... 25

iii
SIMPLE SQL

REPRESENTING CARDINALITY BETWEEN ENTITIES USING RELATIONSHIP


NOTATIONS..................................................................................................................... 25
SCENARIO: A SIMPLE ECOMMERCE SALES ER MODEL........................................... 26
STEP 1: IDENTIFYING THE ENTITIES..................................................................... 26
STEP 2: IDENTIYING THE RELATIONSHIPS........................................................... 27
STEP 3: CREATING THE ER DIAGRAM................................................................... 27

CHAPTER 2: THE RELATIONAL MODEL, RDBMS AND SQL......................................... 29


THE RELATIONAL MODEL........................................................................................... 29
SOME KEY TERMS OF RELATIONAL MODEL....................................................... 30
KEYS IN A TABLE....................................................................................................... 33
CHARACTERISTICS OF A RELATIONAL TABLES........................................................ 36
RELATING MULTIPLE TABLES ..................................................................................... 38
DEPENDENCIES IN A TABLES.................................................................................. 39
NORMALIZATION.................................................................................................... 40
CODD’S RULES OF RELATIONAL MODEL.................................................................. 42
RELATIONAL DATABASE MANAGEMENT SYSTEM (RDBMS)................................... 45
SQL AND ITS IMPACT.................................................................................................... 47
ADVANTAGES OF SQL.................................................................................................... 47
HISTORY AND BIRTH OF SQL...................................................................................... 47

CHAPTER 3: DATACEPTION: Data, Datatypes and Metadata............................................. 53


UNDERSTANDING DATATYPES.................................................................................... 53
NUMERIC DATA TYPES............................................................................................ 55
STRING DATATYPES.................................................................................................. 61
BINARY DATA TYPES................................................................................................ 63
DATE TIME DATATYPES IN SQL.............................................................................. 65
METADATA: DATA ABOUT DATA.................................................................................. 68

iv
Table of Contents

PART 2: GETTING YOUR HANDS DIRTY WITH SQL....................................................................71

CHAPTER 4: INSTALLATION OF SOFTWARE TOOLS..................................................... 73


SQL SERVER INSTALLATION FOR WINDOWS............................................................ 74
SQL SERVER INSTALLATION IN MAC OS.................................................................... 95
PART 1: INSTALLING DOCKER................................................................................ 95
PART 2: DOWNLOAD AND INSTALL SQL SERVER ON MAC............................. 102
PART 3: AZURE DATA STUDIO INSTALLATION................................................... 106

CHAPTER 5: MASTERING SQL QUERIES ....................................................................... 111


SQL QUERIES, STATEMENTS, and CLAUSES............................................................... 111
NUT AND BOLTS OF SQL STATEMENTS.............................................................. 112
PRACTICING SQL COMMANDS............................................................................ 119

CHAPTER 6: UNDERSTANDING TABLES IN DEPTH..................................................... 141


DESIGNING AND CREATING TABLES ....................................................................... 141
STEP 1: IDENTIFYING ENTITIES............................................................................ 142
STEP 2: IDENTIFYING ATTRIBUTES...................................................................... 142
STEP 3: IDENTIFYING THE KEYS ATTRIBUTES .................................................. 143
STEP 4: IDENTIFYING THE CONSTRAINTS......................................................... 144
STEP 5: CREATING TABLES USING SQL STATEMENTS....................................... 163
BEST PRACTICES FOR CREATING TABLES THAT EVERY DEVELOPER WILL
RESPECT YOU FOR....................................................................................................... 163
CHOOSING THE RIGHT CASES AND STICKING TO IT:...................................... 164
AVOID SPELLING MISTAKES:................................................................................. 166
ADDING COMMENTS IN YOUR SQL STATEMENTS:.......................................... 166
ADDING ALIASES:................................................................................................... 168

CHAPTER 7: PLAYING WITH DATA USING SELECT ..................................................... 181


THE SELECT CLAUSE................................................................................................... 182
TOP........................................................................................................................... 182
DISTINCT................................................................................................................. 183
THE FROM CLAUSE...................................................................................................... 183
THE WHERE CLAUSE................................................................................................... 184

v
SIMPLE SQL

THE GROUP BY CLAUSE.............................................................................................. 185


COUNT ().................................................................................................................. 187
SUM ()....................................................................................................................... 188
AVG ()........................................................................................................................ 189
MIN () ....................................................................................................................... 190
MAX ()...................................................................................................................... 192
THE HAVING CLAUSE.................................................................................................. 193
THE ORDER BY CLAUSE.............................................................................................. 195
ADVANCED FILTERING (Operators in WHERE clause ).............................................. 197
COMPARISON OPERATORS IN SQL...................................................................... 198
LOGICAL OPERATORS IN SQL.............................................................................. 201
EVALUATION AND PROCESSING OF SQL QUERY ................................................... 207

CHAPTER 8: MASTERING SQL FUNCTIONS ................................................................. 213


SYSTEM DEFINED FUNCTIONS.................................................................................. 214
AGGREGATE FUNCTIONS........................................................................................... 215
MAX ()...................................................................................................................... 216
MIN ()........................................................................................................................ 216
SUM()........................................................................................................................ 216
AVG()......................................................................................................................... 216
COUNT()................................................................................................................... 217
STRING FUNCTIONS.................................................................................................... 217
ASCII ........................................................................................................................ 218
CHAR........................................................................................................................ 218
LEN........................................................................................................................... 219
CHARINDEX ........................................................................................................... 219
PATINDEX ............................................................................................................... 220
LEFT.......................................................................................................................... 220
RIGHT ...................................................................................................................... 221
LTRIM ...................................................................................................................... 222
RTRIM ..................................................................................................................... 222
REPLACE ................................................................................................................. 223

vi
Table of Contents

REPLICATE............................................................................................................... 223
REVERSE................................................................................................................... 224
QUOTENAME.......................................................................................................... 224
SPACE........................................................................................................................ 225
STR............................................................................................................................ 226
STUFF ....................................................................................................................... 226
SUBSTRING.............................................................................................................. 227
LOWER..................................................................................................................... 228
UPPER ...................................................................................................................... 228
SOUNDEX................................................................................................................. 229
DIFFERENCE............................................................................................................ 229
CONCAT................................................................................................................... 230
TRIM......................................................................................................................... 230
TRANSLATE ............................................................................................................ 230
NCHAR..................................................................................................................... 231
DATALENGTH......................................................................................................... 231
CONCAT_WS............................................................................................................ 232
CONCAT USING + ................................................................................................... 232
DATE AND TIME FUNCTIONS..................................................................................... 233
FUNCTIONS THAT RETURNS CURRENT DATE................................................. 234
FUNCTIONS THAT RETURN PART OF A DATE AND TIME:............................. 235
SQL FUNCTIONS TO MODIFY DATE VALUES...................................................... 238
WORKING WITH NUMERIC/MATH FUNCTIONS............................................... 240
POWER...................................................................................................................... 247
REFRESHING SOME PROGRAMMING FUNDAMENTALS....................................... 250
USER DEFINED FUNCTIONS ...................................................................................... 251
SCALAR FUNCTIONS.............................................................................................. 251
INLINE TABLE-VALUED FUNCTIONS................................................................... 254
LEVELING UP THE GAME WITH ADVANCED FUNCTIONS.................................... 255
WINDOW Function in SQL....................................................................................... 255
ROW_NUMBER()...................................................................................................... 257

vii
SIMPLE SQL

RANK()...................................................................................................................... 260
DENSE_RANK()........................................................................................................ 263
NTILE()..................................................................................................................... 266
DEALING WITH NULL VALUES USING FUNCTIONS ......................................... 268

CHAPTER 9: LEVELLING UP THE GAME WITH SUBQUERIES..................................... 277


What is a SUBQUERY? .................................................................................................. 277
EXPLORING POSSIBILITIES WITH SUBQUERIES....................................................... 278

CHAPTER 10: SQL JOINS MADE EASY............................................................................ 285


WHY DO WE NEED JOINS?......................................................................................... 285
UNDESTANDING JOINS............................................................................................... 286
THE CROSS JOIN..................................................................................................... 288
INNER JOIN............................................................................................................. 290
OUTER JOINS........................................................................................................... 294
LEFT OUTER JOIN................................................................................................... 295
RIGHT OUTER JOIN............................................................................................... 299
FULL OUTER JOIN.................................................................................................. 303

CHAPTER 11: SETS IN SQL............................................................................................... 313


UNION........................................................................................................................... 313
UNION ALL .................................................................................................................. 315
INTERSECT.................................................................................................................... 316
EXCEPT ......................................................................................................................... 317

PART 3: ADVANCE LEVEL STUFF..................................................................................................323

CHAPTER 12 : VIEWS AND INDEXES IN SQL................................................................. 325


VIEWS............................................................................................................................. 325
WHY USE VIEWS?.................................................................................................... 325
TYPES OF SQL VIEWS............................................................................................. 328
USER-DEFINED VIEWS............................................................................................ 329
INDEXES........................................................................................................................ 332

viii
Table of Contents

CHAPTER 13: STORED PROCEDURES, CURSOR AND TRIGGERS .............................. 337


UNDERSTANDING STORED PROCEDURES............................................................... 337
TRIGGERS...................................................................................................................... 341
TYPES OF TRIGGERS............................................................................................... 342
CURSORS....................................................................................................................... 349

RESOURCES and REFERENCES......................................................................................... 359

ix
SQL
INTRODUCTION

A fter completing my engineering in computer science, I was selected by a Multinational


Software Company as a junior developer. I joined the organization with high hopes and
ambitions.
I onboarded a project where my manager explained that I had to work as a SQL developer.
When I heard the word SQL. I was in deep shock;
I hated SQL since my college days. Even in college, I used to delegate all my SQL development
work to my college project mates. The reason was SQL coding was always confusing for me;
I started to think I must quit this job, and I even tried looking for other career paths (Which
was a mistake). Also, the project environment in which I started working in my first company
was not Motivating and Supportive. The manager wanted me to start taking on the tasks of a
senior developer in just a week of training. Whereas, It took me a whole week to understand the
office procedures and my responsibilities.
I sucked at my job, and my manager loaded me with extra work. So I worked my ass off and
hated every day at work. Because I could not shine, my work quality was pathetic.
I was terrible at memorizing the syntax of different SQL statements; complex queries that
senior developers gave me were difficult to understand. Creating even simple queries was a night-
mare for me.
I had no idea or path to know where to even start from?

When I searched for study material Online, none of the results explained the concepts thor-
oughly. But I persisted and decided that I would master this language. So I started practicing SQL
on my laptop for a couple of weeks, and things began to change for me. I started to understand
complex queries and write some advanced-level queries. My confidence started to build up, and
I realized that it's just a language, and I had to solve some problems using this SQL language.

So when I used this mindset of a craftsman and looked at SQL as just another skill I could
master, it changed everything for me. I also won the rising star award in my project because of
my work and massive improvement. My seniors started to appreciate my work and performance,
which boosted my confidence in my abilities.

SQL is just like any other skill that might seem difficult initially, but once you keep practicing
it and solve problems, you'll eventually master it.

1
SIMPLE SQL

Even if you want to build your database or learn this skill to become a SQL freelancer, this
book will help you; I will show you the path to mastering this language.
This book is designed carefully and crafted to take you from an absolute beginner level (Even
if you’re unfamiliar with coding) to an advanced level of proficiency in SQL.
I have divided this book into 3 parts:

Part 1: This part is about “Exploring the fundamentals.” I will explain the database, data-
types, and some foundational concepts in this part.

Part 2: This part of the book is all about Core SQL and its implementation. If you already
know the fundamentals, you can directly jump to this part of the book. After learning the
concepts in this section, you’ll be able to play with data.

Part 3: The 3rd part of this book contains advanced-level stuff. I recommend finishing the
previous sections before jumping to this part to become an advanced professional in SQL.

After learning SQL from this book, you’ll be able to write complex SQL queries, Analyse
data with ease and play with data using SQL.
My purpose in writing this book is to create a super high-quality resource for people willing
to learn SQL. I don’t want any other person to go through my pain. Mastering SQL boosted my
career and confidence, and I want you to experience the same.
Are you ready to thrive?? Then keep reading….

2
YOUR FREE GIFT

Before We dive deep into the nitty gritty of learning SQL. I wanted to share a gift to you.

To Download this FREE SQL pocketbook

Visit: https://dataceps.com/free-sql-pocketbook/

Or Scan the below QR code

This small SQL pocketbook will serve you in:

a) Quickly Referencing Complex SQL Syntax


b) Understanding Basics In No Time
c) Mastering SQL Faster
JOIN THE SQL FOR BEGINNERS COMMUNITY

Are you looking to learn SQL and share your progress, challenges, and roadblocks with like-
minded people?
If yes, Then Join SQL For Beginners community. This community has thousands of like-
minded people on the same journey to master SQL.
If you want to "level up" your SQL game, this group will benefit greatly.

Just visit the below Facebook group link:

https://www.facebook.com/groups/sqlmastery
PART 1
THE
FUNDAMENTALS
SQL
CHAPTER 1

MASTERING THE
FUNDAMENTALS & DATABASES

M astering the fundamentals will always help you learn any new life skill. That’s why I
always spend much of my time mastering the fundamentals first, then later, I move on to
the advanced level stuff.
That’s why this chapter is all about the essential fundamental concepts and knowledge before
learning about SQL programming.
I am sure you are ready and super-excited to learn and discover the most used data skill—
SQL ! SQL is one of the foundational languages while working with data, and it has made it
manageable for us “developers” to extract meaning and insights from data. Before I explain SQL
, It is better to understand data, databases, where and how the data is stored, and other essential
concepts. These fundamental concepts are the core of SQL, and many developers ignore this and
later on struggle with SQL.
We live in a digital age driven by data, and our lives are surrounded by digital devices that
capture all the information around us. Also, we can access information from any part of this
fantastic planet with a single click of a button!
Isn’t that amazing?

( Figure 1.1)

7
SIMPLE SQL

Data: Any information, knowledge, or attribute that describes a person, place, or entity can
be known as Data.

Data is basically stored inside a database on a server!

Server: A server is a centralized machine dedicated to providing different services to its clients
(i.e., other computers and users).

( Figure 1.2)

A server is basically a role that a powerful computer takes to serve the needs of its clients and
users. You can even convert a simple desktop computer into a server.

Below are the different roles a server can take:

• Web server: A server where data and information of a website are stored is known as a
web server.

• Email server: A dedicated server that handles and manages to send and receiving of emails
over the network.

• Database server: Database servers are dedicated physical servers used to provide services
in the database to different authorized users and applications.

• Database: A Database is a structured format of collected information. The information in


the database is stored in a way that anyone can quickly access that information whenever
it is required.

8
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

( Figure 1.3)

A database can be represented using the icon in the Figure 1.3.

Databases are the backbone of all the technologies you see around you!! Everyone needs a
database for efficient data storage for better decision-making!
Businesses, government agencies, small vendors, and weather forecasting organizations
require some kind of database to store the data they have collected over a period of time!

Database: A Database is a structured format of collected information. The information in


the da-tabase is stored so that anyone can access that information whenever required.

Even an old-school phone book falls under this category of the database. as it has related
information collected in a way that it can be accessed whenever a person requires specific infor-
mation. It can be considered manual data storage as writing, storing, and accessing data requires
manual effort.
As the technology evolved, databases also evolved and, we humans started using computer-
ized data storage and access methods.

THE EVOLUTION OF DATABASES

Before the Computer Age


Data used to be stored in files, folders, card cat-
alogs, etc. However, storing, managing, and retriev-
ing the required data was slow and required manual
labor.

(Figure 1.4 a)

9
SIMPLE SQL

Early Computer Age


Data used to be stored in simple flat files.
In this model, To access one particular infor-
mation from the file. The computer had to
start from the first file and traverse each line
until the desired information was found.

(Figure 1.4 b)

1960

Charles Bachman laid the foundation of computer databases.


Charles designed the first-ever computer database known as The
Integrated data store (IDS).This database used a network model and
was much more flexible and reliable than earlier databases.

(Figure 1.4 c)

1970
The second historical moment in database evolution was when
E.F Codd released his paper “A Relational Model of Data for Large
Shared Data Banks.” This paper introduced a beautiful and much
more efficient way to model data using– relational databases. The
data is stored in the tables in relational databases, and the tables were
cross-linked!
This model dramatically made managing, storing, and accessing
data faster and more efficient than the previous database models!
Relational databases used SQL to communicate and manage rela-
(Figure 1.4 d) tional databases.

10
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

2000

In the early 2000s, when the internet became a thing, the data gen-
erated in the internet age was massive. It wasn’t easy to manage such
massive data in a relational database ( on a single server).
Hence, NoSQL databases were the only solution for scalability!
(Figure 1.4 e)

Today

Now the times have changed, We are


still using RDBMS and NoSQL. But we
have introduced distributed databases as
well; in these distributed systems, data is
not stored in a single location, but is widely
spread across multiple locations that can
communicate with each other.

(Figure 1.4 f)

The database is not just being used to store information, and we are using data to extract
insights and trends that help organizations make better decisions.
Earlier databases were massive and used to take a lot of time to process and store informa-
tion.Database basically resides on servers in the storage spaces (disk space).

DIFFERENT TYPES OF DATABASES


Nowadays, there are many different types of databases present. I have listed down some of
these databases for you:

11
SIMPLE SQL

Personal Database:

(Figure 1.5 a)

A database designed for a single person, to be used on a personal computer. Personal data-
bases are small and easily managed.

Centralized Databases:

(Figure 1.5 b)

When the database operates from a single location, the data is stored at this centralized
location.
Multiple users from different locations can access this type of database. But to access the
data, users need to verify their identity first, and only after that can they access the data.
Usually, big companies and universities use this type of database. The database is located in
a single location, and the users (Employees or Students) can access it via their applications (Web
applications, company web portal etc.)

12
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

Distributed Database

( Figure 1.5 c)

A distributed database is a database that is physically distributed and spread across multiple
systems and machines. This database is exactly the opposite of the centralized database. These
distributed databases are connected via communication links. As a result, these databases have
faster speed, reliability, and expansion capabilities because of these distributed systems.

Commercial Database:

( Figure 1.5 d)

Any database specially designed to be used by a business is considered a commercial data-


base. The commercial database is uniquely designed and has a different composition than other
types of databases. Usually, they are sold by companies that create them for the business that
regularly uses them.

13
SIMPLE SQL

Relational Database
Any database that stores structured data in tables and uses SQL as a standard language to
communicate with data and is based on a “relational model” is called a relational database.

(Figure 1.5 e)

Relational databases are one of most used databases in the world and in this book. Going
forward, I will be discussing will be discussing in-depth about relational databases only.

NoSQL Database

(Figure 1.5 f)
Databases that don’t use SQL as their primary language and primarily deal with unstructured
and semi-structured data are considered NoSQL Database.

Graph Database

( Figure 1.5 g)

14
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

Graph databases are pretty similar to NoSQL databases. However, the data is stored in a
graph-like structure and helps analyze the interconnections between the connected entities.

Hierarchical Database

( Figure 1.5 h)

A database that stores data in a parent-child relationship model. Basically, in a tree-like


model with a top-to-down branching approach.

Cloud Database

( Figure 1.5 i)

A virtual database is accessed from a cloud platform ( like AWS, Azure, or google cloud ) over
the internet. It is similar to the traditional databases in how it works and operates.
The cloud platform provider manages the physical infrastructure (servers and disks), and the
users who want to use this database service can use it on a subscription basis.

15
SIMPLE SQL

Object Oriented Database


A database that uses the object-oriented model to store data is considered an object-oriented
database.

There are many more different types of databases. I have tried to cover most of them. But
in this book, I will be discussing mostly relational databases only. As I have already mentioned,
data in Relational Databases are structured and easy to access by using the query language SQL.
And to access and modify data in a database, we use database management systems (DBMS).

UNDERSTANDING DATABASE MANAGEMENT SYSTEMS

DBMS is a software program that helps create, manage, maintain, and delete databases. In
addition, it provides an interactive user interface to access data from a database.

Database management system (DBMS) runs on these database servers and provides various
database services to the users and applications.
To simplify this, let me explain it by using an analogy that best describes data, databases, and
database servers. Imagine server as a library, the database is the book racks, and the actual data
is inside the book. DBMS is the library staff who manages the books present on the bookshelves.
The server can have multiple databases like the library can have various bookshelves.
The reader who comes to read the books is the user or application that takes the help of
library staff to get the book they want to read (i.e., access the required data)

( Figure 1.6)

16
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

The actual data is stored on ‘data disks’ on these physical servers. This is similar to keeping
our data on computer hardware and mobile devices. That is considered as the physical location
of the data.

( Figure 1.7)

The data is stored in these physical locations in magnetic pattern groups (each group is popularly
known as bit). (See, Figure 1.8, for reference)

( Figure 1.8)

These groups are a combination of tiny grains; these small grains have only two possible
values—either 0 or 1
All the data files we see all around us, starting from excel files, images, texts, videos, etc., are
first converted in this format and then stored physically in these disks. This is all about how the
data is stored on a physical level.
Now, let me explain to you how we arrange the data on a “logical level” before storing it in
those hard disks!

17
SIMPLE SQL

FUN FACT:
Do you know how many BITS are there in 1 MB storage?
1Megabyte (MB) storage contains 8000000 bits!
You can now imagine how many bits are there in large storage.

DIVING INTO THE CONCEPT OF DATA MODELLING


Understanding the building blocks of data modelling

Most of the entities present in this world have some sort of data and information associated
with them. All this data basically tells us about that particular entity in detail.

Let me explain..

Meet Joey!

( Figure 1.9)

• Joey is a male
• Joey is 6ft tall
• Joey loves food
• Joey is an Actor

All this information is about one entity— Joey!

18
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

An Entity is basically any tangible or intangible thing, place, or person that has some set of
meaningful and measurable attributes or information.

By tangible entities, I meant anything that has “physical existence” in this world. And “intan-
gible entities” have a conceptual presence in this world.

For Example:
• An engineering college is an entity ( Physical Entity )
• An apartment is an entity ( Physical Entity )
• A dog can be an entity ( Physical Entity )
• The generator can be an entity ( Physical Entity )
• The oil in the generator can be an entity ( Physical Entity )
• A department of a college is an entity ( Conceptual Entity )
• Courses are entities (Conceptual Entity )
• Subjects are entities. (Conceptual Entity )
• Your phone, laptop, book, etc., all are entities! ( Physical Entities )

All these entities have some sort of meaningful information related to them.

Let’s take the example of a dog; it has meaningful information related to it (Also called its
attributes), which describes it perfectly. I have mentioned some of this information related to a
dog “Bruno” below:

( Figure 1.10)

19
SIMPLE SQL

ENTITY: Dog
• Dog’s Name: Bruno
• Dog’s Breed: Pug
• Dog’s Colour: Brown
• Dog’s Height: 1.5 Feet
• Dog’s Weight: 8 Kilograms
• Dog’s Date of Birth: 8th August 2020

So, now you understand what entities are and how many entities are present in this world
(unlimited ).
And also, it’s pretty obvious now that I love dogs!
Every entity in this universe has some meaningful information related to it. And all these
entities are connected with each other with some kind of RELATIONSHIP.
As per DBMS, Relationship is a logical link between two separate entities..

For Example:
a) Dog is an entity that is related to an owner. Both entities have their own attributes and
are related to each other with a logical link.
b) professor is an entity related to the department of a college. All 3 are entities and have
their own set of attributes.

As I have already mentioned, there are seemingly unlimited entities present in this world, and
all these entities are related to each other by RELATIONSHIP!
And as this world is so complicated and connected, there are multiple relationships or links
between each entity, and hence there are different types of relationships between entities:

ONE TO ONE
Whenever one record of an entity is related to only one record of another entity. This kind of
relationship is considered a one-to-one relationship.
For Example: Joey has one passport ( passport ID: C003004785).
And the passport (with the passport ID: C003004785) is related to only ONE person, “Joey.”
So, this relation is the best example of the one-to-one relationship between two separate
entities, “Passport” and “Joey.”

20
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

( Figure 1.11)

ONE TO MANY AND MANY TO ONE


Whenever one entity can have a relationship with multiple entities, that is considered one-to-
many relationships or many-to-one relationships.
For Example.: Joey has 3 credit cards from 3 different companies.
So, one entity, joey, is linked with multiple separate entities’ credit cards (with a different
credit card numbers).
And every credit card has only one customer linked with it and establishes one-to-many
relationships.

( Figure 1.12)

MANY-TO-MANY
Whenever many entities are related to many other different entities, that relationship is con-
sidered as many to many relationships.

21
SIMPLE SQL

( Figure 1.13)

For Example: Joey, Ross, and Sara started taking some courses for their professional devel-
opment from Udemy. Here, Joey, Ross, and Sara are acting as the entity “Students” related to
another entity, “Courses.”
And the relationship which connects students with the online courses is “Study.” And like
them, multiple other Students are studying and taking some courses online from Udemy.

SELF-REFERENCING RELATIONSHIPS
Whenever an entity has a relationship with itself. i.e., Entity refers to any of the attributes or
information with itself.
For Example.: Employee Joey works in a company and reports to supervisor and manager
Garry. Both fall under the entity employee and are related to another employee from the same
entity, creating a self-referencing relationship.

( Figure 1.14)

22
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

Hence, in this complex universe, all the entities can be related to each other.
Data and information related to each entity can then be linked to other entities’ information.
And to create complex databases. Our job is to identify these relationships between entities. And
eventually, create a model known as the Entity-Relationship model.

ENTITY-RELATIONSHIP MODEL
The Entity-Relationship Model is a logical model and representation of entities and their
relationships. After the creation of the logical model, storing data in relational databases gets
easier.
This model reflects the exact interdependencies of entities with each other in the real world.
In ER model, We use different shapes and elements to represent real-life relationships. Below
are the different shapes and elements of an ER Model:

ENTITY
A rectangular shape is used to represent an entity in an ER Model. (See, Figure 1.15 for
reference)

( Figure 1.15)

ATTRIBUTES
Every entity has some attributes or related information associated with it. These attributes
are represented by the oval shape in a ER model. (See, Figure 1.16 for reference)

( Figure 1.16)

23
SIMPLE SQL

RELATIONSHIP
The diamond shape represents the Action or relationship between the entities. (See, Figure 1.17
for reference)

( Figure 1.17)

As discussed in the previous section, there are many different types of relationships and these
types of relationship between the entities are represented as:

ONE

( Figure 1.18)

MANY

( Figure 1.19)

1 AND ONLY 1

( Figure 1.20)

By 1 and only 1 , here I mean that there can only be ‘ 1 and only 1’ relationship that can exist
between entities. Not more than that..

24
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

1 OR MANY

( Figure 1.21)

By 1 or many , I mean that there can be either 1, or even many relationships can exist between
entities.

ZERO OR ONE

( Figure 1.22)

The above notation represents a relationship where there can either be 0 or 1 connection between
the entities.

0 OR MANY

( Figure 1.23)

The above notation represents a type of relationship where either 0 or Many relationships can
be present between the mentioned entities.

REPRESENTING CARDINALITY BETWEEN ENTITIES


USING RELATIONSHIP NOTATIONS.
Let me show you how to use the ER shapes, elements and notations practically for different
types of relationships.
Below are some scenarios for which I have used ER model.

a) 1 Person has 1 passport

( Figure 1.24)

25
SIMPLE SQL

b)1 Customer has either 1 or MANY credit cards

( Figure 1.25)

c) 1 or MANY Courses, can have , 1 or MANY Students

( Figure 1.26)

I hope, now you have a better idea of how entities and relationships are represented in ER
models.
To make you understand this concept much deeper, I will present an ER model representation
of a real-life scenario. Together, We will identify how many entities are there and the “types of
relationships” these entities have with each other.

SCENARIO: A SIMPLE ECOMMERCE SALES ER MODEL


Let’s take an example of an ecommerce model. There are many entities present in an ecom-
merce system. I will tell you about these different entities and then how we can represent them
in an ER model.
Usually, the actual model is much more complex, but I will only consider a simplified version
of the actual model. This simplified model will have much lesser entities and relationships.

STEP 1: IDENTIFYING THE ENTITIES


The first step is to identify the entities of an e-commerce sales system. Usually, in every commerce
system. However, there are below essential entities present in every commerce system.

a) Product
b) Seller
c) Customer
d) Order
e) Shopping cart
f) Shipping

26
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

Although many other entities are present in the e-commerce system, I will only take a few of
them to keep it simple to understand. Then I will create an ER model based on that. Let’s con-
sider these 6 entities and create ER model on top of that.

STEP 2: IDENTIYING THE RELATIONSHIPS


I hope while shopping online, you must have observed the below scenario.

a) One online seller can sell one or more products.


b) There can be many customers that can buy many products online.
c) One online shopping cart can have multiple orders.
d) Many orders are processed and delivered to a customer by one shipping department.

STEP 3: CREATING THE ER DIAGRAM


Create an ER diagram based on the information we have for this scenario.

( Figure 1.27)

As you can see in the ER diagram of an online shopping system in Figure 1.25. It has different
entities, with attributes and all the entities have meaningful relationships with each other.
I am sure you can now create and understand Simple ER models. I hope now you understand
how the data present in the world can be represented in diagrams and models.

27
SIMPLE SQL

We are surrounded by so much data that it needs to be organized so that anyone can under-
stand it and process it quickly.
Now, I want to present another model to you.
That will also help you understand the fundamentals and set an unshakable foundation for
your career in the data field. The following section is dedicated to that model popularly known
as the Relational Model!

28
SQL
CHAPTER 2

THE RELATIONAL MODEL,


RDBMS AND SQL

T he relational model was a pivoting point in the data management industry. As a result, there
are countless relational database management systems nowadays. That’s why understanding
the relational model becomes quite essential. In this chapter, I will discuss the relational model,
relational tables, and their characteristics. Also, I will be telling you about how we can relate
multiple tables in a relational model. Then I will explain relational database systems, SQL, and
much more.

THE RELATIONAL MODEL

In 1970, a historical event happened that basically changed the


course of how we store, process, and manage data. Dr. Edgar F Codd
published a paper “A Relational Model of Data for Large Shared Data
Banks” in the research lab of IBM.
Many big corporations and companies then adopted this rela-
tional model for commercial purposes.
The concepts and terminology present in the relational model are
different than the ER model. Basically, both models are different and
have their own techniques to represent the data.
( Figure 2.1)

The purpose was to store data in 2D tables where rows and columns will hold the data
related to the entity for which we are trying to hold the data. The foundation of this model is
on set theories ( i.e. - mathematical discipline). A set is basically a collection of unique elements
( i.e., without any duplicates )
Therefore, in the relational model, there are some constraints and rules that tell us how data
MUST be stored in the tables.

29
SIMPLE SQL

The reason for storing data in tables is to get rid of unnecessary duplicate data entries.
Removal of duplicates is done with the help of a unique identifier, also known as a “Primary
Key.”
The foundational concept you must understand is the concept of keys, even before you start
to learn about RDBMS .People who understand and focus more on these basics will definitely
thrive in SQL programming.
Let’s get started...
Before going further, let me explain to you some foundational concepts and building blocks
of relational databases.

SOME KEY TERMS OF RELATIONAL MODEL.


Relation or Table: In the relational model, data is stored in tables, also known as relations. The
table will have rows and columns to store the data. It is the fundamental logical component that
stores information. The information/data related to any real-world entity is stored in tables in
rows and columns.

Attribute: An attribute of a relational model is the property/Information related to the table (or
relation). An attribute is also known as a field. To be honest, most developers use the term “field”
instead of “attributes.”

Example:
To understand the concept of tables and attributes, Let’s consider a relation (Table) Student .
The student table has below attributes:

a) StudentID
b) FirstName
c) LastName
d) EmailID
e) CourseID
f) JoiningDate

The Student table is represented in Figure 2.2:

30
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

(Figure 2.2)

Relation Schema: The design and attributes of a table ( or relation) is called relation schema.
Let me explain it with a simple example.

Example: The schema for the above-mentioned student table should be

Student ( StudentID, FirstName, LastName, EmailID, CourseID, JoiningDate)

Records: Records are the actual data or information related to an entity. (See, Figure 2.3 for
reference)

(Figure 2.3)

Tuple: A tuple is a single record of a relation.

(Figure 2.4)

31
SIMPLE SQL

NULL Records: In a table ( or relation ), sometimes no value is available for a particular field
( attribute ), or the data is inappropriate. NULL is entered whenever there is no value for an
attribute.

NULL is NOT equal to 0 (ZERO) as ZERO has some value.

NULL is NOT even equal to NULL. Every NULL is distinct and unique, but still, it is represented
the same. It just describes “I don’t know” or the “information is missing.”

(Figure 2.5)

Column: The total values present for a particular attribute are the column of that relation (or
table).

(Figure 2.6)

Degree: A total number of attributes present in a table (or relation) is called degree of that table.

From the above table in the figure 2.6, Student, can you tell what the degree is?

It is 6.

32
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

(Figure 2.7)

Cardinality: Cardinality is the total number of records or rows present in a table.

(Figure 2.8)

The cardinality of the above table is 4.

KEYS IN A TABLE
In a table, the attribute that helps in uniquely identifying a column is called a key.
There might be thousands if not millions of people with the same name or record in a table.
So to identify each record uniquely, A key is the best thing that we can have in a table.
A key is basically an attribute or group of attributes that helps in uniquely identifying other
attributes of a table.
The concept of keys is dependent on the concept of Determination.

33
SIMPLE SQL

Determination here means that if you know the value of an attribute X of a table, then
attribute Y can be determined from it.

This can be Denoted by: X à Y

Let me explain it with one example..

Suppose you want to determine the Course ID on an online course platform for the student
joey. To do this, you just need Joey’s ID for the table where this information is stored.

That means StudentID DETERMINES CourseID

This can be denoted as : StudentID à CourseID

If an attribute is able to determine multiple attribute we can denote it as below:

StudentID à FirstName, LastName, CourseID and so on..

After understanding the concept of determination, I hope you now know that there are
certain types of relationships between the attributes of the table.

CANDIDATE KEY:
A candidate key is an attribute or combination of attributes that helps in uniquely identifying
a row of a table. There can be more than a single candidate key. You can say they are the candi-
date for becoming the primary key. A primary key can also be the combination of candidate keys.

PRIMARY KEY:
A primary key in a table is a column (Sometimes a combination of multiple columns), which
helps make every data row a UNIQUE row. While designing the database, the primary key is
selected from the set of candidate keys.

Properties of a primary key in a table:

a) ONE table can have ONE primary key only.


b) The primary key column can’t have NULL values
c) The primary key column must have a unique value for every record.

Understanding the concept of a primary key is essential before moving ahead. This is the
most important concept that is frequently used when we are working in RDBMS.

34
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

(Figure 2.9)

ALTERNATE KEY:
There is only one primary key selected while designing a database. Rest all the remaining
keys that are not chosen as primary key are known as Alternate key

FOREIGN KEY:
An attribute or set of attributes that help link two tables is called a “Foreign Key”. The
­foreign key simply refers to the primary key of another table.

(Figure 2.10)

35
SIMPLE SQL

CHARACTERISTICS OF A RELATIONAL TABLES


In the relational model, the Data of every entity is stored in tables, and then these 2D tables
are related to each other using Primary key and foreign key relationships. But not every table
that has some data in rows and columns can be considered a relational table. There are specific
characteristics that define if a table is relational or not.

a) Sequenced columns and rows are insignificant: Data in columns and rows can exist with-
out any order or sequence (i.e., Alphabetic, Numeric, Ascending, or descending)

For Example: The FirstName of the Student can exist in any order. The first name ”Sara” can
come before “Dane”.

b) No duplicates in rows are allowed: This is one of the most important rules of relational
tables. A relational table can’t have duplicate data in rows. As you can observe, in the
­figure 2.11 a there is a duplicate record in the last row with the StudentID. It is not
allowed in relational tables!

(Figure 2.11 a)

If we remove this duplicate record from the table, then we can say it is a relational table. (See,
Figure 2.11 b )

(Figure 2.11 b)

36
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

c) No duplicate table name: In one relational database, the table name must be unique. i.e.,
notable names with the same name can’t exist in one database.

d) Each column must have a unique name: The column names of a relational table must
have unique names.

(Figure 2.12)

e) Column values must be of same kind: All the values in a particular column must be of the
same kind—basically the same “datatype.” I will discuss what data type is in the upcom-
ing chapter. For now, understand that if the column is designed to have Alphabetical
values (Example: Days of the week: Sunday, Monday, Wednesday. Etc), then it can’t have
numbers. ( Example: 1223, 1323, 132).

f) Values in a relational table is always atomic: According to this characteristic of a rela-


tional table, there must always be exactly one value in each row for a particular column.
If there is no value present for that attribute, NULL should be assigned for that value.

So now you understand how data is stored in tables, and the key terms and characteristics of
relational tables. Now, I will discuss how multiple tables are connected in a relational database.

37
SIMPLE SQL

RELATING MULTIPLE TABLES


As I have discussed earlier, in a relational model, data is stored in the tabular format, and
in real life, there are many entities present in a system. Even If we consider a small system, like
school, college, or office systems. There will be hundreds if not thousands of tables. And to estab-
lish a relational model, those entities need to be connected somehow, and the required informa-
tion can be accessed quickly. The best way to connect and relate tables is by using key fields.
These key fields are primary and foreign keys.When the primary key field of table A is linked
with a field of another table B, then the field of table B is said to be a foreign key for table A.
The foreign key must be a primary key in the reference table.

(Figure 2.13)

These primary and foreign keys help build relationships between tables and eventually get
the desired information. Although relating multiple tables with the help of foreign keys helped
establish complex relationships. But it creates many issues as well.
When Dr. Codd developed the concept of the relational model. He knew that the complexity
of relationships between the real-world data might create issues in the RDBMS. Data present
in a table are interdependent with each other and have some meaningful associations and rela-
tionships with each other. Also, In reality, data changes updates and gets deleted from the tables,
creating anomalies in the databases.

To make this concept of relating multiple tables simple, Let me explain table dependencies and
anomalies first...

38
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

DEPENDENCIES IN A TABLES
Dependencies in a table help in identifying the relationships between the different attributes.
As we learned in the previous section about keys, one table attribute (Y) can be determined using
the other one (X). This means that both the table attributes are in a relationship and have some
sort of ‘dependency’ between them.

Functional dependency
When one attribute (X) of a table UNIQUELY identifies another attribute (Y) of the same
table, then we can say that there is a FUNCTIONAL DEPENDENCY between these two
attributes.
Usually, the attribute X is a primary key in the table.
These dependencies gives birth to anomalies that increase redundancies, inconsistency, and
irregularities in data.
These irregularities and inconsistency in data are known as Data anomalies.

DATA ANOMALIES are the issues and irregularities in the data that happen while inserting,
updating, and deleting data from the databases.

INSERT Anomaly: When we insert data for an attribute in a table without any data for the rest
of the dependent attributes, inconsistency will occur. Suppose, there is a dependency between
two attributes, we can’t simply insert data for the first attribute and ignore inserting data in the
second one.

Let me explain it with an example

Example:
Suppose, A new student opted for a course on an online course platform. And for this new stu-
dent, we need to enter the data in the database table- Students. But somehow, the course that
student selected is NOT in the database table-Courses.

In this case, we know that a student without any course must not exist in the database. Hence
this will create an insert anomaly!

UPDATE Anomaly: The inconsistency occurs in a database when we modify an attribute in a


table in which we have dependent attributes. We can’t update or modify it completely without
creating inconsistency. We will need to update all the related rows to ensure data is consistent in
the table.

39
SIMPLE SQL

Example:
Suppose in the Student table I have thousands of students, and for each student I have also
mentioned CourseName in the Student table only. Now, If I want to update the name of the
any course I need to change data in each row, which will cost us time and lots of energy. And
without any guarantee that the data will be completely updated in the table.

DELETE Anomaly: The inconsistency that occurs in a database when we try to delete data from
a table, and that data is dependent on data present in any other attribute or table.

Example: Suppose any course creator decides to take down the course from the platform for
personal reasons. And we need to delete the records related to that particular course. Then the
deletion of the record related to that course will result in the deletion of other student’s data.
To resolve and fix these different database anomalies in EF Codd introduced the concept of
Normalization!
Normalization is the best way to reduce these anomalies and inconsistencies in the database.

NORMALIZATION
Normalization is efficiently organizing the data in the database by reducing redundant data
and breaking larger complex tables into smaller tables. In addition, it reduces redundant data
that eventually reduces the database’s size resulting in a faster database.
To normalize tables, we need to follow a process and implement some rules on the tables that
EF Codd developed.

These rules are called “Normal forms.”

When the first rule is followed in the database, it is said to be in the first normal form. However,
When the first two rules are followed, it is considered the “second normal form”. If all the first
three rules are followed, it is in “third normal form.”

Below listed are the normal forms for normalization:

1st Normal Form: Each table cell must contain a single value (atomic value).

2nd Normal Form: To be in 2nd normal form, First, the table must be in 1st Normal form,
and all the non-key attributes must depend on key attributes.

40
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

3rd Normal Form: The table must be in 2nd Normal form, and all attributes must depend
upon the primary key only.

Although these normal forms removed most of the inconsistencies in the data, some discrepan-
cies were still there. Some higher normal forms then removed these.

These higher normal forms are:

Boyce Codd Normal Form: EF Codd and Raymond F Boyce created this normal form called
Boyce-Codd Normal. This form was an extended and more robust version of the 3rd Normal
form (Also known as 3.5 NF). 3.5 normal form dealt with anomalies that BCNF was not able to
remove. A table is considered in BCNF when it is in the 3rd Normal form and doesn’t have any
overlapping candidate key present in the table.

4th Normal Form: For a table to be in 4th normal form, it must follow the below conditions:

a) It must be in Boyce Codd Normal form.


b) No multivalued dependency.

Multivalued dependency: When the value of two attributes is not dependent on each other
but a common attribute.

There are 6 normal forms in total, but I have only given a brief overview until the 4th normal
form in this book. I am not covering this concept deeply because the scope of this book is to
build the foundational knowledge of databases and focus entirely on SQL.
The purpose of introducing this concept of normalization to you was to make you under-
stand how the databases evolved and where it has reached now.EF Codd developed normal
forms and improved the usage and execution of databases. When a database is normalized, it
runs faster, and data integrity is at its peak.

Data integrity is the reliability, consistency, and accuracy of data stored in a database.

The concept of normalization is relating multiple tables of a complex system without having
any data anomalies. These relationships between the tables make RDBMS better than other tra-
ditional database management systems. Other conventional database management systems are
slow and rely on storing data on file systems.
When the relational model was relatively new and started becoming popular, every other
Database vendor marketed their products as RDBMS back in the day.

41
SIMPLE SQL

Therefore, Codd presented rules of the relational model to make people aware and under-
stand a relational database. Any database management system that follows these rules can be
considered as RDBMS.

These rules are mentioned as below:

CODD’S RULES OF RELATIONAL MODEL

# Rule 0: The Rule About Foundation


Any relational database management system must manage its database through its relational
capabilities only.

# Rule 1: The Rule About Information


All the data related to any entity MUST be stored in cells of a table.

#Rule 2: The Rule About Guaranteed Access


Every value that needs to be accessed from the database must be accessed by combining Table
name + Primary Key (Row Value) + Column name (Attribute Name).

#Rule 3: The Rule Of Systematic Treatment Of NULL values


NULL is used for multiple reasons in a database. Hence the usage of NULL must be consistent
and systematic. It must only be used for missing values, No Data, and Inappropriate informa-
tion. Also, the Primary key must never be a NULL value.

#Rule 4: The Rule Of Active Online Catalog


The database structure must be stored in an online catalog that can only be accessed by autho-
rized users using queries.

Breakdown: we store an organization’s application, e-commerce systems data, etc. These data-
bases might have many entities related to each other with a relationship. This rule says that,
along with storing the data of applications, systems, etc. We must also keep the structure of the
data itself.

i.e.- What is present in this database? What are the columns present in the tables?

42
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

Only Authorized users can use SQL to extract all these essential information.
For example: An authorized user can check the number of columns for any table by executing
a SQL command.

#Rule 5: The Rule Of Comprehensive Data SubLanguage


There must be one “well-structured” language that helps in accessing, manipulating, manag-
ing transactions in a database.

Breakdown:
According to Codd, the language must be comprehensive and must support the below criteria:

a) Defining data (Constructing new tables, rows, and columns)


b) View Data (Able to see what Data is in a table)
c) Manipulating Data (change the data inside a table)
d) Managing transactions (the language must allow managing transactions in a database)
e) Authorization (which users are allowed to access the database and what they can do once
they access the database)

#Rule 6: The Rule Of Updating Views


All the views are updated theoretically must be updated by the database system practically.

Breakdown:
Views are virtual tables not physically present in the database ( more on this in chapter 12 ).
Understanding views first is essential to understand this rule, and for that, you need to wait for
that chapter to come. For now just understand that views are virtual tables used in the database
systems, that have some underlying tables.
According to this rule, whenever there is a change of data in a view. Then the underlying data
present in the table must also be changed.

#Rule 7: The Rule Of High level Insert, Update and Delete


The database system must allow performing operations like insertion, updating, and deleting
single or multiple rows. Also, the database system must support operations like union, intersec-
tion, and minus.

Breakdown:
As per Codd, the database management system must allow the users to manipulate the data
and apply some operations. You will discover this operation on the data in later chapters in
depth. However, these operations are essential for data analytics, cleaning, and data integration.

43
SIMPLE SQL

#Rule 8: The Rule Of Physical Data Independence


The changes in the table’s physical location must not impact the data at the application level.

Breakdown:
According to this rule, the changes or modifications to the table’s physical address must
not impact the data at the application level. Even if the table’s physical location is changed and
transferred to another disk, this must impact how applications access the data from those tables.

#Rule 9: The Rule Of Logical Data Independence


Logical and conceptual changes at the table level must not affect the application and how it
accesses or processes the data from that application.

Breakdown:
As per this rule, changes done in the schema at the logical or conceptual level must not affect
the processing and accessing of data at the application level. For example, If you add a new
column in an existing table, it must not affect the application accessing the data from that table.

#Rule 10: The Rule Of Integrity Independence


The integrity of the database must be dependent on its own and not on some external appli-
cation or programs. And the integrity constraints must be stored in the database catalog.

Breakdown:
There are different kinds of data stored and accessed in the database , and there are specific
rules or constraints in a table (You will learn about these table constraints in chapter 6) to ensure
the data is consistent and reliable. This rule emphasizes that data integrity must depend on other
systems, and there should be specific rules to maintain consistency.
These integrity constraints must be stored in a database catalog and not in the application
program. This will help the database to be independent and not rely on the application to main-
tain its integrity.

#Rule 11: The Rule Of Distribution Independence


Distributed portions of data in different physical locations must not affect how the applica-
tion works for the end-user.

44
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

Breakdown:
Data distributed over different physical locations and used by various end-users in various
applications must appear as if the data is stored in one place in a single computer. In reality, data-
base data is not stored in a single location and is distributed over different locations.

#Rule 12: The Rule Of Nonsubversion


Suppose a system has a low-level language to access the database system. It should not
change the data by bypassing the integrity.

Breakdown:
Suppose a database has an “other” mechanism to access the data (a low-level language in
this case). That mechanism must not change or harm the data stored in the database. In simple
words, You can’t cheat and make changes using other low-level languages.
Any database that follows EF Codd rules can be considered as RDBMS. Now let me explain
more on RDBMS..

RELATIONAL DATABASE MANAGEMENT SYSTEM


(RDBMS)
A relational database management system ( RDBMS ) is a software application that helps in
creating, designing and managing a “relational database.” RDBMS stores data in a structured
format in tables and manages, accesses, and modifies using SQL.

Nowadays, almost all the DBMS applications are RDBMS. Some of these popular RDBMS are men-
tioned below:

a) Oracle
b) MySQL
c) Microsoft SQL server
d) Postgre SQL
e) IBM DB2

All the RDBMS mentioned above do precisely the same thing – help users and applications to
create, design, and manage a “relational database.” There might be slight differences because of
the different vendors that offer these RDBMS. But on a fundamental level, they all do the same
thing.

45
SIMPLE SQL

I am sure now you understand the difference between a DBMS and RDBMS.
Although I have already mentioned in previous sections, I am still comparing it side by side
to make your understanding better (See, Figure 2.14 for reference).

(Figure 2.14)

After looking at the benefits RDBMS provides, many major corporations developed their
own RDBMS based on the relational model developed by EF Codd.

I have listed below some of the most popular RDBMS currently dominating the data space.

a) Microsoft SQL Server: Developed by the world’s leading software company, Microsoft. It
was launched in 1989 and still is on the top of many companies’ priority lists.
b) MySQL: MySQL is a leading RDBMS and developer’s favorite as it’s open-source and
free.
c) Oracle Database: Developed by oracle corporation and used by leading industries for
secure data management.
d) IBM DB2: Developed by IBM for advanced data management and data analytics
capabilities.
e) PostgreSQL: Another free and open-source RDBMS that is a favourite of developers and
leading corporations.

And the list goes on…


There are hundreds of RDBMS nowadays present in the market today.

46
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

All of them are fundamentally working on the same principles and require SQL to insert, manage
and fetch data from its table. And that’s why mastering SQL is essential.

SQL AND ITS IMPACT


SQL is a query language that was developed to communicate with databases. SQL is an
abbreviation for Structured Query Language and is pronounced as S-Q-L (some people prefer
saying it “sequel”).
SQL is primarily used to insert, update, manage and fetch data from a database. You can also
create tables and databases and delete them using SQL.
Apart from only communicating and managing the databases, SQL has many other advantages.

ADVANTAGES OF SQL
• No complex coding skills required: One of the best advantages of SQL is—less complex-
ity. Unlike other programming languages, SQL is relatively easy.
• Portability: SQL is quite portable and can be used in many different platforms, servers,
and applications.
• Powerful: SQL can handle enormous amounts of data with ease.
• Analyze Data Efficiently: SQL can also generate insights and specific information from a
large dataset.

HISTORY AND BIRTH OF SQL


Just after Boyce published the paper “A Relational Model of Data for Large Shared Data
Banks”.

47
SIMPLE SQL

(Figure 2.15)

Raymond F Boyce and Donald D. Chamberlin started working on developing the first version
of SQL at the IBM research laboratory in San José in the early 1970s.
The name of the first version of SQL was SQUARE ( Specifying QUeries in A Relational
Environment ).
As the first version of SQL was challenging to use, Boyce and Donald started working on
its “sequel” .They thought of naming it as SEQUEL, but it was already trademarked. Therefore
the name was then changed to SQL by dropping the vowels from the earlier proposed name
SEQUEL.
In 1980, ANSI (American National Standards Institute) and ISO adopted SQL and started
working on the standard of SQL. Later on, there were many refinements and improvements on
SQL, and newer and better versions of SQL kept publishing. The most recent refinement was
released in 2016.

48
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

SQL is designed in a way that reads like simple English sentences. Therefore, Anyone who
understands basic English can learn databases concepts quickly and can immediately start work-
ing with SQL.
The primary purpose of the development of SQL was to do four types of fundamental oper-
ations that provide control over data and databases:

CREATE: This operation helps in creating a database and its objects.

READ: This operation helps read the data we have inserted manually or by some applications
in the tables.

UPDATE: This operation helps in updating the data present in tables.

DELETE: This operation helps delete databases, tables, and other database objects.

When you know SQL, you can play with data present in the databases.
Don’t confuse SQL with any other computer programming languages out there. It is not just
a programming language. It’s a “command language” that helps in communicating and manipu-
lating data present in the database.
The purpose of SQL is to “make data useful”. Raw data is not useful until we extract some
useful insight from it.
For example, the information about people visiting a store is of no use until we can identify
what kinds of products are being sold frequently and on which days of the week or maybe which
months of the year.
When we track such important data and derive the required information, the data becomes
useful. And SQL helps in doing that!
Nowadays, every web application and mobile application focuses on gathering customer
behavioral data, their likes, and dislikes. These data points are critical decision-makers for big
companies’ marketing, business, and growth.
With the rise in mobile and web applications, there is an increasing demand for data skills.
As a result, SQL is becoming a rewarding data skill to master.

49
SIMPLE SQL

EXERCISES
Select the correct relationship type between the entities.

1) Mother à Children
a) One To Many
b) Many To Many
c) Many To One
d) None Of The Above

2) Owner à Pets
a) One to Many
b) Many To Many
c) Many To One
d) None Of The Above

3) Husband à Wife
a) One to Many
b) Many To Many
c) One To One
d) None Of The Above

4) Captial à Country
a) One to Many
b) Many To Many
c) One To One
d) None Of The Above

5) Person à PhoneNumbers
a) One to Many
b) Many To Many
c) Many To One
d) None Of The Above

50
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

6) Author à Books
a) One to Many
b) Many To Many
c) Many To One
d) None Of The Above

7) Person à BirthCertificate
a) One to Many
b) Many To Many
c) One To One
d) None Of The Above

8) Which of the following is most suitable to become the primary key of the below table?
Employee ( EmployeeID, FirstName, LastName, Address, Salary)
a) FirstName
b) LastName
c) EmployeeID
d) Address

51
SIMPLE SQL

ANSWERS
1) a) One To Many
2) b) Many To Many
3) c) One To One
4) c) One To One
5) a) One To Many
6) b) Many To Many
7) c) One To One
8) c) EmployeeID

52
SQL
CHAPTER 3

DATACEPTION:
Data, Datatypes and Metadata

I n this chapter, you’ll to learn more about datatype and types of datatypes. Also, you’ll be
exploring about metadata as well in this chapter. When you understand how the data is stored
and what type of data can be stored in tables using SQL. Then you can move ahead and start
exploring and playing with different data. Most people like to quickly start working with the
commands in SQL. Which is not harmful in any way, and you can also do that as well. And to
be honest with you, I learned that way only!

But I believe things would have been much easier if I had focused on understanding the basics
mentioned in this part of the book. All the topics in this section are carefully chosen and hold a
massive value for individuals aspiring to build their careers in the IT industry.

Now, let’s get back to the main topic…

UNDERSTANDING DATATYPES
Till now, you know about relational databases and understand that the best way to store
the data is to store it in tables. The data resides in the columns and rows of tables and is then
accessed using SQL. The data stored in the columns for a particular attribute needs to have spe-
cific datatype based on the type of information the column holds.
Let me explain with an analogy.
suppose you have three buckets; you’re allowed to only store water in bucket 1. In bucket
2, you can only store pebbles, and in the 3rd one, only sand is allowed. Basically, Bucket here
represents the column of a table, and the type of stuff allowed for that bucket is the datatype of
that particular column. ( See, Figure 3.1 for reference)

53
SIMPLE SQL

(Figure 3.1)

Datatypes define the rules about how data is stored in the columns of tables. It increases the
efficiency of how data is stored in tables.

Let me explain.

In the table Student ( refer Figure 2.2 ) The StudentID of students can only have numerical
data , not alphabetical data. Similarly, a student’s name must be of an alphabetical type, not any
other type like numerical. This maintains the quality of data, and when we try to sort and access
data, it becomes more readable and uniform across all applications.

Datatype of a particular column defines what type of data and values a column can contain.
Every programming language has different datatypes to store related data. So you can say it
acts as a category to decide what kind of data will be allowed in that particular data type.
To design tables and other database objects. This is the essential step to do because the kind
of data that will be in columns of tables ensures the data quality, ease of access, and readability.
Based on the type of relational database management system (RDBMS) a developer uses,
only the name and size of a datatype slightly varies. But in most cases it is almost same across
different RDBMS.
Now to understand this concept of the datatype, we will use MS SQL Server datatypes.

54
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

Datatypes are classified into 3 categories:

a) Numeric Datatypes: Numeric datatypes help store values that are in numerical format.
For example: if you want to store values like 1, 234, 11.33, or 24450. You can only store
such values in a column with numeric datatypes.

b) String Datatypes: A datatype that helps store data in text format is known as a string
datatype.
For Example Storing values like Name, City and Location. All these values fall under
string datatype as the format to store these or similar values is in text.

c) Date and Time Datatype: A datatype that is designed to store information related to Date
and Time is called Date and Time datatype.
For Example: Values like Date of birth, Product Purchase Date, or Manufacturing date
fall under this datatype. These categories have multiple datatypes in them. In this book, I
will cover only a few of them to make this book beginner-friendly.

Let’s take the category of numeric datatype first:

NUMERIC DATA TYPES


Numbers are best to quantify information related to an entity, and numeric data types help
us store numbers in a table well. There are many types of numbers in the numeric system, and
SQL can handle and deal with different numbers quickly.
When dealing with numbers in real-life scenarios, numbers might get pretty long and are not
helpful for calculations.

For Example: The pi (π) value is represented as 3.141592654 in calculators and other sys-
tems, not because the values are limited to 10 digits only.

55
SIMPLE SQL

(Figure 3.2)

Therefore, choosing the correct datatype to store the numerical values based on the proper-
ties of the value is quite important.
In SQL, numbers are divided into two parts based on the properties.

Exact Numeric and Approximate Numeric.

(Figure 3.3)

Let me first explain Exact numeric datatype.


Exact numeric datatypes are used to store exact numbers in tables with precision (p) and
scale (s).
Where,
Precision (p) is the total number of digits stored in a column.
In simple words, precision displays as many numbers you want to see in that particular
column.
Whereas scale (s) is the number of digits allowed after the decimal.

56
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

(Figure 3.4)

Below are the different Exact numeric datatypes that are used in SQL to store different types
of values with precision and scale.

• TINYINT
• SMALLINT
• INTEGER
• BIGINT
• NUMERIC
• DECIMAL
• SMALL MONEY
• MONEY
• BIT

TINYINT
TINYINT datatype is best for storing TINY whole number values.
Range in SQL Server: 0 to 255
Storage Space: 1 byte

SMALLINT
The SMALLINT datatype stores SMALL whole numbers.
This datatype must be used for the column when you are already aware of the size of poten-
tial numeric values allowed for this column.
For example, The table of your online test (Test) has a column Student_Score, and the max-
imum number of marks a student can score on that test is that small online test in 10. Then it’s
better to set the column datatype for the scored marks as SMALLINT.
Range for SMALLINT in SQL Server: -32,768 to 32,767
Storage Space for SMALLINT in SQL Server: 2 bytes

57
SIMPLE SQL

INTEGER
Integers are whole numbers of negative, positive, and 0 values. INT is used to store integers
in SQL Server. The INT datatype stores value greater than SMALLINT but lesser than BIGINT.
Range for INT in SQL Server: -2,147,483,648 to 2,147,483,647
Storage space for INT in SQL server: 4 bytes

BIGINT
BIGINT datatype stores whole numbers that are big. This column is better when the data is
bigger in size, and the column with INT datatype can’t handle the data.
Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Storage Space: 8 Bytes

DECIMAL
To store the data with decimal values, the decimal datatype is widely used. While designing
the table, we need to enter the details about how many digits are allowed before and after the
decimal.
In order to do this, the below syntax is used.

Decimal (p,s)

For example: decimal (6,2) will allow total values of 6 (precision) and 2 values after the dec-
imal (scale). This means 1004.44 and 121.23 will be allowed in the column.
But, 1231234.324 can’t be stored in the column that has decimal precision 6 and scale 2.
Whereas when you would have chosen datatype as DECIMAL, the system would have
exceeded the precision to handle large numbers. You can say that decimal has some extra “behind
the scene” storage space for extra digits.
Hence, the system with DECIMAL can even store 12345.5432. For the 2nd value, the system
has utilized its “behind the scene” storage.
Range: -10^38 +1 to 10^38 -1
Storage Space: 5-17 bytes

SMALL MONEY
In SQL Server, Small money datatype is used to store monetary values and is “functionally”
quite similar to the datatype DECIMAL (10,4).
But if we deep digger and check how the data is actually stored on disks, it is stored like an
integer.

58
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

Range for SMALL MONEY datatype: -214,748.3648 to 214,748.3647


Storage Space for SMALL MONEY in SQL Server: 4 bytes

MONEY
MONEY datatype is also a dedicated datatype especially designed to handle currency and
financial values. Moreover, it can handle a broader range of data than SMALL MONEY as it
has 8 bytes of storage.
Range for MONEY datatype: -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Storage Space for MONEY in SQL Server: 8 Bytes

BIT
BIT allows Integer values – 0,1 and NULL. Helpful when we have only 2 possible values for
a column.
Example: A student’s attendance in a class can be represented as either 0 or 1. This will save
some space, instead of entering values like the present or absent in tables, especially when we
have thousands of students.
Range: 0 to 1
Storage space: 1 bit

APPROXIMATE DATA TYPE


The REAL numbers that were difficult to represent using the exact numeric datatype, can be
easily represented using approximate data type. It is best to use this datatype for representing
fractional values.This happens because these REAL numbers are either quite large or too small
to deal with the numeric data type.

The concept of floating-point


Floating-point numbers are numbers that don’t have a fixed decimal point. To understand
this concept easily, you can say that the decimal keeps on “Floating” in floating numbers.

Floating point numbers can represent a wider variety of numbers than the fixed point.
Therefore, scientific values and measurements that are very small must be stored in the
approximate data types.

59
SIMPLE SQL

Let me now explain the different type of Approximate data types in SQL:

a) REAL
b) FLOAT

REAL
REAL datatype in SQL is a single-precision floating number. That means REAL datatype
occupies 32 bits in computer memory.
Range of REAL datatype: -3.40E + 38 to 3.40E + 38
Storage space for REAL datatype: 4 Bytes

FLOAT
FLOAT can handle a wider range as compared to the DECIMAL datatype. Therefore, it is a
good choice if you specify your precision. Unlike REAL, your precision is default and can’t be
changed. Also, It is pretty cost-efficient and saves more space.

The syntax for float is:

float (n)

where n= parameter shows if the field will hold 4 or 8 bytes.


Default value of n= 53.

Range: – 1.79E+308 to 1.79E+308


Storage Space: 4 Bytes

If you have a background in coding, you might already know what a string is. But you have
no experience in coding, knowing what string is quite essential before diving into this concept:
Basically, String in computer programming languages is referred to characters or series of
characters. For example: “How you doin?” and “US12399” are string values as they have a series
of characters.
Now let me explain to you about string datatypes…

60
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

STRING DATATYPES
String datatypes are designed to store alphanumeric or String values in SQL tables.
To understand the concept of String datatypes, we will take SQL Server as our RDBMS, and
the datatypes will be String datatypes from SQL server only. However, these are the standard
datatypes that you will discover among all the top RDBMS.

So, the String datatypes present in the SQL server are mentioned as below:

a) CHAR
b) VARCHAR
c) VARCHAR ( max )

Let me explain each string datatype to you one by one.

CHAR
CHAR datatype in SQL is designed to store alphanumeric values or character values of a
fixed length. If the length of the characters in a string datatype is less than the decided fixed
length, then those extra spaces allocated for it will be padded with “Trailing Blank Spaces.” This
is done to ensure that the length of the string is always the same for all the values present in the
column.

Syntax:
CHAR (n)
Where n means the length of the string

For example: If a column Name of table STUDENTS has the datatype CHAR (6). Then the
total length of the column for both the values “DONALD” and “JOEY” will be 6.
Because for the name JOEY, there will be 2 more spaces will be allocated with blank trailing
spaces by SQL Server. We will be discussing how you can figure out the length of characters using
SQL in the upcoming chapters.
Range for CHAR in SQL Server: 0 to 8000 characters

61
SIMPLE SQL

VARCHAR
VARCHAR datatype is a datatype that has a variable length of the character string. It is
designed to hold values like numbers, characters, and special characters.

Syntax:
VARCHAR (n)
Where n means for the length of the string and not bytes. The default value of n is 1.
For example, if you want a column that can store a string of 7 characters. The datatype
should be VARCHAR (7).
VARCHAR(n) range in SQL Server: 0 to 8000 characters.

VARCHAR (max)
Where (max) in VARCHAR(max) represents the maximum storage size. i.e.—2 GB.
Range for VARCHAR (max) in SQL Server: 0 to 1,073,741,824 characters.
Unlike CHAR datatype, if the string values stored in a VARCHAR datatype are less than the
allocated space. Therefore, no trailing blank spaces will be added after the string value.

For example: when you want to store “JOEY” as a student’s first name, allocate the space for
the field StudentName as VARCHAR(7). The extra 3 spaces will not be replaced with the trailing
spaces as it’s done in the CHAR datatype.

62
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

BINARY DATA TYPES


BINARY (n)
VARBINARY
VARBINARY (max)

BINARY
Binary datatype is a dedicated datatype in SQL to store “Raw Binary Data.” With Raw
binary data, I mean graphic images, files, and media that can’t be stored in a character or numer-
ical format in database tables.
Yes, we store images and media files in the database in BINARY format.
Basically, the pixel is the smallest element of an image, and a binary value represents each
pixel. Below is the format of how an image is represented in binary.

(Figure 3.5)

I hope you now understand how images are stored in the binary format on disks.
Now let me tell you the syntax of the binary datatype.

63
SIMPLE SQL

Syntax:

Binary (n)

Where “n” stands for the length of the binary bytes that will be stored in the column.

In the binary(n) datatype, the length of the binary datatype is fixed, and when binary data
that is LESS THAN the fixed binary data is stored in this data, it is padded.

This behavior of padding extra space is quite similar to CHAR datatype, but instead of padding
it with trailing spaces, it is padded with hexadecimal “00” padding.

NOTE: In SQL Server Management Studio, the binary values are “displayed” in hexadec-
imal format. i.e., It is prefixed with “0x”. That means the SQL server just “displays” the
binary value in the hexadecimal format, NOT changes or manipulates it at a Physical level.

BINARY (5) column can store up to 5 binary bytes of data, and if we try to store data that
is less than this, it will fill up the extra space with “00” in SQL Server.

For example:
The hexadecimal conversion of string JOEY is stored as “4A 4F 45 59”.
And the display of the same string of a BINARY(4) data type column in SQL Server will
be “0x4A4F455”;

And the display of the same string of a BINARY(5) data type column in SQL Server will
be “0x4A4F455900”;

VARBINARY (n)
Varbinary datatype is a datatype that is used to store media file with variable width.

Syntax:
VARBINARY (n)
Where “n” stands for the length of the binary bytes

64
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

VARBINARY (max)
VARBINARY (max) datatype is designed to store media that require large storage space.
VARBINARY(max) is also known as a Binary Large Object (BLOB). The maximum storage
space VARBINARY (max) can have 2 GB.

DATE TIME DATATYPES IN SQL


Date time datatypes in SQL store the values related to date and time with accuracy.
Below are the different DATE TIME datatypes in SQL that we will be discussing in this
section.

DATE
Date datatype is commonly used to store only the “Date”—Day, Month, Year.
However, this datatype is only used for storing dates and not time.
The range for DATE datatype in SQL Server: 0001-01-01 to 9999-12-31.
Storage Space for Date Datatype: 3 bytes.

DATETIME
This datatype is used to store the “Date and Time” values in a column.
Date Range: 1753-01-01 to 9999-12-31
Time Range: 00:00:00 to 23:59:59.997
Storage Space: 8 Bytes
Format of values in DATETIME datatype: “YYYY-MM-DD hh: mm: ss.nnn”

Example: In a column with datetime datatype, below value can be stored easily.

2025-05-21 10:15:30.557

65
SIMPLE SQL

SMALLDATETIME
SMALLDATETIME is a datatype that is used to store the date and time values. The time
values stored in the SMALLDATETIME datatype are in the 24-hour system, with seconds but
without fractional seconds or Nanoseconds.
Date Range: 1900-01-01 to 2079-06-06
Time Range: 00:00 to 23:59
Storage Space: 4 Bytes

DATETIME2
Datetime2 datatype is also a dedicated datatype to store “Date and Time” values in a table.
It is considered an extended version of the datatype DATETIME with higher precision, accuracy,
and bigger size.
Date Range: 0001-01-01 to 9999-12-31
Time Range: 00:00:00 to 23:59:59.9999999
Storage Space: 6-8 Bytes
Format of values in DATETIME datatype: “YYYY-MM-DD hh: mm: ss. [. fractional seconds]”
Example: In a column with datetime2 datatype below values can be stored easily

2025-05-21 10:15:30.5555555

SMALLDATETIME
SMALLDATETIME is a datatype that is used to store the date and time values. The time
values stored in the SMALLDATETIME datatype are in the 24-hour system, with seconds but
without fractional seconds or Nanoseconds.
Date Range: 1900-01-01 to 2079-06-06
Time Range: 00:00 to 23:59
Storage Space: 4 Bytes

DATETIMEOFFSET
DATETIMEOFFSET is a datatype that can hold the date and time values along with “Time zone
offsets.” First, let me explain to you a bit about time zone offset..

66
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

A Time zone is a place in a geographical region where the people residing and traveling
observe the same time.
And Time zone offset is the time by which that time zone is ahead or behind the Universal
coordinated time (UTC).
Now, the datetimeoffset datatype can store the timezone offset values as well.

Syntax:
DATETIMEOFFSET (n)
Where n represents the number of fractional seconds precision.

Format:
YYYY-MM-DD hh:mm:ss[.nnnnnnn] [{+|-}hh:mm]
Where,
YYYY= Year
MM = Month
DD= day
[{+|-}hh:mm] are used to represent offset values.

Example:
2020-12-20 17:20:12.6 +05:30

TIME
A dedicated datatype to store the time in a 24-hour clock-based style.

Syntax:

TIME (n).

Where n is the number of digits that must be allocated to store the fractional part— fractional
second’s scale. The fractional part for TIME datatype can be from 0 to 7.

Format
hh:mm:ss [.nnnnnnn]

67
SIMPLE SQL

METADATA: DATA ABOUT DATA


Now, I hope you know that each entity has some data related to it and how entities are
related to each other in this complex world. Also, I am sure that you know that this data is stored
in tables and database objects in relational databases.
In this section, I want you to understand that the databases also need to store the information
about these objects ( tables, views, etc.) that we create to store information about these entities.
Basically, It’s Data about Data, also known as Metadata.
For Example, An Image is a data that is collected by your phone’s camera. The information
about that image is, the image’s metadata.

(Figure 3.6)

Below are the types of information database stores in a typical metadata:

a) Name of the table (database Object) you created


b) Name of the columns
c) Primary Key columns
d) Foreign Key Column Name
e) Column’s Datatypes
f) Tables size and storage

And some other related information.

68
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

EXERCISES

1) From the below options, What is the best datatype for the value “121454”?
a) Binary
b) Datetime
c) Bit
d) smallint
Answer: 1) a) smallint

2) From the below options, What is the best datatype for the value “112.44”?
a) Decimal
b) Date
c) int
d) Varchar(max)
Answer: 2) a) decimal

3) From the below options, What is the best datatype to represent Present or absent record?
a) datetime
b) bit
c) decimal
d) binary
Answer: 3) b)bit

4) From the below options, What is the best datatype to store FirstName of Students?
a) date
b) bit
c) varchar(n)
d) decimal
Answer: 4) c) varchar(n)

69
SIMPLE SQL

5) From the below options, What is the best datatype to store Product Description of a product
on amazon?
a) varchar(max)
b) decimal
c) integer
d) datetime

Answer: 5) a) varchar(max)

6) From the below options, What is the best datatype to store Large Images and Media files?
a) Bit
b) integer
c) decimal
d) varbinary(max)

Answer: 6) d) varbinary(max)

7) From the below options, What is the best datatype to store date value along with time ( 2022-
03-21 11:23:33.512)
a)datetime
b)int
c)decimal
d)bit

Answer: 7) a) datetime

70
PART 2
GETTING YOUR
HANDS DIRTY
WITH SQL
SQL
CHAPTER 4

INSTALLATION OF
SOFTWARE TOOLS

T his chapter will cover the complete step by step RDBMS software installation.
I know you’re excited to learn SQL fast and do the cool stuff. If you have spent your pre-
cious time learning the foundational topics in part 1 of this book, Your excitement level to learn
SQL might be going through the roof! I would suggest you to wait for a few moments. Once the
software is installed, we will dive deep into SQL.

There are many different types of RDBMS out there, and different companies and projects
use different types of RDBMS based on their requirements, budgets, and features.
All the RDBMS use SQL, so learning SQL and database fundamentals are much more import-
ant than the software/tool we use.
I am using Microsoft SQL Server to teach you SQL in this book. I have worked on many
different RDBMS and found SQL Server easy to understand and operate.
This chapter is all about to installing SQL Server on your system. I will be discussing the step-
by-step installation process that will successfully help you with the installation process.

The installation process will be helpful for the below operating system users:

a) Windows
b) Mac
c) Unix

Choose the section as per your operating system and get the software installation completed
today!

73
SIMPLE SQL

SQL SERVER INSTALLATION FOR WINDOWS


In this section, I will cover the installation of the FREE SQL Server version for windows—
SQL SERVER EXPRESS, step-by-step.
Let’s get started..

1st Step: VISIT Microsoft’s official website to download the official SQL server setup.

https://www.microsoft.com/en-us/sql-server/sql-server-downloads

2nd Step: Scroll down to the middle of the page and find the Developer Icon, under the
download the free specialized section. (See Figure 4.1 a for reference.)

(Figure 4.1 a )

3rd Step: Click on the download now button, and your installation file will be downloaded
soon. Then, locate the installation setup file on your downloaded file section on your PC or
laptop.

74
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

4th Step: Right Click on the installation setup file and then select “run as administrator”
from the options. ( See Figure 4.1 b for reference.)

(Figure 4.1 b)

5th Step: A popup will appear asking you for permission to install SQL Server Express. Press
“YES” to continue the installation process. ( See Figure 4.1 c for reference.)

(Figure 4.1 c)

75
SIMPLE SQL

6th Step: After you click “YES,” a window with three installation types option will pop up.
( See Figure 4.1 d for reference.)

(Figure 4.1 d)

The options will be:

a) Basic: If you select this option Default configuration will be installed quickly. All the
essential features will be there in this installation type.
b) Custom: The custom option allows you to choose some custom settings and features.
c) Download Media: The download media option allows you to download all the essential
files right away. You can then do the installation process later, even without any internet
connection.

For this installation process, I recommend you choose the CUSTOM option. And in this sec-
tion, I will demonstrate the same process to you.
When you select the CUSTOM option, the next step will be..

76
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

7th Step: Select the folder where you want your media files to be downloaded and click
install. ( See Figure 4.1 e for reference.)

(Figure 4.1 e)

77
SIMPLE SQL

8th Step: After clicking install next dialog box will open. This is your “SQL Server Installation
Center”. In this dialog box, click on the “Installation” section.
Then hover to the right side, and click on the “New SQL Server stand-alone installation or
add features… section.” ( See Figure 4.1 f for reference.)

(Figure 4.1 f)

9th Step: Once you click the new installation section, the next window will be opened. This
window is the “Microsoft Update” window. If you want the installation setup, Tick the checkbox
to check for any new updates. ( See Figure 4.1 h for reference.)

(Figure 4.1 h)

78
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

10th Step: Let the installation center setup some updated files. Once this step is completed,
click next. ( See Figure 4.1 i for reference.)

(Figure 4.1 i)

79
SIMPLE SQL

11th Step: Now, the next window (Install rules) will pop up. Make sure all the rules are
“passed” in this window. Make sure you don’t proceed further to the next steps without taking
action to resolve the warnings. Also, make sure there are no failures in the install rules windows.
Once all errors are resolved, click next.

The errors that might appear in this are entirely based on your system settings. For example,
I was getting a port-related issue that I resolved before proceeding to the next step.
If you’re not able to solve these errors and issues on your own, feel free to reach out to our
Facebook community for guidance.

(Figure 4.1 j)

80
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

12th Step: Now, the next dialog box will be installation type. So , as it’s a new installation,
select the option 1 here—“Perform a new installation of SQL Server.” and click next!

13th Step: Now, it will move to the product key section (Figure 4.1 k)); You should select
the FREE option— “specify a free edition.” And click next!
If you have a licensed key, you need to select the second one.

(Figure 4.1 k)

81
SIMPLE SQL

14th Step: The next section is the “licensed terms”. This contains the license, terms of the
agreement, and privacy statement. You can read it and tick the checkbox if you agree.
In case, If you disagree with the Microsoft terms, you have a choice not to select the checkbox
and quit the installation. I agreed to the terms and clicked next.

(Figure 4.1 l)

82
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

15th Step: Once you agree and click next, the next section will be “feature selection.” This
section lets you install various options and features in your SQL Server Management studio-like
database engine services, Machine learning services, Python, R, and whatnot.
As the book’s scope revolves around SQL and Databases, we will go with the option—
“Database engine services.”
Then, click next.

(Figure 4.1 m)

83
SIMPLE SQL

16th Step: You have set up the instance configuration on the next dialog box. In this dialog
box, you have 2 options—default instance and Instance ID.
I have entered this value “Manually” for the instance name and instance ID field in my sys-
tem. i.e., SQL_SERVER. Once done, click “Next.”

(Figure 4.1 n)

84
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

17th Step: The next dialog box is about setting up the server configuration. I have chosen
the default setting for this and recommend you go with the “default settings” only.

Click next and proceed to the next step.

(Figure 4.1 o)

85
SIMPLE SQL

18th Step: In the database engine configuration dialog box. Select “mixed mode” as the
authentication mode. After that, enter the password you want to set.
Then, click on the “Add current user” button. This will make you the administrator of the
SQL Server Management Studio. Then click “Next” to go on to the next step.

(Figure 4.1 p)

86
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

19th Step: Now you have configured most things, and the installation center will present
you the quick summary in the ready to install dialog box. Click install!

(Figure 4.1 q)

87
SIMPLE SQL

20th Step: Check if the installation is going well!

(Figure 4.1 r)

88
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

21st Step: Part 1st of the installation is completed now!

(Figure 4.1 s)

89
SIMPLE SQL

22nd Step: In the 2nd part, we will be installing the Microsoft SQL Server Management
studio. This management studio allows us to view, design, and manage databases.
For that you need to visit the Microsoft official website and download the setup for manage-
ment studio.
https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-
ssms?view=sql-server-ver15
Scroll down a bit and find the “Download SSMS.” Next, click on the Download SQL Server
Management Studio link and download the setup.

(Figure 4.1 t)

23rd Step: Locate the SSMS setup file and then “Right-click” and install it as an administrator.

(Figure 4.1 u)

90
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(Figure 4.1 v)

24th Step: Allow access to the installation setup. Click “YES” to proceed.

(Figure 4.1 w)

91
SIMPLE SQL

25th Step: Locate the folder location where you want to install the files and click the install
button.

(Figure 4.1 x)

26th Step: Setup is now finished!

(Figure 4.1 y)

92
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

Finally, Access Your SQL Server: Now you have installed the SQL Server Management stu-
dio. You can now access the newly installed software on your laptop or PC.
To access the SQL Server, go to the windows start menu search. Start Typing SQL Server
Management Studio. SQL Server Management Studio will pop up in the suggestions.

(Figure 4.1 z)

Click on it or Open it and the SSMS will start.

(Figure 4.2 a)

Now the SSMS will pop up in the dialog box. This will help you to connect with a server.
It will automatically have the server’s name created while you were doing the installation.

In my case, I tried connecting to a server and faced an error. This is because I have not men-
tioned the name of the Instance, I wanted to connect.

93
SIMPLE SQL

In case, you’re also facing the issue (Figure 4.2 b), You can visit this link and follow the steps
to resolve it.

LINK: https://stackoverflow.com/questions/9945409/how-do-i-fix-the-error-named-pipes-provider-
error-40-could-not-open-a-connec

(Figure 4.2 b)

When you’ll try to access the SQL Server, you will get two options to LOG IN. That basically
means you can access SQL server in two ways mentioned as below:

a) Windows Authentication
b) Manually Entering Username and Passwords.

Once all the details are correct, you can connect to the SQL Server and access the databases.

(Figure 4.2 c)

94
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

In the upcoming chapters, You will spend a lot of time in the studio. You will create many
databases and database objects and learn SQL in record time!

SQL SERVER INSTALLATION IN MAC OS


In this section, I will be showing you the STEP-BY-STEP installation of SQL server on a MAC
operating system. Before you begin, make sure you have administrator privileges in your system.
Follow the below steps to install the SQL Server in your MAC OS successfully.
Let’s get started.

PART 1: INSTALLING DOCKER


STEP 1: Install and Configure Docker
To install docker on your system visit the below link :
https://docs.docker.com/desktop/mac/install/
or you can search in google “Docker for MAC” and visit the official docker page. ( See,
Figure 4.4 a for reference)

(Figure 4.3 a)

You can see that there are two options here:

• MAC with an intel chip


• MAC with Apple chip

95
SIMPLE SQL

To select one of them, you must first identify if your MAC has an Intel chip or Apple chip.

(Figure 4.3 b)

Choose and download the file as per your chip. For example, I have intel chip; hence I chose
the option MAC with intel chip.
Then Double click the .dmg file to initiate the process of installation. Once this is done, drag
the docker icon to the application.

(Figure 4.3 c)

96
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

Step 2: Launch Docker


On your MAC ,go to launchpad and click on the docker to launch it.

(Figure 4.3 d)

(Figure 4.3 e)

97
SIMPLE SQL

The system will prompt a dialog box asking for privileged access to the install helper.

(Figure 4.3 f)

Enter your MAC credentials and click install helper.

(Figure 4.3 g)

98
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

After you click install, the Docker engine will start up...

(Figure 4.3 h)

(Figure 4.3 i)

99
SIMPLE SQL

Now, minimize this window and go to the docker icon and select preferences.
On the preferences screen, go and click on the resources tab.

(Figure 4.3 j)

On the resources tab, increase the memory to 4GB. Once you have expanded the memory to
4GB, click Apply & Restart.

(Figure 4.3 k)

100
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

After you’ve made the change in memory and clicked on Apply & Restart, you will see in the
bottom left the color of the icon will be turned from green to amber.Once the docker is restarted
successfully, you’ll see that the bottom left icon will turn green.
You can also verify the current status of docker anytime by clicking the docker icon on the
top.

(Figure 4.3 l)

Now, in the next part I will guide you to install SQL server on MAC.

101
SIMPLE SQL

PART 2: DOWNLOAD AND INSTALL SQL SERVER ON MAC


Step 1: Go To the SEARCH on your Mac and type terminal.

(Figure 4.3 m)

Step 2: Type the below mentioned command to download SQL Server.

docker pull mcr.microsoft.com/mssql/server:2019-latest

(Figure 4.3 n)

Wait until the download is completed.

102
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

Step 3: Type the below command in the terminal to Configure and Run the SQL Server.

docker run -d --name sql_server -e ‘ACCEPT_EULA=Y’ -e

‘SA_PASSWORD=MySuperStrongPassword1’ -p 1433:1433 microsoft/


mssql-server-linux

In the above command,

-d: launches the docker container in the background without opening the window.

--name: set a name for the docker container; in the above command, we are using sql_server
as the name of the docker container.

-e ‘ACCEPT_EULA=Y’ : This part of the above command accepts the user license agree-
ment, where Y means YES.

‘SA_PASSWORD= MySuperStrongPassword1’: This part of the above command helps


to set the password for the database. In this, I have set MySuperStrongPassword1 as the
password for the database. You can set password of your choice in this place.

-p 1433:1433: This part of the command maps the docker container to port 1433.

microsoft/mssql-server-linux : This part of the above command basically selects


the image file for the docker.

(Figure 4.3 n)

(Figure 4.3 o)

103
SIMPLE SQL

Step 4: Verify the status of SQL Server

There are two ways to check the status of SQL Server:

a) The first one is to type the below command on the terminal:

docker ps -a

If the output is ‘Up,’ the SQL Server Container is running.


If the output is ‘Exited,’ the SQL Server is not running.

(Figure 4.3 p)

b) Second way is to click on the docker icon and to the dashboard.

(Figure 4.3 q)

104
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(Figure 4.3 r)

105
SIMPLE SQL

PART 3: AZURE DATA STUDIO INSTALLATION


At this point, I am expecting that you have already downloaded the SQL Server into your
system. However, to access SQL Server to create and execute queries, you need a management
tool with a graphical user interface.
For this, we can use Azure data studio on MAC.

STEP 1: Download Azure Data Studio


To download the setup file for azure data studio, visit the below link:

https://docs.microsoft.com/en-us/sql/azure-data-studio/download-azure-data-studio?
view=sql-erver-ver15

scroll down a bit, click and download the azure data studio .zip file.

(Figure 4.3 s)

Step 2: Install Azure Data Studio


In some time, the .zip file will be available in the Downloads folder of your system. Now,
open the .zip file and find the azure data studio application (Azure Data Studio.app).
Then, Drag and drop it into the application folder.

106
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(Figure 4.3 t)

(Figure 4.3 u)

107
SIMPLE SQL

Step 3: Launch the azure data studio


Go to the launchpad, click on the azure data studio icon to launch the application.

(Figure 4.3 v)

The system might ask you if you’re sure to open the application. Click “open” if you want to
proceed further.
Azure data studio will start running.

(Figure 4.3 w)

108
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

Step 4: Connect with SQL Server

In order to establish a new connection with SQL Server from azure data studio, Go and click
on the “New Connection”.

After that, enter the connection details.

Server: <localhost>
Authentication Type: SQL Login
User Name: sa
Password: MySuperStrongPassword1
Database Name: <DEFAULT>
Server Group: <DEFAULT>

(Figure 4.3 x)

So finally, you are now connected to SQL Server on your MAC OS.
In the upcoming chapters, you will study how to work on SQL Server.
So be ready to get your hands dirty with SQL.

109
SQL
CHAPTER 5

MASTERING SQL QUERIES

I believe you have now installed SQL server on your system and are ready to work on SQL
Server. In this chapter, I will explain to you about SQL queries, the syntax of SQL queries, and
how to design queries. Also, you’ll be creating a table in a database using SQL statements.
Let’s get started…

SQL QUERIES, STATEMENTS, and CLAUSES


A SQL Query in a database is a statement to extract the desired information. It can be con-
sidered a request or question to ask the database to access the desired information.
It is pretty similar to asking a question to google and expecting a relevant and appropriate
answer.

(Figure 5.1)

For example, With the help of a query, you can ask the Database ‘what’s the phone number
of Joey?’ and the Database will answer!
To communicate and ask questions to a database, a standard ,and structured language (SQL)
is used. SQL is a language that helps communicate and manipulate databases. SQL queries and
statements are pretty easy to write, as most of it is like writing a simple English statement. It has
a standard syntax that helps us design the command that allows communicating and manipulat-
ing the data in database tables.

111
SIMPLE SQL

NUT AND BOLTS OF SQL STATEMENTS


I hope till now you understand the scope and usage of SQL. Now, in this section, I will pres-
ent different types SQL statements that we will be using frequently.

As I mentioned earlier, In SQL, whenever we want to do some operation, we just need to write
our statements in the SQL server and we can expect the desired result. The only thing we need to
keep in mind is —the SQL statements that we are writing is in proper syntax.

For example: Suppose we have a table of employees (TableEmployee).

(Figure 5.2)

If you want to extract the only first name, Last name, and EmailID of employees from the
table employee.You need to execute a SQL statement that will help you extract these columns
and, these types of SQL statements are known as SQL queries.
So to get the desired results you need to execute the below SQL Query in the database to get
the desired results

SELECT FirstName,LastName,EmailID
FROM TableEmployee;

You can see in Figure 5.3, after I executed this SQL Statement in database.

112
CHAPTER 5 - MASTERING SQL QUERIES

(Figure 5.3)

The above statement has the following components that make it an effective SQL statement.

KEYWORDS
In SQL statements, Keywords are the predefined and reserved words. There are many key-
words are present in SQL, and each keyword contributes to constructing a SQL Statement.
In the above SQL Query, SELECT and FROM are keywords.
Where SELECT displays the data column you wish to extract and, FROM helps to guide from
where the data needs to be extracted.

CLAUSES
A SQL clause is a meaningful part of a SQL statement that using reserved SQL keywords to
construct an effective SQL statement. From the above SQL Query, let me explain the two clauses
that are involved in the creation of this SQL query:

SELECT FirstName,LastName, PhoneNumber à This 1st clause in the above statement is


known as SELECT clause and uses SELECT keyword.

FROM TableEmployee à This is the FROM clause, 2nd clause in the above statement and uses
FROM keyword.

(Figure 5.4)

113
SIMPLE SQL

Also, This SQL statement uses the SELECT keyword in its first clause, Hence it is also known
as a SELECT statement.
So, a SQL Statement is a statement you design to carry out an operation in the database. These
operations can be anything starting from extracting the desired dataset (Using SQL Queries),
Creating Databases, Creating and Deleting Tables, and much more.
To work with data in the database tables efficiently, each operation is categorized into differ-
ent categories based on the nature of the operation.
There are five categories based on the type of operations a SQL command can perform.

Below are the five different categories of a SQL command:

a) Data Definition Language (DDL)


b) Data Manipulation Language (DML)
c) Data Query Language (DQL)
d) Data Control Language (DCL)
e) Transaction Control Language (TCL)

(Figure 5.5)

Let me explain about each category in detail.

114
CHAPTER 5 - MASTERING SQL QUERIES

DATA DEFINITION LANGUAGE (DDL)


SQL commands are used to define, create and modify the structure of a database and its
objects are classified as Data definition language.

Below are the commands that come under the DDL category:

CREATE: CREATE command falls under the DDL category as it helps in CREATING
database and database objects (Tables, Views, Indexes, etc.)

ALTER: ALTER command helps change and modify the already created database struc-
ture and objects.

DROP: DROP Command is used to delete already created database objects.

TRUNCATE: The TRUNCATE command deletes all the rows and data in a table in one go.

DATA MANIPULATION LANGUAGE (DML)


Data Manipulation Language (DML) comprises commands that help insert, manipulate,
modify, and delete data in tables.

Below are the commands that come under the DML category:

INSERT: INSERT command is used to insert records or rows into a database table.

UPDATE: The purpose of the UPDATE command is to update or modify the existing data present
in the table.

DELETE: The purpose of the DELETE command is to delete one or more rows from the table.

DATA QUERY LANGUAGE (DQL)


Data Query Language ( DQL) is the category in SQL with a command to retrieve data from the
database. DQL has only one command—SELECT; This command does the fetching the data.

SELECT
The SELECT command helps in retrieving data from a table. You can also use this command
with different clauses to filter out the results you want to extract based on the condition you
mention in the SQL statement.

115
SIMPLE SQL

SELECT is the most used command. This command uses different conditions to filter out
records and play with data. So, I suggest you focus a bit more on this particular command.

DATA CONTROL LANGUAGE (DCL)


Data Control Language ( DCL ) category has the commands used to control a user’s access, per-
missions, and rights in a database.

In simple words, DCL commands help distribute and revoke the user responsibilities. Suppose
you want a specific user only to view data present in a table and restrict that user from making
any changes. You can do that using DCL commands by giving only SELECT privilege to the user
and not giving users DELETE or INSERT privilege.

Below are the commands that come under DCL:

a) GRANT: GRANT command is used to give certain privileges to a user.


b) REVOKE: REVOKE command is used to take back the privileges from a user.

UNDERSTANDING PRIVILEGES
Privileges are basically the “rights” given to a user to access a database object or per-
form some action in a database.
For example: In a restaurant, the customer does not have the privilege to access the
kitchen. However, the customer has the privilege of visiting the restaurant, sitting on the
couch, and making an order.
When a user has a specific privilege, then only that user can do the task for which the
privilege is assigned.
In SQL, there are two different types of privileges:

a) SYSTEM PRIVILEGES
b) OBJECT PRIVILEGES

116
CHAPTER 5 - MASTERING SQL QUERIES

SYSTEM PRIVILEGES:
System privileges are privileges given to users to create and modify a database and its
objects. The system privileges that can be granted to a user are:

CREATE: Users with the CREATE privilege can CREATE database objects and execute
CREATE commands.
Without this privilege, even if the user executes the CREATE command, the system will
not create anything and throw an error.

ALTER: Users with ALTER privilege can execute ALTER command and change the
structure of the database and its objects.

DROP: Users with DROP privilege can execute the DROP command and destroy a data-
base and its objects. Executing the DROP command destroys the structure of the database
objects completely. Therefore, it is advised to execute the command carefully, especially
while working on live projects.

OBJECT PRIVILEGES:
Object privileges can be provided to a user to view and make changes in the data. The
object privileges that can be granted to a user are:

SELECT: user with this privilege can fetch the desired records from a table.

INSERT: Users with this privilege can execute the insert command and then insert data
in a table. Without INSERT privilege, the user will not be able to insert data into a table.

UPDATE: A user with UPDATE privileges can execute the UPDATE command and mod-
ify the ex-isting values in a table.

DELETE: Users with DELETE privileges can execute the DELETE command and DELETE
the ex-isting records present in a table.

117
SIMPLE SQL

TRANSACTION CONTROL LANGUAGE (TCL)


In live projects, applications and users constantly extract, load, and modify data. For exam-
ple, if we talk about a mobile banking application, A customer might be transferring their money,
receiving money, and sometimes updating their details on the mobile application.
All these activities are constantly manipulating the data in the database tables. The banking
application is executing many DML commands.
Transaction Control Language manages these DML operations effectively. The commands
that are used in the Transaction Control Language are:

COMMIT:
The COMMIT command saves transactional data permanently in a database. The transactions
and changes made are solidified when the COMMIT command is executed in a database.
If there is no COMMIT between multiple transactions, then there are high chances that the
data can get lost between multiple transactions and never get stored permanently in the database
tables.

Syntax:
COMMIT;

SAVE TRANSACTION:
SAVE TRANSACTION command temporarily saves transactional data in a database. This
command also helps ensure that the changes in the data by the DML are not lost in between two
consecutive SAVEPOINTS.

Syntax:
SAVE TRANSACTION Name_Of_Savepoint

ROLLBACK:
The purpose of the ROLLBACK command is to restore the database to the last point of the
COMMIT or SAVEPOINT state.
Suppose you are executing multiple DELETE statements and by mistake DELETED the wrong
record before committing. Then you can ROLLBACK to the last point of COMMIT or SAVEPOINT.

Syntax:
ROLLBACK TRANSACTION Name_Of_Savepoint;

118
CHAPTER 5 - MASTERING SQL QUERIES

I tried my best not to make the SQL statements daunting for you in this chapter. All the SQL
Statements mentioned in this chapter are beginner-friendly and easy to implement. However, I
recommend you go through the exercises given at the end of this chapter to understand different
SQL statements.
Things will get a little bit advanced in the upcoming chapters, and these DDL, DML, and
DQL statements will be much more sophisticated.

PRACTICING SQL COMMANDS

CREATING SIMPLE DATABASES AND DATABASE OBJECTS


WITH DDL
I hope you understood the SQL commands and the different categories of the SQL com-
mands until now. I have presented most of the foundational concepts, and now, in this section,
You and I will use these commands to create simple database and its objects together!
While developing a database, clarity about the real-world conceptual system is essential.
All this starts from identifying the entities, attributes, and relationships between those entities
and building an ER model for that.
Once the ER model is constructed, we can create the tables with appropriate attributes and
relationships. All these relationships are then converted into a normalized relational model, and
then SQL is finally used to CREATE everything!
Let’s take the example of the simple online e-commerce model that we worked on in the
foundational chapters.

We will be doing the below tasks for the e-commerce model using SQL:

a) Creating a simple Database in SQL server


b) Creating tables for entities
c) Inserting data in the tables
d) Viewing all the data of the tables.
e) Updating data in the tables
f) Deleting data from tables

Lets get started then..

119
SIMPLE SQL

CREATING A SIMPLE DATABASE IN SQL SERVER


To create a simple database, we need to use the below syntax to create a simple database in
the SQL server.

Syntax: CREATE DATABASE DatabaseName ;


Where, DatabaseName = Name of your Database.

Lets try to do it practically..

Step 1: Open SQL Server

Step 2: Connect to your local server with windows authentication

(Figure 5.6 a)

120
CHAPTER 5 - MASTERING SQL QUERIES

Step 3: Right Click on the server and click on “New Query”

(Figure 5.6 b)

Step 4: Creating the database by executing the below command in SQL server with the name
MyEcommerceDB.

CREATE DATABASE MyEcommerceDB ;

Step 5: Exploring the newly created database by going to the object explorer, expanding the
database section, and seeing your newly created database!

(Figure 5.6 c)

121
SIMPLE SQL

If you don’t see the database, you just created, click on the Object Explorer Refresh button
and again check in the database section.

CREATING TABLES FOR ENTITIES


To create tables in a database, we first need to identify the entities present in the model. For
example: in the e-commerce model, we can have many entities, but we will only consider a few
of them.

The entities that we will be considered for this scenario are:

• Products
• Seller
• Customer
• Orders

The columns with their respective datatypes are mentioned as below:

Product:
ProductId INT
ProductName VARCHAR (20)
ProductPrice DECIMAL (10,4)
OrderID INT
SellerID INT
ProductCategory VARCHAR (20)

Sellers:
SellerID INT(10)
SellerName VARCHAR (20)
ProductID INT(10)
SellerLocation VARCHAR (20)
SellerCategory VARCHAR (20)

122
CHAPTER 5 - MASTERING SQL QUERIES

Customers:
CustomerId INT
FirstName VARCHAR (20)
LastName VARCHAR (20)
Address VARCHAR (30)
Contact VARCHAR (20)
Email VARCHAR (50)
OrderID INT

Orders:
OrderID INT
OrderDate DATE
ProductID INT
CustomerID INT
SellerID INT
DeliveryLocation VARCHAR (30)

If you don’t understand the rationale behind selecting the datatype of the columns for the
above tables. You might want to check the chapter on datatypes in part 1 of this book. But if you
understand the reason behind choosing the datatypes, then my friend you’re on the right track.
Now let’s create tables for each entity one by one, using the CREATE TABLE command.
To create a table, you need to create SQL statements for each entity using the below syntax.

CREATE TABLE TableName


(
COLUMN_NUMBER1 DATATYPE ,
COLUMN_NUMBER2 DATATYPE,
COLUMN_NUMBER3 DATATYPE,
..
..
..
..
);

123
SIMPLE SQL

EXECUTION ; CREATING SIMPLE TABLES FOR THE E-COMMERCE MODEL


STEP 1:
Go to the e-commerce Database that you created earlier.

STEP 2:
Right Click the “MyEcommerce” and Select “New Query”

STEP 3:
Based on the above-mentioned create table syntax, create SQL statements for each table.
Execute below SQL statements one by one for each table:

For Products table:

CREATE TABLE Products


(
ProductId INT PRIMARY KEY,
ProductName VARCHAR (20),
ProductPrice DECIMAL (10,4),
OrderID INT,
SellerID INT,
ProductCategory VARCHAR (20)
);

Copy and paste the above SQL Statement in your SQL Server to a products table. ( See Figure
5.7 for reference)

124
CHAPTER 5 - MASTERING SQL QUERIES

(Figure 5.7 )

Now, Execute the SQL Statement.


The above SQL statement will create a simple table with a primary key column ProductId (
Primary Key) and other columns with respective datatypes.

For Sellers table:

To create a seller table, using the create table syntax, the SQL statement will be:

CREATE TABLE Sellers


(
SellerID INT,
SellerName VARCHAR (20),
ProductID INT,
SellerLocation VARCHAR(20),
SellerCategory VARCHAR(20)
);

Copy and paste the above SQL Statement in your SQL server to create the Sellers table.

125
SIMPLE SQL

Then, Simply execute the SQL Statement.

For Customers table:

In order to create Customer table, using the create table syntax the SQL statement will be:

CREATE TABLE Customers


(
CustomerId INT PRIMARY KEY,
FirstName VARCHAR(20),
LastName VARCHAR(20),
CustomerAddress VARCHAR(100),
Contact VARCHAR(20),
Email VARCHAR(50),
OrderID INT
);

Then, Simply execute the SQL Statement.

For Orders table:


In order to create Orders table, using the create table syntax the SQL statement will be:

CREATE TABLE Orders


(
OrderID INT PRIMARY KEY,
OrderDate DATE,
ProductID INT,
CustomerID INT,
SellerID INT ,
DeliveryLocation VARCHAR(100),
);

126
CHAPTER 5 - MASTERING SQL QUERIES

Now, Execute the SQL Statement.


After we create a database and objects with the DDL statements, the next step is to insert
data and view the data we inserted in each table.

INSERTING AND VIEWING DATA


Inserting data in tables uses the insert command in SQL and falls under Data Manipulation
Language (DML) category in SQL.
The syntax used for INSERTing data in a table is:

INSERT INTO TableName


(
COLUMN_NUMBER1,
COLUMN_NUMBER2,
COLUMN_NUMBER3,
..
..
..
)
VALUES
(
VALUE1,
VALUE2,
VALUE3,
..
..
..
);

FETCHING RECORDS FROM A TABLE


Viewing the data present in the table uses the SELECT command and falls under the Data
Query Language category in SQL.
The syntax for a simple SQL SELECT statement is:

SELECT COLUMN_NUMBER1, COLUMN_NUMBER2, COLUMN_NUMBER3 ...


FROM TableName;

127
SIMPLE SQL

In the above SQL SELECT statement or SQL Query, you only need to mention the columns
you wish to see the results. Suppose you only want to see the results for COLUMN_NUMBER1 and
COLUMN_NUMBER3, then the SQL SELECT Statement will be as below:

SELECT COLUMN_NUMBER1, COLUMN_NUMBER3


FROM TableName;

If you wish to SELECT ALL THE COLUMNS, use the syntax below.

SELECT * FROM TableName;

Where * means all the columns present in the table.

Example: SELECT * FROM Sellers;

Now let’s do some practice to understand the concept at a much deeper level.
Let’s INSERT some dummy data in all 4 tables in our simple e-commerce model.

FETCHING A SINGLE RECORD FROM A TABLE


If you wish to SELECT ALL COLUMNS of a particular record, use the syntax below.

SELECT * FROM TableName WHERE Condition;

Here the above SQL statement will only return all the records from the Table, Only when it
meets a condition that is mentioned after the WHERE keyword .
The system will look for the records that satisfy the condition mentioned after the WHERE
keyword.

Example: SELECT * FROM Sellers WHERE SellerID=’44444’;

In the above example, The query will return all the columns from the seller table for the
record that has SellerID=’44444’;

128
CHAPTER 5 - MASTERING SQL QUERIES

EXECUTION: INSERT DATA IN CUSTOMER TABLE


To insert data in the customer table, we can use the INSERT command.
Let’s try to insert some data into the customer table with the help of the INSERT command.
Whenever you’re inserting data, always make sure that you’re entering the appropriate datatype
for each value for their respective column.

I used the below SQL Statement to insert data in the table customer:

INSERT INTO Customers


(CustomerID,FirstName,LastName,CustomerAddress,Contact,
Email,OrderID)
VALUES
(‘111’,’Joey’,’Trib’,’Rose Apartment,Jackson Street,New York’,
’+1 630 323 4064’,’Joey.Trib007@gmail’,’0001’);

(Figure 5.8 a)

Also, Make sure in the SQL statement the “number” of values you enter is exactly the same
as the columns you mentioned in the statement.

For example: if I created a SQL statement and mentioned all 7 columns for the customer
table and then tried to enter data or values for only 4 rows. Then the system will throw an error.
(See, Figure 5.8 b for reference)

Let me show it to you, by entering lesser values in the INSERT statement:

INSERT INTO Customers


(CustomerID,FirstName,LastName,CustomerAddress,Contact,Email,OrderID)
VALUES
(‘111’,’Chandler’,’B’,’Rose Apartment,Jackson Street,New York’);

129
SIMPLE SQL

(Figure 5.8 b)

The system throws an error! ( See , Figure 5.8 b for reference )


But when I put the correct number of values in the INSERT SQL Statement, the data will be
inserted smoothly. (See, Figure 5.8 c for reference)

(Figure 5.8 c)

Now, we will be viewing the data that we inserted in the customer table using the SELECT
statement. Let’s now first extract all the data from the Customer table using the below SQL
Query:

SELECT * FROM Customers;

(Figure 5.8 d)

130
CHAPTER 5 - MASTERING SQL QUERIES

Now, Let’s retrieve data for specific columns (CustomerID, FirstName, LastName,
Contact, and Email ) from the table Customers.

SELECT CustomerID,FirstName,LastName,Contact,Email
FROM Customers;

(Figure 5.8 e)

Similarly, we can INSERT and RETRIEVE data using SQL Statements for the rest of the
tables.

EXECUTION: INSERTING DATA IN ORDERS TABLE


This time we will be inserting two rows in one go!
This will be done in the same query editor, and the SQL statements will be written one after
another. The system will identify the end of the first SQL statement when it encounters the first
semicolon (;) after the 1st statement.

The SQL statements that I will use to insert data rows are:

INSERT INTO Orders (OrderID,OrderDate,ProductID,CustomerID,SellerID,


DeliveryLocation)
VALUES (‘0001’,’2021-08-01’,’4904’,’112’,’11111’,’Rose Apartment,
Jackson Street,New York’);

INSERT INTO Orders (OrderID,OrderDate,ProductID,CustomerID,SellerID,


DeliveryLocation)
VALUES (‘0002’,’2021-03-07’,’4711’,’111’,’66666’,’Rose Apartment,
Jackson Street,New York’);

131
SIMPLE SQL

Now let’s retrieve all the inserted data from the Order Table.

SELECT *
FROM Orders;

EXECUTION: INSERTING DATA IN PRODUCTS TABLE

INSERT INTO Products (ProductId,ProductName,ProductPrice,OrderID,SellerID,


ProductCategory)
VALUES (‘4904’,’Recliner Chair’,’267.55’,’0001’,’11111’,’Living Room Chairs’ );

INSERT INTO Products


(ProductId,ProductName,ProductPrice,OrderID,SellerID,ProductCategory)
VALUES (‘4711’,’Outdoor Pizza Oven’,’324.99’,’0002’,’66666’,
’Outdoor Ovens’ );

INSERT INTO Products


(ProductId,ProductName,ProductPrice,OrderID,SellerID,ProductCategory)
VALUES (‘4244’,’SQL Mastery Book’,’31.55’,NULL,’44444’,
’Database Management’ );

You can observe that in the third record, I have inserted the NULL value for OrderID. The
OrderID inserted is NULL because there is no order yet made for this product; therefore, there
is no value assigned for the column OrderID.
Then I Executed the above SQL Statements in the MyEcommerceDB Database.
Using the below query, I displayed all the data for the table products.

SELECT * FROM Products;

132
CHAPTER 5 - MASTERING SQL QUERIES

EXECUTION: INSERTING DATA in Sellers table


INSERT INTO Sellers (SellerID,SellerName,ProductID,SellerLocation,SellerCategory)
VALUES (‘11111’,’Akasa Furnitures LLC’,’4904’,’Denver’,’Furnitures’);

INSERT INTO Sellers (SellerID,SellerName,ProductID,SellerLocation,SellerCategory)


VALUES (‘44444’,’Dataceps LLC’,’4244’,’Chicago’,’Books’);

INSERT INTO Sellers (SellerID,SellerName,ProductID,SellerLocation,SellerCategory)


VALUES (‘66666’,’Homecare LLC’,’4711’,’Boston’,’Kitchen Appliances’);

Now, After executing the below query ,We can display data from Sellers Table

SELECT * FROM Sellers;

The above examples of different SQL Statements that we used are the simplest way to insert
data in SQL tables and retrieve columns from the other SQL tables.

UPDATING DATA IN A TABLE WITH SQL STATEMENTS


I am pretty sure that till now, you have understood how to insert records in a table and
retrieve data from a table.
But in real-life scenarios, a database gets updated with new values quite frequently.

For example: Increased or decreased product prices, Product Sold to a customer ,etc.
Such events create updates in the database, and to that, we need to use UPDATE SQL
Statements.

The syntax for UPDATing a particular record is:

UPDATE TableName
SET COLUMN_NUMBER1 = VALUE1,
COLUMN_NUMBER2 = VALUE2,
COLUMN_NUMBER3= VALUE3,
..
..
..
WHERE CONDITION;

133
SIMPLE SQL

The above SQL Statement will only update the record where it satisfies the condition men-
tioned in the WHERE clause.
Let’s do some practical stuff now...

EXECUTION: UPDATING DATA IN TABLE


Consider the same e-commerce model; what if the customer ‘Chandler’ moves to a new
apartment in the same city and updated their address on the e-commerce website to ensure the
following orders will be delivered to his new address.
Now, the new address is: “111, Maspeth Ave, New York”
This update in the address of an existing record requires running an UPDATE SQL Statement
in the database table. To update this record, we will be using the below SQL Statement:

UPDATE Customers
SET CustomerAddress=’111 , Maspeth Ave, New York’
WHERE CustomerId =’112’;

The above query will only update the record to where it satisfies the condition CustomerId
=’112’. And as the column CustomerId is a unique primary key, there will only be one record
for which the value of the address will be updated.

You can see the results after executing the UPDATE statement in Figure 5.8 g.

(Figure 5.8 f)

Executed the UPDATE Query and then retrieved the results.

134
CHAPTER 5 - MASTERING SQL QUERIES

(Figure 5.8 g)

As you can see, the value for the CustomerAddress column is now updated!
This is how records and data are updated using UPDATE SQL Statements, and hence it is
categorized in the Data Manipulation Language category in SQL.

DELETING DATA FROM TABLES USING SQL STATEMENTS


Sometimes, when working in a database, incorrect records or data get inserted, or some
records become unnecessary or irrelevant. In such cases, deleting the records or data from the
tables seem the right thing to do.
To understand this, Let’s again take the example of our E-commerce model.
Suppose the seller ‘Homecare LLC’ decides to launch their new product (Smoothie Blender)
on the e-commerce website.
And after a few months, the seller realized that there were no sales for the product. Therefore,
he decided to take it down from the website and its database.

In that case, there will be below operations will be happening on the database tables:

a) Insert a new record for the new product in the product table
b) Delete the record for the new product.

First, Let’s add a new record to the product table...

INSERT INTO Products


(ProductId,ProductName,ProductPrice,OrderID,SellerID,ProductCategory)
VALUES (‘4444’,’Smoothie Blender’,’33.74’,NULL,’11111’,’Kitchen & Dining’ );

In the above SQL statement, the value for OrderID is set as NULL because there is no order
made for this product yet.

135
SIMPLE SQL

Now the 2nd Operation, as per the scenario mentioned above, is to delete the record from
the table.
Use the below-mentioned SQL Statement to delete the record inserted in the table.

DELETE FROM Products


WHERE ProductId=’4444’;

(Figure 5.8 h)

(Figure 5.8 i)

So this is how we use different DDL, DML, and DQL statements and do multiple operations
in the database.

136
CHAPTER 5 - MASTERING SQL QUERIES

EXERCISES

1) From the below options, Which SQL statement is the most suitable to extract data from the
tables?
a) SELECT
b) TRUNCATE
c) DELETE
d) INSERT

2) Which SQL statement is the most suitable to INSERT data in a table?


a) TRUCATE
b) DELETE
c) UPDATE
d) INSERT

3) Which SQL statement is the most suitable to UPDATE data in a table?


a) UPDATE
b) INSERT
c) DELETE
d) SELECT

4) Which SQL statement is most suitable to DELETE records from a table?


a) SELECT
b) UPDATE
c) INSERT
d) DELETE

5) Create SQL statements for each scenario


a) Create a new database with name it as DatacepsNewDB.
b) Create a new table with name ‘Students’ in the ‘DatacepsNewDB’ with below mentioned
columns and datatypes.
i) StudentID ( int)
ii) StudentName (varchar (50) )
iii) StudentAddress ( varchar (255))
iv) StudentAge ( int)

137
SIMPLE SQL

6) Insert the below mentioned 3 records in the Students table


Record 1: ‘111’,’Jakie’,’Blossom Apartment,William Street,New York’,24
Record 2: ‘112’,’Billy’,’New Ridge Apartments,Jackson Street,New York’,22
Record 3: ‘113’,’Jakie’,’House No:112,St Mary Street, New Jersy’,32

7) Display only the StudentName and StudentAddress columns from Students table

138
CHAPTER 5 - MASTERING SQL QUERIES

ANSWERS
1) a) SELECT
2) d) INSERT
3) a) INSERT
4) d) DELETE
5) a) CREATE DATABASE DatacepsNewDB;
5) b)
USE DatacepsNewDB

CREATE TABLE Students


(
StudentID int,
StudentName varchar (50),
StudentAddress varchar (255),
StudentAge int
);

5 c)
INSERT INTO Students( StudentID,StudentName,
StudentAddress,StudentAge)
VALUES (‘111’,’Jakie’,’Blossom Apartment,William Street,New York’,’24’);
INSERT INTO Students( StudentID,StudentName,
StudentAddress,StudentAge)
VALUES (‘112’,’Billy’,’New Ridge Apartments,Jackson Street,New York’,’22’);
INSERT INTO Students( StudentID,StudentName,
StudentAddress,StudentAge)
VALUES (‘113’,’Jakie’,’House No:112,St Mary Street, New Jersy’,’32’);

5 d)
SELECT StudentName,StudentAddress FROM Students;

139
SQL
CHAPTER 6

UNDERSTANDING
TABLES IN DEPTH

I n the previous chapter, I explained to you that creating tables comes under the category of
Data Definition Language commands in SQL. You also learned to Create simple tables in the
last chapter.

In this chapter, you will be leveling up your game! In addition, you will be learning much
more advanced stuff about creating tables. This chapter will include in-depth detailed knowledge
about table constraints, inserting, updating, and deleting data in tables!

So, without wasting much of your time, Let’s get started.

DESIGNING AND CREATING TABLES


In the previous chapter, I discussed the basics of designing and building simple tables with
one primary key and a few columns to store data. In this section, I discuss about creating tables
that can be used in advanced relational models and live projects.
As you already know, tables in relational models are related based on their column values
through primary and foreign key relationships. Also, a few columns can have NULL values,
whereas a some columns don’t allow any NULL values. There are many rules that define what
kind of values a table can store in it. And these rules are known as constraints of a table.
All this information related to a table needs to be mentioned while designing and creating
the tables. These relationships and constraints can only be identified when the entities and the
data that need to be inserted are identified way before creating SQL statements for the creation
of tables.

A typical process of creating relational tables looks something like this:

Identifying Entities à Identifying Attributes à Identifying the key attributes à Identifying


Relationships and Constraints àCreating Tables Using SQL Statements.

141
SIMPLE SQL

(Figure 6.1)

Now let me explain each part of the process one by one to you.

STEP 1: IDENTIFYING ENTITIES


In this phase of creating a table, brainstorming helps identify the proper entities present in the
system. In the foundational chapters of this book, I have already shared how to identify entities
of a system while creating ER diagrams for a system.

STEP 2: IDENTIFYING ATTRIBUTES


After you have identified the entities, all the potential attributes need to be identified in that
entity. For example: suppose you have identified a “Student” as an entity.

142
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

Then the potential attributes for that entity are:

• StudentID
• StudentName
• StudentAddress
• StudentAge

The list can go much bigger than this. The bigger the model gets, the bigger the list of attri-
butes becomes.

STEP 3: IDENTIFYING THE KEYS ATTRIBUTES


The next step is identifying the key attributes and constraints you want for your table.

Once all the potential attributes are identified for the table, we are creating. Then you must
specify the different key attributes that can be present in that table. The two identified entities
we have for this are Student and Courses.

The entity Student table has attributes like:

• StudentID
• StudentName
• StudentAddress
• StudentAge

For the above entity, the key attribute is StudentID.

The entity Courses table has the below attributes that I have identified:

• CourseID
• CourseName
• CourseCreationDate
• CourseDescription

For the above entity, the key attribute is CourseID.

143
SIMPLE SQL

STEP 4: IDENTIFYING THE CONSTRAINTS


Once the key attributes are identified, we can start identifying the constraints we want to
select for the table that we want to create.

To identify the proper constraint, first let me explain what SQL constraints are.

SQL constraints : SQL Constraints can be considered rules implemented on a column of a


table. These rules help limit the type of data inserted in the column.

If the data satisfies the constraint rule, it will be allowed to enter the table as a row. Else it
will be discarded. Usually, the constraint on a column is added while creating the table. But it can
also be added after the table is already created.
The primary purpose of SQL constraints is to maintain integrity and accuracy in a database.

Below mentioned constraints are the most commonly used:

NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
DEFAULT
CHECK

Let’s discuss each constraint one by one..

NOT NULL Constraint


A NOT NULL Constraint is a constraint that helps in preventing a column from having NULL
values.
It ensures that any column with a NOT NULL constraint can never have a NULL value. Even
If we try to insert a NULL value for the column with NOT NULL constraint, a NULL value will
never be inserted in the table.
The default programming of columns is to allow columns to store NULL values. Therefore, it
is essential to explicitly declare the NOT NULL columns while creating tables.

For example:
Let’s create a table in the e-commerce database with NOT NULL Constraint on a column.
Then we will try to insert both NULL and NOT NULL values in the column with NOT NULL
constraint.

144
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

Creating a table with NOT NULL constraint.

STEP 1: Open the ‘MyEcommerce’ database, right-click and click on the new query.

STEP 2: CREATE a simple table with NOT NULL constraint


Execute the below SQL CREATE statement in the editor to create a table with NOT NULL
constraints on one column.

CREATE TABLE TestingTableNotNull


(
CustomerID INT NOT NULL,
FirstName VARCHAR(30),
LastName VARCHAR(30)
);

STEP 3: INSERT data with NULL values in the column.


Now let’s try to insert NULL values in the NOT NULL constraint column. Below is the query
in which I am trying to put CustomerID as NULL ( CustomerID has NOT NULL constraint )

INSERT INTO TestingTableNotNull (CustomerID,FirstName,LastName)


VALUES (NULL,’Monika’,’G’);

The results after executing the above INSERT script are displayed in Figure 6.2 a.

(Figure 6.2 a)

See, when I tried to insert a NULL value in the table for the column CustomerID. The system
throws an error.

Cannot insert the value NULL into column ‘CustomerID’, table ‘MyEcommerceDB.dbo.
TestingTableNotNull’; column does not allow nulls. INSERT fails.

145
SIMPLE SQL

When I insert NOT NULL values in the NOT NULL column, the data will be inserted smoothly.
Below is the SQL Statement that inserts NOT NULL values in the column with NOT NULL
constraint.

INSERT INTO TestingTableNotNull (CustomerID,FirstName,LastName)


VALUES (‘0101’,’Monika’,’G’);

The results after executing the above INSERT script are displayed in Figure 6.2 b.

(Figure 6.2 b)

Now check the table to ensure if the data is inserted or not using the SELECT statement.

SELECT * FROM TestingTableNotNull;

UNIQUE Constraint
A UNIQUE constraint is a constraint that helps in preventing a column from having Duplicate
values and all values for that column are different.

For example:
Let’s create a table with UNIQUE constraints on one of its columns. Then we will try to insert
some duplicate values for the column with UNIQUE constraint.

146
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

Creating a table with UNIQUE constraint on a column:

Step 1: Connect with a database, right-click and click on a new query.

Step 2: Create and Execute SQL CREATE table statement with a UNIQUE constraint.

CREATE TABLE TestingTableUnique


(
CustomerID INT NOT NULL,
FirstName VARCHAR(30),
LastName VARCHAR(30),
EmailID VARCHAR(100) UNIQUE
);

Inserting values in the table with a UNIQUE constraint.

Let’s try to insert 3 records in the table with UNIQUE constraints for the column “Email”.
Below are the SQL statements to insert these 3 records.

INSERT INTO TestingTableUnique (CustomerID,FirstName,LastName,EmailID)


VALUES (‘101’,’Will’,’McBeth’,’will.mcbeth@gmail.com’);

INSERT INTO TestingTableUnique (CustomerID,FirstName,LastName,EmailID)


VALUES (‘102’,’Will’,’James’,’will.james@gmail.com’);

INSERT INTO TestingTableUnique (CustomerID,FirstName,LastName,EmailID)


VALUES (‘103’,’William’,’McBeth’,’will.mcbeth@gmail.com’);

As you can see, in the INSERT statements, the value of an email is the same for two records.
And as we have UNIQUE constraint applied on email column. So the system must throw an error
when it tries to enter the same value for the email column.

147
SIMPLE SQL

(Figure 6.3 a)

See Figure 6.3 a, when we try to enter duplicate values in a column with a UNIQUE con-
straint, the system will always throw an error. So, If I display all the columns from the table using
the below SELECT query, I will get the results displayed in the Figure 6.3 b.

SELECT * FROM TestingTableUnique;

(Figure 6.3 b)

When I fix the value for the 3rd record and change the email id and make it unique. The sys-
tem must insert the record into the table.
Let’s find out.

INSERT INTO TestingTableUnique (CustomerID,FirstName,LastName,EmailID)


VALUES (‘103’,’William’,’McBeth’,’will.mcbeth1@gmail.com’);

Now, let’s view all the data present in the table. ( See, Figure 6.3 c for results )

148
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

(Figure 6.3 c)

PRIMARY KEY Constraint


A PRIMARY KEY constraint helps make a column as a PRIMARY KEY column. The purpose
of the Primary key is that each record can be uniquely identified.
Once a column is marked with PRIMARY KEY constraint, the values inserted in the column
must be UNIQUE and NOT NULL both. Therefore, you can say that PRIMARY KEY constraint is
a combination of both UNIQUE and NOT NULL constraints.

Let me explain this to you with an example..

Let’s create a table with PRIMARY KEY constraint on one of its columns. Then we will
try to insert some duplicate values and then NULL values for the column with PRIMARY KEY
constraint.

Creating a table with PRIMARY KEY constraint on a column

STEP 1: Connect with a database on the SQL Server, right-click and click on a new query.
STEP 2: Create and Execute SQL statement with PRIMARY KEY constraint

CREATE TABLE TestingTablePrimaryKey


(
CustomerID INT PRIMARY KEY,
FirstName VARCHAR(30),
LastName VARCHAR(30),
EmailID VARCHAR(100)
);

149
SIMPLE SQL

(Figure 6.4 a)

Let’s try to enter duplicate values in the column with PRIMARY KEY constraint; I am sure
the system will throw an error. Below are the SQL statements to insert these 3 records that will
help carry out this testing.

INSERT INTO TestingTablePrimaryKey (CustomerID,FirstName,LastName,EmailID)


VALUES (‘111’,’Andrew’,’Mikkelson’,’Andrew.Mikkelson@gmail.com’);

INSERT INTO TestingTablePrimaryKey (CustomerID,FirstName,LastName,EmailID)


VALUES (‘112’,’George’,’Keller’,’George.Keller@gmail.com’);

INSERT INTO TestingTablePrimaryKey (CustomerID,FirstName,LastName,EmailID)


VALUES (‘111’,’Sia’,’wade’,’sia.wade@yahoo.com’);

You might have observed that both the first record and last record have the same CustomerID.
Therefore, it must not enter the table because the column has PRIMARY KEY constraint imple-
mented. ( See, Figure 6.4 b for reference)

150
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

(Figure 6.4 b)

Let me display all the columns from the table using the below SELECT query, I will get the
results similar to what you can see in the Figure 6.4 c.

(Figure 6.4 c)

Now, If I change the value of CustomerID to ‘112’ instead of ‘111’, I am sure that it will not
violate the PRIMARY KEY constraint, and the record will be inserted easily. To do this, I will use
the below SQL statement to enter the record easily.

INSERT INTO TestingTablePrimaryKey (CustomerID,FirstName,LastName,EmailID)


VALUES (‘113’,’Sia’,’wade’,’sia.wade@yahoo.com’);

Now, Let’s check the data using the SELECT statement. (See, Figure 6.4 d)

151
SIMPLE SQL

(Figure 6.4 d)

The above example displays that a column with PRIMARY KEY constraint can’t have dupli-
cate values.
Now, check if a column with PRIMARY KEY constraint can have NULL values or not. We will enter
one record with a NULL value in the CustomerID column of the TestingTablePrimaryKey
table and then execute the SQL statement.

The SQL Statement for this scenario should be:

INSERT INTO TestingTablePrimaryKey (CustomerID,FirstName,LastName,EmailID)


VALUES (NULL,’Dean’,’Robbins’,’Dean.Robbins@gmail.com’);

After executing the above query, we will face the below PRIMARY KEY violation error.

(Figure 6.4 e)

When I change the PRIMARY KEY column value from NULL to ‘114.’

INSERT INTO TestingTablePrimaryKey (CustomerID,FirstName,LastName,EmailID)


VALUES (‘114’,’Dean’,’Robbins’,’Dean.Robbins@gmail.com’);

152
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

(Figure 6.4 f)

See, after changing the column value from NULL to 114, the record was inserted successfully
(See, Figure 6.4 f for reference). We can see the new record in the table by executing the SELECT
query.

(Figure 6.4 g)

FOREIGN KEY Constraint


In a relational database, a Foreign Key acts as a link that helps build relationships between
two tables. In technical terms, A foreign key column of one table refers to the Primary Key of
another table. This reference helps in building relationships between the two tables.
The table with a foreign key column can be considered a child table, and the one with the
primary key is considered a parent table. Creating this foreign key relationship is quite helpful
because it helps in referential Integrity in the database.

153
SIMPLE SQL

Referential Integrity is the property that ensures the data present in tables refers to the data
present in the same table or another table.

Many experienced developers and database experts ignore the importance of this concept
and create data models that are not optimized for good performances.
Referential Integrity Reduces Redundancy and makes sure that the tables connected using
a relationship must always be in sync during data manipulation operations (INSERT, UPDATE
and DELETE).
Let’s discuss using an example to understand the concept of foreign key constraints and refer-
ential Integrity. We have two tables to understand this concept – Department and Employee!

DEPARTMENT
The Department table will have department details and contain details related to the com-
pany’s different departments. The Department table is acting as a parent table, and the DeptID
is the primary key column.

Below is the SQL Statement to create this table:

CREATE TABLE Department


(DeptID VARCHAR(25) PRIMARY KEY,
DepartmentName VARCHAR(255));

Now , lets insert some data in the table using below SQL Statement:

INSERT INTO Department (DeptID,DepartmentName)


VALUES(‘D1’,’Sales’);
INSERT INTO Department (DeptID,DepartmentName)
VALUES(‘D2’,’IT’);

EMPLOYEE

Employee table will have Employee details and data.

Below is the SQL Statement to create Employee table:

154
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

CREATE TABLE Employee


(EmployeeID VARCHAR(25) PRIMARY KEY,EmployeeName VARCHAR(255),DepartmentID VARCHAR
(25) FOREIGN KEY REFERENCES Department(DeptID));

Now, Let’s enter some data in the table using below INSERT statements:

INSERT INTO Employee(EmployeeID,EmployeeName,DepartmentID)


VALUES (‘111’,’Joey’,’D1’);
INSERT INTO Employee(EmployeeID,EmployeeName,DepartmentID)
VALUES(‘112’,’Samantha’,’D2’);

Suppose Joey joins a sales department of a company. Then the company’s database needs to
enter this event in the database. As you can see, the column data of DepartmentID is present in
Employee must reference and depend upon the data present in the Department table.
Also, the creation of the parent table must be before the creation of the child table. This is
because we can’t build the foreign key references before the column we are referencing exists.
The purpose of linking the Employee and Department table using the foreign key constraint
is to make the information in the database consistent. In addition, it prevents the tables from
wrong or inconsistent data being inserted in tables.

The potential inconsistencies that foreign key constraint prevents, due to below DML operations:

INSERT: When the tables are in referential integrity, then records NOT RELATED to the parent
table can’t be inserted in the child table.

Let me explain..

Till now, the data is in sync for both tables. That means the employees that are inserted in the
Employee table, for them there must be a department in the Department table. If I try to
insert an employee for which there is no data in the parent table (i.e., no records for reference).
Then this operation will violate the referential integrity!

INSERT INTO Employee ( EmployeeID,EmployeeName, DepartmentID)


VALUES (‘113’,’Ross’,’D3’);

155
SIMPLE SQL

(Figure 6.4 h)

This means that if we have foreign key relationships between two tables, then the data that
needs to be inserted for the foreign key column in the child table must be present in the parent
table.
Suppose I change the value of the Department column (foreign key column) to D2. Then the
above record will be inserted smoothly. (See, Figure 6.4 for reference)

(Figure 6.4 i)

In cases where you might need to insert records in the child table, but the relevant column is
not present in the parent table. Then the best way to enter the record in the child table is men-
tioned below:

1st Step: Enter the relevant record in the parent table.


2nd Step: Then, enter the desired record in the child table.

Basically, To INSERT data in the child table linked with primary key constraints, we need to
make sure that the parent table has the relevant data.

Hence, foreign key constraints restrict unnecessary insertions and maintain referential
integrity.

156
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

UPDATE: When tables in a relationship have a foreign key constraint. Then updates are not
allowed on the values present in the primary key column of the parent table and the foreign key
column of the child table.

In simple words, The linked columns (PK and FK) can’t be updated when they are in foreign key
relationships. Therefore, Updating values for the PK and FK columns in either of the two tables
will result in an error.

Let’s understand with an example:

Let me first try to update one record of the table Department and then Employee using the
below SQL statements.

UPDATE Employee
SET DepartmentID=’D0’
WHERE DepartmentID=’D1’;

UPDATE Department
SET DeptID=’D0’
WHERE DeptID=’D1’;

After executing both the SQL statements one by one, we will get the error ( See, Figure 6.4.j
for reference).

(Figure 6.4 j)

157
SIMPLE SQL

(Figure 6.4 k)

What to do when we need to update the values?


Although the foreign key constraint helps maintain the data quality, consistency, and reliabil-
ity of the database. But sometimes, we need to update the key column values.
To work around such scenarios in updating the table, the best way is to follow the below
steps:
1st Step: DROP the foreign key constraints from the table.
2nd Step: UPDATE the values
3rd Step: ADD the foreign key constraint again.

DELETE: It is not allowed to delete records from parent tables or even drop parent tables entirely,
which is in a foreign key relationship with a child table.
Let me explain…
Suppose you’ll try to delete the Department table using the DROP command. However,
the table will not get deleted because now the values of Employee tables are dependent on the
Department table.
Same with the case of values present in the Department table. Suppose we try to eliminate
the values present in the Department table. The system will throw an error.

Let’s take an example to understand this..

Suppose I try to drop the table Department first, using the below SQL statement:

DROP TABLE Department;

158
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

(Figure 6.4 l)

Let me try to delete a record from the parent table that has some related records in the child
table. Using the below SQL statement:

DELETE FROM Department


WHERE DeptID=’D1’;

(Figure 6.4 m)

As you can see in Figure 6.4 m, the above SQL statement led to an error. This shows how
important and effective the foreign key constraint is.

What to do when you need to delete some records from the parent table?
When we need to delete some records from the parent table, and the related records are pres-
ent in the child table. Then in such cases deleting the parent records is not simple.

To do this, below steps need to be followed:

1st Step: DROP the foreign key constraints from the table.
2nd Step: DELETE the record you want to delete from both parent and child tables.
3rd Step: ADD constraint back again.

159
SIMPLE SQL

So, as you must have observed until now, foreign key constraints increase data quality and
consistency and make it difficult to make changes in data. Therefore, we need to follow certain
steps one by one to work around foreign key constraints.

DEFAULT Constraint
DEFAULT constraint automatically inserts a DEFAULT VALUE for the columns for which
there is no value being provided.

SYNTAX:
CREATE TABLE TableName
(
Column1 datatype DEFAULT ‘DefaultValue’,
);

Example:
Let’s create a table to test the DEFAULT constraint now. The table will have 4 columns, and
2 will have DEFAULT constraints. This table stores data of a company, and hence the company
name should be the same for all the records, i.e., DataCeps.

To do that, we can use the below SQL statements:

CREATE TABLE CheckDefaultConstraint


(
ID INT NOT NULL,
EmployeeName VARCHAR(50) NOT NULL,
CompanyName VARCHAR(50) NOT NULL DEFAULT ‘DataCeps’,
);

And then try to insert the below records in the table.

INSERT INTO CheckDefaultConstraint ([ID],[EmployeeName])


VALUES (‘104’,’Dane’);

INSERT INTO CheckDefaultConstraint ([ID],[EmployeeName])


VALUES (‘105’,’Ross’);

160
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

As you can see in the above mentioned INSERT statement, I have mentioned ID,
EmployeeName, and CompanyName columns and inserted values of those columns only. I have
not mentioned any value for the CompanyName as I expect the DEFAULT constraint to automat-
ically put a value for both the above entries.
After executing the above SQL statements and then selecting the data from the table, we will
get the results as displayed in the Figure 6.4 n.

(Figure 6.4 n)

As you can see, the CompanyName column is automatically populated with the default value
i.e.: DataCeps.

CHECK Constraint
CHECK constraint is used in scenarios when we either limit values or want a certain type of
value in a column. The value inserted in the column must satisfy a condition that we can set
while creating the CREATE statement for the table. When the condition is satisfied, only then is
the record inserted. Else the record will not be inserted into the table.

Let me explain with an example…

Let’s create a table for the company DataCeps; The table will have columns EmpID, EmpName,
DepartmentID, EmpAddress, EmpEmail, and EmpSalary.

The main requirement is that every employee of DataCeps must have a salary greater than 1000
USD. No employee of DataCeps will have a lesser salary than this.

So, this will become our condition, which will be represented as EmpSalary<=1000.

161
SIMPLE SQL

The SQL script for the table with above requirement can be written as below:

CREATE TABLE TestingCheckConstraint


(
ID INT PRIMARY KEY,
EmpName VARCHAR(100),
DepartmentID VARCHAR(100),
EmpAddress VARCHAR(100),
EmpEmail VARCHAR(100),
EmpSalary INT,
CONSTRAINT EmpSalary CHECK (EmpSalary>=’1000’)
);

In the above CREATE statement, you can observe that I have added the constraint CHECK
on EmpSalary; when the EmpSalary is greater than and equal to 1000, only then the record
needs to be inserted.
Let’s try to insert a record with a value less than 1000 in this table. Using the below INSERT
statement.

INSERT INTO TestingCheckConstraint VALUES


(‘111’,’Rasmus’,’D1’,’Meadows Apartment,Jackson Street,New York’,’Rasmus.m1@gmail.
com’,’999’);

(Figure 6.4 o)

When I try to enter a record with value equals to 1000 using the below SQL insert statement:

INSERT INTO TestingCheckContraint VALUES


(‘113’,’Brian’,’D2’,’124’ , ‘Keeth Ave, New York’,’Brian.G1@gmail.com’,
’1000’);

The record will be inserted easily ( See, Figure 6.4.p for reference).

162
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

(Figure 6.4 p)

After identifying the correct constraint requirement for the table you’re created. Then, it is
time for you to move on to the next step.

STEP 5: CREATING TABLES USING SQL STATEMENTS


Once you have identified the entities for which you want to build the table, its attributes, and
the constraints you want for your table, then you just need to create an efficient SQL statement
that can easily create the table you want. However, make sure that you are always following the
best practices for creating the tables.

BEST PRACTICES FOR CREATING TABLES THAT EVERY DEVELOPER WILL


RESPECT YOU FOR
I am confident that you have learned how to design and create tables. That is the core of
building awesome tables!
Even If you’re going to create tables for a database for a live project or just for learning,
make sure that you follow these best practices to create tables like a pro-developer. In my career,
I have seen many developers with great technical skills ignore these practices and create tables
that suck. (Sorry for my language, but sadly it’s true).
Below are the best practices you can use to make beautiful tables, and it is easier for other
developers to work on these tables. So, the best practices for creating tables are:

163
SIMPLE SQL

CHOOSING THE RIGHT CASES AND STICKING TO IT:


When creating database objects like tables, views, triggers, etc. We can name the object name
using different cases. Make sure you choose any one of them and name all your database objects
in that case only.
Not only does it look pleasing and beautiful, but it also creates a sense of consistency. It also
makes it easy for other developers to work on the tables you developed.
There are different types of cases that you can use while creating database objects, and some
of them are:

CAMEL CASE: In the Camel case, the first letter of each word is capitalized except the first
word; the rest are in a small case.

For example:
Suppose you want to name a table that has Marks of all Students. In the camel case, it will
be written as—studentMarks. No wonder why it is named as camel case; the first letter of 2nd
word looks like a camel ‘hump’.

CAPITAL CAMEL CASE OR PASCAL CASE: In the Capital camel case or Pascal Case, the 1st
letter of every word will be in upper case.

For example:
If you want to name a table that has Marks of all Students.
In the capital came case, it will be written as—StudentMarks.

SNAKE CASE: In the snake case, all the letters of the word will be small, except each word needs
to be separated by an underscore.

For example:
If you want to name a table that has Marks of all Students.
In the snake case, it will be written as – student_marks.

164
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

UPPER CASE: In the upper case, all the letters of the word need to be in capital letters, and two
words need to be separated by an underscore.

For example:
If you want to name a table that has Marks of all Students.
In Upper Case, it will be written as – STUDENT_MARKS.

FLAT CASE: In flat case, all the letters of the word need to be written in small letters or lower-
case. Also, words are not separated by an underscore or hyphen.

For example:
If you want to name a table that has Marks of all Students.
In Flat Case, it will be written as – studentmarks.

KEBAB CASE: In the kebab case, all the letters of the word need to be written in small letters,
and a hyphen separates words.

For example:
If you want to name a table that has Marks of all Students.
In the kebab case, it will be written as – student-marks.
You need to pick one style and make sure; you use it for every database object you create.
I prefer using the capital camel case!

165
SIMPLE SQL

AVOID SPELLING MISTAKES:


This is something that doesn’t have an impact on the data and the database. But creating
tables and another database object with names that don’t have any spelling mistakes will make
it easier for you and even other developers to work with the database objects you created.

Example:
Suppose, If I create the table that has Marks of all Students and names it in Capital Camel
Case, the spelling is wrong. So, instead of naming the table as StudentMarks, I name it as
StudentMkars.
Whenever I work on this table again to extract data or alter columns, this single spelling
mistake will make me go urrhhh…

ADDING COMMENTS IN YOUR SQL STATEMENTS:


With SQL, we can write complex statements that can become the backbone of an application.
Writing SQL statements is fun, especially when you know that you’re building something
that will be used in an application or system for a long time. You might need to write some com-
plex SQL statements for a complex requirement to accomplish a particular task.
To make your code readable and easy to understand. The best technique is to add comments.
You can write some comments in between your SQL statements. These comments can be of a
single line, or you can choose to write an entire paragraph. These comments are NOT executed
and are ignored whenever you execute your entire SQL statements.

You can add your comments in two ways:

ENTERING A SINGLE LINE COMMENT: You can use the – symbol to join a single line. This
symbol tells the SQL server not to execute the line after this symbol. But the line above and
below the – symbol can execute easily.

Let me explain with an example:

Let me try to extract records from the table Employee where DepartmentID=’D2’. If I want to
add comments in the query, I will simply use the – symbol and add comments in the query.

166
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

So, my SQL query will look something like this:

SELECT TOP (1000) [EmployeeID]


,[EmployeeName]
,[DepartmentID]
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D2’;

--Selecting Employees from department D2 in this query

When I execute the query, the line written in the comments will not be executed, and it will
only display the results of the query.

ENTERING A PARAGRAPH COMMENT: When you want to enter an entire paragraph to


explain whatever is going on in the SQL statement. Then the best way to do this is to start your
paragraph comment with /* symbol and end your paragraph comment with */.

Let me explain this with an example:

If I want to add more lines to the same SQL statement, the SQL statement will look something
like this:

SELECT TOP (1000) [EmployeeID]


,[EmployeeName]
,[DepartmentID]
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D2’;

/*The above query is designed to extract data from the table employee.
It will only select the records that have DepartmentID as D2 */

This commented paragraph will not hamper the query execution even if you put the entire
sentence between the SQL statements.

167
SIMPLE SQL

ADDING ALIASES:
Alias in SQL is a temporary name you give to a column or a table. When you give an alias to
a table or a column, it doesn’t change the actual name of the table or column permanently.

To give an alias to a column, use the below syntax:

SELECT NameOfColumn AS AliasName


FROM NameOfTable;

For Example:
SELECT DeptID AS DepartmentID
FROM Department;

To assign an alias to a table, use the below syntax:

SELECT NameOfColumn(s)
FROM NameOfTable AS AliasName;

For Example:
SELECT *
FROM Department AS DPT;

Once you have created tables that you want for the entities, that you have identified. It’s an obvi-
ous choice to populate those tables with relevant data. Once the table is loaded with data, we
also need to make sure that we enter the correct data, update the wrong records with the right
ones and delete the records that are no longer required.

Let me explain to you about different ways to populated data in SQL tables.

168
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

POPULATING DATA IN TABLES USING INSERT


There are many different ways to enter data into a table. In the initial chapters, I taught you
how to insert data in a table into the easiest way possible. I discussed about the simple way you
can insert the records into a table. There are multiple ways you can use to insert data into tables.

The different ways you can populate data in a table are mentioned below:

a) Entering all the values of the table in one go


b) Entering values partially in a table
c) Importing data from other tables using INSERT INTO.
d) Copying data from one table to a different table.

Entering all the values of the table in one go


To enter all the values in the tables for all the columns, use the syntax below.

Syntax for INSERT:

INSERT INTO TableName


(
COLUMN_NUMBER1,
COLUMN_NUMBER2,
COLUMN_NUMBER3,
..
..
..
)
VALUES
(
VALUE1,
VALUE2,
VALUE3,
..
..
..
);

169
SIMPLE SQL

Suppose you want to insert a complete record, i.e.:- data in all the columns of a table. Then,
the above syntax works the best.
But sometimes, we might want to only enter records in specific columns of a table.
Therefore, Learning about partially entering the data record in a table is a must!

Entering values partially in a table


As you learned about some constraints in the previous section of this chapter, if a table has
some constraints that allow the table to have NULL values in the column or maybe DEFAULT val-
ues in the column. Then entering values for those specific columns using the INSERT statement
is not a smart move..
This kind of insertion is also known as Inserting partial values using insert!
I am not sure if you realized it till now or not. I have covered a great example of inserting
data in the table by just entering selected values as I knew that the other records would be
entered automatically!
To insert the values in the table for the specific column, we just need to mention those col-
umns in the insert statement and mention the data that we want to insert for those columns in
the values part of the SQL statement.
For example: I want to insert data specifically for ID and EmployeeName columns in the
CheckDefaultConstraint table. And for the 3rd Column CompanyName, I don’t need to
insert any values because I know, that it’ll be inserted automatically because of the DEFAULT
constraint.

INSERT INTO CheckDefaultConstraint ([ID],[EmployeeName])


VALUES (‘141’,’Jessica’);

I hope you have not deleted your CheckDefaultConstraint table yet. If you have, you
can go back and recreate it again and execute the INSERT statement.

Importing data from other tables using INSERT INTO.


Usually, to insert records in a table, we use INSERT statements. Using this statement, we can
INSERT data one by one. And whenever you want to enter multiple records simultaneously in a
table. You just need to run multiple INSERT statements and populate a table.
But what if you want to Import data from another table?
In that case, running multiple insert scripts can be a tiring task. To do this quickly, we can
leverage the INSERT INTO statement. The syntax of the INSERT INTO statement is below:

170
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

INSERT INTO TargetTable


(
TargetColumn1,
TargetColumn2,
TargetColumn3,
..


)

SELECT
(
SourceColumn1,
SourceColumn2,
SourceColumn3,
..


)
FROM SourceTable;

For example:
Let me try to import data from one of the Employee table that I created and import data
into another table with same metadata and schema. I will create a table EmployeeNew that will
have the schema exactly like the Employee table that I created earlier.
After I create the new table, I will execute the below SQL statement to import data from the
Employee table to the newly created table (EmployeeNew).

INSERT INTO [MyEcommerceDB].[dbo].[EmployeeNew]


(
EmployeeID,
EmployeeName,
DepartmentID
)
SELECT
EmployeeID,
EmployeeName,
DepartmentID
FROM [MyEcommerceDB].[dbo].[Employee];

171
SIMPLE SQL

The above SQL statement will take all the data from the columns EmployeeID,
EmployeeName, and DepartmentID and put all the data into the newly created EmployeeNew
Table in seconds!

Copying data from one table to a different table.


You can easily copy data from one table to a different using the SELECT INTO statement.
The only difference about this technique is that there is no need to create a new target table with
the same structure and metadata as the source.

It uses the below syntax to copy data from the source table to the target table:

SELECT *
INTO TargetTable
FROM SourceTable;

The above SQL statement will create a new table – TargetTable for you automatically and
put all the data from SourceTable into it.
Here the * represents that all the rows and columns needs to be inserted into the TargetTable
from the SourceTable. If you only want to copy some columns from the SourceTable, only
mention those in the SQL statement and execute the query.
Let me show this to you with an example. First, let me try to copy only a few columns from
the Employee Table. To do this, I will execute the below query and see the results.

SELECT
[EmployeeID],
[EmployeeName]
INTO EmployeeCopy
FROM Employee;

Don’t get confused between copying data using INSERT INTO and SELECT INTO statements.
On a surface level, both are copying data from one table to another, but if you look closely,
you can observe that the way they work is quite different.
INSERT INTO requires the Target table to be created before transferring data from the
source table to the target.

172
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

However, SELECT INTO creates the target table on the fly or runtime, and we don’t need to
create the table explicitly. Now, you just need to practice, practice and practice. You now have
all the information to create tables with SQL.
In the next chapter, you’ll be learning the cool stuff about SQL!
Also, please take some time for the exercises at the end of this chapter before moving.

173
SIMPLE SQL

EXERCISES
1) Create a table with below schema:

Books (BookID, BookName, BookPrice, AuthorName)

Where, BookID is a Primary Key column and BookPrice column value must always be less
than 50.

Datatype Hints:

BookID à nvarchar(10)
BookName à varchar(55)
BookPrice à decimal (5,2)
AuthorName à nvarchar(255)

Insert 2 records in the Books table:

BookID BookName BookPrice AuthorName


B101 SQL For Begginers 28.99 Dane Wade
B321 SQL Mastery 31 Dane Wade

2) Create a table with below schema:

Geography ( GeoID, CountryName, ContinentName)

Where, CountryName and ContinentName columns can’t have NULL values.

Datatype Hints:
GeoID à smallint
CountryName à varchar(20)
ContinentName à varchar(20)

GeoID CountryName Region


311 Andorra Europe
312 United Arab Emirates Middle East
313 Argentina South/Latin America

174
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

3) Create a table with below schemas:

BankCustomer( CustomerID, CustomerFirstName, CustomerLastName, CustomerAddress)

Datatype Hints:
CustomerID à nvarchar(25)
CustomerFirstName à varchar(25)
CustomerLastName à varchar(25)
CustomerAddress à nvarchar(255)

Table Data:

CustomerID CustomerFirstName CustomerLastName CustomerAddress


C-1111 Dane Wade 321, Jackson Street,
New York

BankAccount ( AccountID, AccountName, CustomerName, CustomerID )

Datatype Hints:
AccountID à nvarchar(50)
AccountName ànvarchar(50)
CustomerNameà varchar(25)
CustomerIDà nvarchar(25)

Table Data:

AccountID AccountName CustomerName CustomerID


BL-10111 Regular Savings Dane C-1111

Where CustomerID in the BankCustomer Table should be the primary key column.
And in the bank account table: AccountID is the primary key column, and CustomerID
column is Foreign key that’s referencing the primary key of the Bank customer table..

4) Create a table with below table schema:

Courses ( CourseID, CourseName, CourseType, CoursePrice)

With a DEFAULT column value for CourseType column as “OnlineCourse” CourseName


must always be a UNIQUE value.

175
SIMPLE SQL

Datatype Hints:
CourseIDàvarchar(100)
CourseNameàvarchar(100)
CourseTypeàvarchar(50)
CoursePriceàdecimal(10,2)

CourseID CourseName CourseType CoursePrice


1111 SQL Mastery Online Course 45.45
1112 Python Mastery Online Course 35.45

5) SELECT INTO
Import all data into a new table ( CoursesCopy ) from the Courses table using the
SELECT INTO command.

INSERT INTO
Create a table CoursesInsertInto with the same table schema as the Courses table. Then
insert all the data present in the courses table into the CoursesInsertInto table using the
INSERT INTO command.

176
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

ANSWERS
1)
CREATE TABLE Books
(BookID nvarchar(10) PRIMARY KEY,
BookName varchar(55),
BookPrice decimal (5,2) CHECK (BookPrice<=’50’),
AuthorName nvarchar(255));

INSERT Script:
INSERT INTO Books (BookID,BookName,BookPrice,AuthorName) VALUES(‘B101’,’SQL For
Begginers’,’28.99’,’Dane Wade’);
INSERT INTO Books (BookID,BookName,BookPrice,AuthorName) VALUES(‘B321’,’SQL
Mastery’,’31’,’Dane Wade’);

2)
CREATE TABLE GeographicalData
(
GeoID smallint PRIMARY KEY,
CountryName varchar(20) NOT NULL,
Region varchar(20) NOT NULL
);

3)
CREATE TABLE BankCustomer
(CustomerID nvarchar(25) PRIMARY KEY,
CustomerFirstName varchar(25),
CustomerLastName varchar(25),
CustomerAddress nvarchar(255));

CREATE TABLE BankAccount


(AccountID nvarchar(50) PRIMARY KEY,
AccountName nvarchar(50),
CustomerName varchar(25),
CustomerID nvarchar(25) FOREIGN KEY REFERENCES BankCustomer(CustomerID));

177
SIMPLE SQL

INSERT SCRIPTS:

INSERT INTO [BankCustomer]


([CustomerID],[CustomerFirstName],[CustomerLastName],
[CustomerAddress])
VALUES (‘C-1111’,’Dane’,’Wade’,’321, Jackson Street,
New York’);

INSERT INTO [BankAccount]


([AccountID],[AccountName],[CustomerName],[CustomerID])
VALUES (‘BL-10111’,’Regular Savings’,’Dane’,’C-1111’);

4)
CREATE TABLE Courses
(CourseID varchar(100) PRIMARY KEY,
CourseName varchar(100) UNIQUE,
CourseType varchar(50) DEFAULT ‘Online Course’,
CoursePrice decimal(10,2) );

INSERT SCRIPT For Courses Table:

INSERT INTO Courses (CourseID,CourseName,CoursePrice) VALUES (‘1111’,’SQL


Mastery’,’45.45’);

INSERT INTO Courses (CourseID,CourseName,CoursePrice) VALUES (‘1112’,’Python


Mastery’,’35.45’);

4)
CREATE TABLE Courses
(CourseID int,
CourseName varchar(100) UNIQUE,
CourseType varchar(50) DEFAULT ‘Online Course’,
CoursePrice decimal(10,2) );

178
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

5)
SELECT INTO
SELECT * INTO CoursesCopy FROM Courses;

INSERT INTO
CREATE TABLE CoursesInsertInto
(CourseID varchar(100) PRIMARY KEY,
CourseName varchar(100) UNIQUE,
CourseType varchar(50),
CoursePrice decimal(10,2) );

INSERT INTO CoursesInsertInto


(CourseID,CourseName,CourseType,CoursePrice)
SELECT CourseID,CourseName,CourseType,CoursePrice FROM Courses ;

179
SQL
CHAPTER 7

PLAYING WITH DATA


USING SELECT

I n previous chapters, I already explained to you what SQL does and how we can work with
different SQL statements to carry out some operations that we want to do on the data.
For this chapter, I will suggest you open SQL Server. Then, follow the step-by-step process to
load the datasets from this URL:

https://dataceps.com/loading-employee-table-data-set-step-by-step/

Make sure you’re practicing in parallel while reading this chapter.


Until now, you have understood that SELECT helps us extract a dataset from a table. We can
either extract all the columns present in a table or even extract fewer columns we are interested
in.
As discussed in the chapter on understanding SQL queries, I mentioned that SQL query or a
SELECT statement is a question we ask the database. That simply means the quality of the ques-
tion decides the quality of the answer we get from the database.
The more specific your question will become, the more detailed, refined, and accurate the
answer the database will return to you.
Generally, to refine the question, there are certain things we add to it to make it more specific.
We can also apply conditions cases and filters. We can even sort the extracted data that our query
returns. All this can be done with the help of SQL clauses.

Below are the clauses that help in creating a SQL Query:

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

Let me explain each clause one by one.

181
SIMPLE SQL

THE SELECT CLAUSE


The most important part of a SQL Query is the SELECT clause.
In the SELECT clause, we mention what we want to see in the final results of the query. The
columns mentioned after the SELECT clause will be displayed in the final result set.
Suppose you want to select a specific column in the results of SELECT. It would be best if you
mentioned the column’s name after the SELECT clause. On the other hand, if you want to select
all the columns in the result set, then you need to use (*) after the SELECT clause.
In SQL, you can add some keywords after the SELECT clause and change the result set.
Below are the most common keywords that can be added after a SELECT clause:

TOP
TOP is commonly used after the SELECT clause and before the column names. It is also pop-
ularly known as the SELECT TOP statement.
It limits and displays only a number of rows based on how many records you want to display.

For example: a Query with SELECT TOP 10 will display only the top 10 records from the
table. If you want to see Top 20, change the TOP keyword value.

Let me show some examples to make it simple to understand.

Example: Select TOP 10 records with all the columns from the table Employee.
Approach: For this requirement, we need to display TOP 10 records, and hence we will use
the TOP keyword after selecting. But as we need to display all the records, we will use an aster-
isk(*) after the TOP 10. This will display all the available columns.

SELECT TOP 10 * FROM [MyEcommerceDB].[dbo].[Employee];

Example: Display Job Roles and Date Of Birth of Top 5 records from the Employee table.

SELECT TOP 5 Role,DateOfBirth


FROM [MyEcommerceDB].[dbo].[Employee];

182
CHAPTER 7 - PLAYING WITH DATA USING SELECT

DISTINCT
The DISTINCT keyword is also quite frequently used with a SELECT clause. DISTINCT
keyword removes the duplicate values and then only displays the unique values for the column
on which it is applied.

Example: SELECT the unique Deparment ID’s from the Employee Table.
Approach: To get the unique records, I would suggest to apply would apply DISTINCT on the
DeparmentID column. The query will look something like this:

SELECT DISTINCT DepartmentID FROM [dbo].[Employee]

Example: Display Unique location present in the Employee table.


Approach: To display unique records, we must use the DISTINCT keyword after the SELECT
clause.

SELECT DISTINCT [Location] FROM [MyEcommerceDB].[dbo].[Employee];

THE FROM CLAUSE


The FROM clause in a SQL query tells about the table from which we want to select the data.
Let’s retrieve some data by using the SELECT and FROM clause.

Example: Retrieve all the columns from the Employee table


Approach: To extract all the columns “from’’ Employee table, we need to mention the database
name, schema name, and actual table name after the clause FROM.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee];

183
SIMPLE SQL

Example: Retrieve Only Job Role and Hire Date of all the employees from the Employee
table!
Approach: To extract only Role and Hire Date from Employee table we need to mention only
these column after the SELECT clause.

SELECT Role,HireDate FROM [MyEcommerceDB].[dbo].[Employee];

THE WHERE CLAUSE


WHERE clause in a SQL statement is used to filter out the unnecessary data and allow the final
results that we want to see, basically the WHERE clause helps in filtering out data with the help
of building conditions using different operators.
Let’s try to retrieve some data by adding some conditions to the SQL query

Example: Retrieve data for all the employee whose department ID is D4.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE DepartmentID=’D4’;

The above query displays all the records present in the employee table with D4 Department
ID. In the upcoming chapters, I will present how important the WHERE clause is to filter data.

184
CHAPTER 7 - PLAYING WITH DATA USING SELECT

THE GROUP BY CLAUSE


The GROUP BY clause groups similar values. The data is grouped using column values of a
table.

Syntax:

SELECT Column1
FROM NameOfTheTable
WHERE Condition
GROUP BY Column1;

GROUP BY simply groups similar values of a column together and display them in the final
resultset.
Let me explain it with an example.

Example: Group all the identical DepartmentID’s together present in the Employee Table
using GROUP BY clause.

SELECT DepartmentID
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY DepartmentID;

The above SQL query will group all the similar DepartmentID’s together in the results.

185
SIMPLE SQL

Figure 7.1

GROUP BY can also be used to see the DISTINCT values present in a column as it GROUPS
similar values together. Keep in mind, When using GROUP BY in the SELECT clause, we can
only include the columns which we are GROUPING. Commonly GROUP BY clause is used
with aggregate functions, and we can play with data using GROUP BY and aggregate functions
together.
There are many types of inbuilt functions in SQL that can be used to perform certain tasks
and calculations ( more on this later in the FUNCTIONS chapter), and Aggregate functions are
one of the many SQL functions.

Aggregate functions are used to perform calculations and actions on the multiple rows of
a particular column. Aggregate functions are commonly used with SELECT, GROUP BY, and
HAVING clauses.

Below are the commonly used Aggregate functions:

186
CHAPTER 7 - PLAYING WITH DATA USING SELECT

COUNT ()
COUNT() function is used to calculate the total number of rows in a the selected column.

Example: Count all the records present in the Employee table.

SELECT COUNT(*) AS TotalRecords


FROM [MyEcommerceDB].[dbo].[Employee];

Figure 7.2

Example: Count all the employees whose DepartmentID is D4.

SELECT COUNT(*) AS Department4Employees


FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D4’

Figure 7.3

187
SIMPLE SQL

SUM ()
SUM() function calculates the sum of all the values present in the selected column.

Example : Calculate and retrieve the total Salary for all the employees from the Employee table.

SELECT SUM(Salary) AS TotalSalary


FROM [MyEcommerceDB].[dbo].[Employee];

Results:

Figure 7.4

Example: Using GROUP BY with SUM()


Group the Job Roles and display the total sum of Salary taken by all the employees with
those roles.

SELECT [Role], SUM(Salary) TotalSalary


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY [Role];

188
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.5

The above query groups the data based on Job Role and then adds the data of Salary Separately
for each group (i.e.: Job Role group).

AVG ()
Average function calculates the average value present in a column.

Example: Calculate the average Salary for all the records present in the Employee table.

SELECT AVG(Salary) AS AverageSalary


FROM [MyEcommerceDB].[dbo].[Employee];

Figure 7.6

189
SIMPLE SQL

Example : Calculate the average salary for each Group of Job roles.

SELECT Role,AVG(Salary) AS AVGSalaryByJobRole


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Role;

In the above query, we are using GROUP BY to group the dataset based on the job role and
then calculating the average salary of each group.

Figure 7.7

MIN ()
MIN() function is used to find out the lowest value present in a particular column.

Example : Retrieve the lowest number of SickLeaveHours from the table Employee.

SELECT MIN(Salary) AS LowestSalary


FROM [MyEcommerceDB].[dbo].[Employee];

190
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.8

Example : Use SQL Retrieve the lowest salary in each Job Role groups.

SELECT Role,MIN(Salary) AS LowestSalary


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Role;

Figure 7.9

191
SIMPLE SQL

MAX ()
MAX() function calculates the highest value present in a particular column.

Example : Retrieve the highest Salary present in the Employee table.

SELECT MAX(Salary) AS HighestSalary


FROM [MyEcommerceDB].[dbo].[Employee];

The above query will retrieve the highest salary present in the Employee table.

Figure 7.10

Example : Retrieve the highest salary for each job Role group.

SELECT Role,MAX(Salary) AS HighestSalary


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Role;

The above query groups the data by the job Role and then selects the highest salary for each
group. See the final results after executing in Figure 7.11 .

192
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.11

THE HAVING CLAUSE


The HAVING clause helps in filtering out unnecessary groups. HAVING clause is commonly
used with GROUP BY clause because it is not allowed to use WHERE with aggregate functions.
The GROUP BY clause will group the data the way you want, and then you can easily filter
out the unwanted groups from that selected data by using a condition in the having clause.
HAVING Clause is similar to WHERE clause, but the main thing that separates HAVING from
the WHERE clause is that HAVING Clause can only be used with the GROUP BY clause.
Whereas the WHERE clause can be used even without GROUP BY.

Syntax:
SELECT Column1, Column2, Column3 . . .
FROM NameOfTheTable
GROUP BY Column1, Column2, Column3. . .
HAVING Condition;

Let me explain this with an example..

193
SIMPLE SQL

Example : Display the Job Roles (Roles) whose average Salary is more than 80,000.

Approach: For the above requirement, first we need to think about grouping the results by the
job roles and then find out the average Salary for each group.
After that, we will filter out the records that have an average Salary of more than 80000.

SELECT Role
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Role
HAVING AVG(Salary)>’80000’;

Figure 7.12

Example : Display the headcounts for each job role from Employee Table where the
headcount for that job role is greater than 2.
Approach: For this requirement, we first need to group the data based on their job role so that
the records with similar job roles are grouped. Then we need to count the number of records for
each job role separately.

SELECT Role,COUNT(*) AS HeadCount


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Role
HAVING COUNT(*)>2;

The above query will display you the results that you want!

194
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.13

THE ORDER BY CLAUSE


The ORDER BY clause helps sort the result set into either ascending or descending order.

Syntax:
SELECT Column1, Column2, Column3…
FROM NameOfTheTable
ORDER BY Column1 DESC/ASC ;

Let me explain the ORDER BY clause with some more examples.

Example : Retrieve all the rows from the Employee table, and sort is based on Salary (Highest
to lowest)
Approach: For the above requirement, We need to ensure that the highest salary will be on the
top and the lowest on the bottom.
To do this, the ORDER BY Clause will be used with DESC. The DESC part will sort the result
set into descending order, i.e.: (Highest to lowest)

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
ORDER BY Salary DESC;

195
SIMPLE SQL

Figure 7.14

Example:

Retrieve all the rows from the Employee table, and sort is based on Job Role (A to Z i.e.,
ascending order).

Approach: To create a query for the above requirement, we want the data sorted based on the
job title, starting from A to Z, i.e., ascending order of the alphabet. Therefore, ORDER BY with
ASC will be used here to sort the data in ascending order

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
ORDER BY Role ASC;

196
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.15

So now you understand how clauses help analyze data and make it easy for a developer to
play with data. Analyzing data with the help of SQL is one of the most in demand, rewarding
and fulfilling skill.
To extract your desired dataset, you need to get rid of dataset that is of no use. As you know
already WHERE clause is quite helpful in such case. With the help of SQL operators, you can
increase the filtering capabilities of WHERE clause.

ADVANCED FILTERING (Operators in WHERE clause )


WHERE clause is for creating conditions, and these conditions are helpful in filtering out our
desired result set. To create such conditions, SQL Operators are used with WHERE clause. These
operators help compare, contrast and make logical and arithmetic calculations.
There are commonly two types of operators that can build conditions with WHERE clause—
Comparison Operators and Logical Operators.

Let’s first discuss some Comparison Operators:

197
SIMPLE SQL

COMPARISON OPERATORS IN SQL

SQL Equal to Operator (=)


SQL Equal To Operator checks if the value present on the left-hand side of equal to (=) oper-
ator matches the value present on the right-hand side of the (=) Operator.

Let me explain this with an example:

Example : Display the records from the Employee table where the job title is ‘Marketing
Assistant.’

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Role=’Marketing Assistant’;

In the query, The equal to the operator (=) will match the values from the employee table
with the value present on the right side of the (=) operator.

SQL Not Equal To Operator (!= )


The Not Equal to the operator (!=) checks the value on the left-hand side of the not equal to
the operator with the value present on the right-hand side of the not equal to the operator (!=).

Let me explain with an example:

Example: Display the records from the Employee table where Salary is other than ‘125000’
Approach: To display the records that have Salary other than ‘125000’. we need to eliminate or
filter out the records that don’t have ‘125000’ as Salary. We can do this by simply using the Not
equal to operator (!=).

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary!=’125000’;

Note: You can also use <> in place of != as both works the same.

198
CHAPTER 7 - PLAYING WITH DATA USING SELECT

SQL Less Than Operator (<)


The Less Than Operator in SQL only displays data from tables that are less than the value
present on the operator’s right-hand side.

Let me explain this with an example:

Example: Display all the records present in the Employee table where Salary is Less Than
125000.
Approach: For the above requirement, we want to display the records with a salary of less than
125000.
The best operator that can help in this case is Less Than Operator (<). The Less Than Operator
will compare the query results for the column Salary and Make sure that only those values are
displayed in the results less than the value on the operator’s right-hand side. (i.e. 125000)

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary<’125000’;

SQL Greater Than Operator (>)


In SQL, The Greater Than Operator compares and checks if the value from the left-hand side
(L.H.S) is greater than the operator’s right-hand side (R.H.S).

Let me make it simple for you with an example,

Example: Display all the records present in the Employee table where Salary is Greater Than
125000.
Approach: For the above requirement, we need to compare the records present in the table and
ensure that the value is greater than 20. The best operator that can help in this case is Greater
Than Operator (<).

Greater Than Operator will compare the query results for the column Salary and Make
sure that only those values are displayed in the results greater than the value on the right-hand
side of the operator. (i.e. 20)

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary>’125000’;

199
SIMPLE SQL

SQL Less Than OR Equal To (<=)


Less than or Equal to the operator, compares the left-hand side values with the tables less
than or equal to the values present on the operator’s right-hand side.

Let me explain this with an example:

Example: Display all the records present in the Employee table where the Salary is equal to
or less than 125000.

Approach: To display all the records from the table with values less than or equal to 125000
for the column Salary, The operator Less Than or Equal to (<=) looks like an obvious choice.

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary<=’125000’;

SQL Greater Than OR Equal To (>=)


The SQL, Greater than or equal to the operator, compares the left-hand side values with the
tables greater than or equal to the operator›s right-hand side values.

Let me explain this with an example:

Example: Display all the records present in the Employee table where the Salary is equal to
or greater than 20.
Approach: To display all the records from the table that have values greater than or equal to
125000 for the column Salary, The operator greater Than or equal to (>=) will be the perfect fit.

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary>=’125000’;

So, these are some common comparison operators that we use to build conditions for the
WHERE clause.
Now, let me discuss the Logical Operators!

200
CHAPTER 7 - PLAYING WITH DATA USING SELECT

LOGICAL OPERATORS IN SQL


In SQL, Logical operators do Boolean operations. In simple words, it tests if the conditions
are true, false, or unknown. When all the conditions mentioned with the operators are met, then
the operators return TRUE, else FALSE.

Below are the main Logical Operators used in SQL:

AND
In SQL, the Logical operator AND allows us to work with two conditions simultaneously in
a single query. The conditions are based on Boolean expressions.

Syntax for AND operator:

SELECT Column1, Column2..


FROM NameOfTheTable87
WHERE BooleanExpression1 AND BooleanExpression2;
The AND operator will only return TRUE and work properly when both the conditions, sepa-
rated by AND operator, will return TRUE.

Let me explain this with an example:

Example: Display all records from the Employee Table who have a date of birth greater than
‘1973-11-12’ and Salary greater than ‘100000’.

Approach: The above requirement wants you to display all records from a table. But it requires
you to match and satisfy 2 conditions. If the data you’re trying to display matches both condi-
tions, then only display the data.
We need to create two conditions and separate them with AND logical operator to do this. As
both the conditions needs to be matched.

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DateOfBirth<’1973-11-12’
AND Salary <’100000’ ;

201
SIMPLE SQL

The above has displayed the results of the records where it is TRUE for both the condition
where the Date Of Birth is Greater than ‘1973-11-12’ and Salary is Greater than 100000.
Had there been no records that satisfied either of the condition. Then, the query would not
have worked as the calculation of Boolean expression result of it would be FALSE. So the data
needs to satisfy both the conditions in AND operator.

OR
In SQL, the logical operator OR is also used with multiple conditions. The OR operator works
when any one of the conditions is TRUE. Return FALSE if both the conditions are FALSE.

Syntax:
SELECT Column1, Column2..
FROM NameOfTheTable
WHERE Condition1 OR Condition2;

Let me explain this with an example:

Example: Display Employee Name, Job Role, and Location from Employee table who have
Salary either ‘100000’ or ‘125000’.

Approach: In the above requirement, the desired Result set should be either ‘100000’ or ‘125000’.
That means any record that matches even one of the conditions should be displayed in the result-
ing output. If any record doesn’t match even one of the two conditions, it must not be displayed
in the resulting output. To do this, the best operator that can be used here is OR.

SELECT EmployeeName,Role,Location
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary<’100000’
OR Salary <’125000’ ;

BETWEEN
BETWEEN Logical operator is used to define a range for the query. When BETWEEN operator
is used in a query, then the result set gets limited within that range only. Then the operations on
the dataset will be within that range of limited data only.

202
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Syntax:
SELECT Column1, Column2..
FROM NameOfTheTable
WHERE Column1 BETWEEN Value1 AND Value2;

Let me explain this with an example:

Example: Display Employee Name, Job Role, and Location from Employee table who have
Date Of Birth starting from ‘1982-04-03’ and less than ‘1988-02-11’.

Approach: For this requirement, we need to display 3 columns from the table Employee. But
the condition is that the Date Of Birth needs to be in the range of ‘1982-04-03’ till ‘1988-02-11’.
Hence, for this requirement, BETWEEN keywords will be perfect in the query as it can easily
set the range for the dataset. And then, from that dataset, we can extract the required columns
by mentioning them after the SELECT clause.

SELECT EmployeeName,Role,Location
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DateOfBirth BETWEEN ‘1982-04-03’ AND ‘1988-02-11’ ;

IN
IN operator is similar to the Comparison Operator EQUAL TO in SQL. The difference
between IN and EQUAL TO is that EQUAL TO deals with only a single comparison. However,
IN operator can handle more than 1 value for comparison.
IN Operators checks if the column values match with any value in the list provided in the
condition.

Syntax:
SELECT Column1, Column2..
FROM NameOfTheTable
WHERE Column1 IN (Value1, Value2, Value3…);

Let me explain this with an example:

Example: Display all records from the table Employee. Make sure the Job Title for the selected
records is:

203
SIMPLE SQL

a) Product Designer
b) Research and Development Engineer
c) Sales Executive
d) Marketing Assistant

Approach: In the above requirement, we need to display all records and make sure the job
title for records that we will display matches the job title in the list mentioned.
We could have done it with a comparison operator with 4 conditions separated by OR
operators.
But, to make things much simpler, we can use the IN operator. IN operator will match
column values with the values present inside the list of values. Any column value that matches
with anyone’s value inside this list will be considered a match and, hence, will be displayed in
the output.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role IN (‘Product Designer’,’Research and Development Engineer’,
’Sales Executive’,’Marketing Assistant’);

LIKE
LIKE Operator in SQL is used to match the column values with a string value or part of a
string value or string pattern.
The LIKE Operator can use two wildcards that help in matching the string patterns and
values mentioned below:

a) It uses the underscore (_) sign. (_) represents only one character.
b) It uses the percentage (%) sign. Here, Percentage Sign can represent 0,1 or even multiple
characters.

With the help of one example, I will show you how it all works together and helps in finding
and matching patterns from string values.

Example: Retrieve all the records from the Employee table whose Job Role starts from the letter
‘M.’

Approach: For this requirement, we need to compare the column values of the job title column
and only display the records that start with the letter M.

204
CHAPTER 7 - PLAYING WITH DATA USING SELECT

It doesn’t matter what the rest of the letters in the job title are. Hence we will compare the
column value JobTitle with ‘M%.’ By mentioning % after M, The query signals to the SQL
server that the number of characters after M is not much of a concern for us.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role LIKE ‘M%’;

Example: Retrieve all the records from the Employee table whose Job Role ends with the word
‘er.’

Approach: For this requirement, we need to display records that have values in a column that
ends with ‘er.’ So, we are not concerned about what is before ‘er’;
Hence, we must use ‘%er’ after the LIKE operator because the % represents multiple charac-
ters and can be used when we are unaware of the actual number of characters.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role LIKE ‘%er’ ;

Example: Retrieve all the records from the Employee table that have ‘Manager’ in their Job
Title.

Approach: We don’t know the number of characters that can come before or after the word
‘Manager’ for this requirement. So, in this case, we’ll use ‘%Manager%’ to match.So, any record
that has ‘Manager’ anywhere in the job title will be displayed in the query results.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role LIKE ‘%Manager%’;

205
SIMPLE SQL

Example: Retrieve all the records from the Employee table whose Job Role has the second
character as ‘a’.

Approach: For this particular requirement, we now know that only the 2nd character must be
‘u’ in the values for the column JobTitle. So, we can use ‘_u%.’

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role LIKE ‘_a%’;

NOT
In SQL, the NOT operator returns the opposite value. If the condition is FALSE, Then the
operator will return TRUE. Else if it’s TRUE it will return FALSE.

Let me explain this with an example:

Example: Retrieve all the records from the Employee table whose Job Role Does Not Start
With character ‘M.’

Approach: For this particular requirement, we now know that only the 1st the character must
NOT start with ‘M’ in the values for the column JobTitle. So, we can use JobTitle NOT
LIKE ‘M%.’
Then only those records will be displayed in the final output for which the condition satisfies.
That means select the records where the Role does NOT start with the letter M

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role NOT LIKE ‘M%’;

Till now in this chapter, I explained to you the power of SQL SELECT statement and the
different clauses that we can use with SELECT statement and analyze data effectively. I want you
to also understand how the evaluation and processing of a SQL query is done.

206
CHAPTER 7 - PLAYING WITH DATA USING SELECT

EVALUATION AND PROCESSING OF SQL QUERY

It seems that a query is processed in the way it is written, i.e., from top to bottom. But the
SQL SELECT statement has an order for processing and this order is essential to understand and
make things easier when working with big and complex queries.

A SQL query is executed and evaluated in the below-mentioned sequence:

The FROM clause: In a SQL statement, The FROM clause, along with the joins, is evaluated in
the first place in any query. It provides us with a working dataset on which, if we want, we can
implement our functions or filters.

The WHERE clause: WHERE clause is the second in the evaluation and helps filter out the
required dataset and discards the unnecessary records.

The GROUP BY clause: Then, the evaluation of the GROUP BY clause is done after the WHERE
clause, which helps in aggregating and grouping datasets.

The HAVING clause: After the execution of the GROUP BY clause, basically the grouping of
records, the HAVING clause can execute. HAVING clause helps in filtering out the records that are
grouped together.

The SELECT clause: Eventually, after all the evaluation is done, the SELECT clause is evalu-
ated in the last.

207
SIMPLE SQL

Figure 7.16

If you read till this point in this book, I want to take some time and commend you for your
dedication and willingness to learn. I don’t know you personally but I can assure you that you
have a bright future. Before moving to the next chapter, make sure to practice all the questions
at the end of this chapter.

208
CHAPTER 7 - PLAYING WITH DATA USING SELECT

EXERCISE
1. Retrieve all the columns for the TOP 3 records present in the Employee Table.

2. Retrieve Employee Name and Location of TOP 5 records present in the Employee Table.

3. Retrieve all the columns of the employees who have D1 as Department ID.

4. Retrieve Employee Name and Location of Employees Who have D3 as Department ID.

5. Retrieve the Count Of Employee who have D3 as Department ID.

6. Retrieve the Total SUM of salary of employees of Department D3

7. Retrieve the lowest salary by each location from the Employee table.

8. Retrieve the Highest salary by each location from the Employee table.

9. Retrieve the Location where the average salary of employees is less than 80000.

10. Retrieve the Location and Count of Employees, where the Employee count is greater than 3.

11. Retrieve all columns from employee table based on descending order of the values in Location
Column.

12. Retrieve all the columns from the Employee table where the Job Role is “Developer”.

13. Retrieve all the columns from the Employee Table where the salary is less than “85000”

14. Retrieve all the columns from the Employee table where salary is greater than or equal to
“85000”

15. Retrieve Employee Name and Salary of Employees where the Salary is “85000” and Date Of
Birth is less than ‘1982-12-31’

16. Retrieve all columns of Employee born between ‘1982-01-01’ AND ‘1999-01-01’.

17. Retrieve the Name and Salary Of Employees Whose Name Start from the letter “A”.

18. Retrieve the Name and Salary Of Employees Who have letter “u” anywhere in their Name.

19. Retrieve the Name and Salary Of Employees Who DON’T have letter “u” anywhere in their
Name.

209
SIMPLE SQL

ANSWERS
1)
SELECT TOP 3 *
FROM [MyEcommerceDB].[dbo].[Employee];

2)
SELECT TOP 5 EmployeeName,Location
FROM [MyEcommerceDB].[dbo].[Employee];

3)
SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D1’;

4)
SELECT EmployeeName,Location
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D3’;

5)
SELECT COUNT(*) AS EmployeeInDept3
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D3’;

6)
SELECT SUM(Salary) AS SalaryD3Dept
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DepartmentID=’D3’;

7)
SELECT Location,MIN(Salary) AS LowestSalary
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Location;

8)
SELECT Location,MAX(Salary) AS HighestSalary
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Location;

210
CHAPTER 7 - PLAYING WITH DATA USING SELECT

9)
SELECT Location,AVG(Salary) AS AverageSalary
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Location
HAVING AVG(Salary)<’80000’;

10)
SELECT Location,Count(*) AS TotalCount
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Location
HAVING count(*)>3;

11)
SELECT * FROM [MyEcommerceDB].[dbo].[Employee]
ORDER BY Location DESC;

12)
SELECT * FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Role =’Developer’;

13)
SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary<85000;

14)
SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary>=85000;

15)
SELECT EmployeeName,Salary
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary=85000 AND DateOfBirth<’1982-12-31’;

16)
SELECT * FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DateOfBirth BETWEEN ‘1982-01-01’ AND ‘1999-01-01’;

211
SIMPLE SQL

17)
SELECT * FROM [MyEcommerceDB].[dbo].[Employee]
WHERE EmployeeName LIKE ‘A%’;

18)
SELECT EmployeeName,Salary FROM [MyEcommerceDB].[dbo].[Employee]
WHERE EmployeeName LIKE ‘%u%’;

19)
SELECT EmployeeName,Salary FROM [MyEcommerceDB].[dbo].[Employee]
WHERE EmployeeName NOT LIKE ‘%u%’;

212
SQL
CHAPTER 8

MASTERING SQL FUNCTIONS

W hen we work on live projects, processing and manipulating datasets is quite common and
frequent. For example, we might need to make some changes Or do some calculations on
the extracted data to make the final result more meaningful. This manipulation and calculation
of the data are done with the help of SQL functions.
SQL functions are simply some SQL code snippets that can be used repeatedly to do a par-
ticular type of task or process.

Some of the tasks that a SQL function can do are mentioned below:

a) Manipulation and modification of the dataset


b) Calculations on a dataset
c) Data types conversion

A function is a set of SQL statements that returns a value. These SQL statements carry out
some operations or calculations to return the calculated value. Whenever we call a function, it
will always return a value based on the SQL statements written inside the function. So, it makes
it easier for us developers not to re-write some SQL statements repeatedly as we can simply call
a function and get the desired results.
The best thing about functions is that we can also pass some parameters while calling SQL
functions. And these parameters act as an input value for the function, and then on based on
these inputs, an output value is returned.

There are broadly two categories of functions available in SQL:

a) System Defined Functions


b) User Defined Functions

213
SIMPLE SQL

Figure 8.1

SYSTEM DEFINED FUNCTIONS


A system-defined function is a built-in function defined by the database system. Many sys-
tem-defined functions are available in RDBMS to make it easier for developers to work with
data using SQL.

In SQL server, we have the below-mentioned types of system-defined functions:

a) Aggregate functions
b) String functions
c) Date and time functions
d) Numeric or Math functions
e) Advanced Functions

214
CHAPTER 8 - MASTERING SQL FUNCTIONS

Figure 8.2

The above-mentioned system-defined functions help us analyze, process, and manipulate


data efficiently and quickly. Let me explain each one of the user-defined functions one by one.

AGGREGATE FUNCTIONS
Aggregate functions are system-defined functions that help do mathematical operations and
calculations on multiple rows of a column and return a single value.

For example: calculating the average of records present in a column, calculating the maxi-
mum or minimum value present in a column.

Figure 8.3

Below mentioned are the aggregate functions used in SQL:

215
SIMPLE SQL

MAX ()
Returns the biggest value present in the selected column on which the function is applied.

Syntax
SELECT MAX(NameOfTheColumn)
FROM NameOfTheTable;

MIN ()
Returns the lowest value present in the selected column on which the function is applied.

Syntax:
SELECT MIN(NameOfTheColumn)
FROM NameOfTheTable;

SUM()
Calculates and returns the total sum of the values present in the column on which the SUM()
function is applied

Syntax:
SELECT SUM(NameOfTheColumn)
FROM NameOfTheTable;

AVG()
Calculates and returns the average of the total values in the column on which the AVG() func-
tion is applied.

Syntax:
SELECT AVG(NameOfTheColumn)
FROM NameOfTheTable;

216
CHAPTER 8 - MASTERING SQL FUNCTIONS

COUNT()
Counts and returns the total number of records present.

Syntax:
SELECT COUNT(NameOfTheColumn)
FROM NameOfTheTable;

STRING FUNCTIONS
While working with data, you will frequently encounter string values and records. And you
will be modifying and manipulating string values most of the time.
To facilitate working with string values, SQL has multiple string functions that help do these
efficiently.

Below mentioned are the SQL string functions that make it easy to work on string values:

Figure 8.4

217
SIMPLE SQL

ASCII
ASCII function converts the character value to ASCII value.

Syntax:
ASCII (‘Character’);

Example: Display the ASCII value of character ‘S’.


SELECT ASCII (‘S’);

Result: 83

The output is 83 because the ASCII value of S is 83.

Example:
Display the ASCII Values of the Employee Names in the Employee Table.

SELECT ASCII(EmployeeName) AS ASCIIConvertedNames


FROM [MyEcommerceDB].[dbo].[Employee];

CHAR
CHAR string function converts and returns the character value of an ASCII value.

Syntax:
CHAR (ASCII code);

Example: Display the Character value of ASCII value ‘83’.


SELECT CHAR (83);

Result: S

The output is S because the CHAR value of 83 is S.

218
CHAPTER 8 - MASTERING SQL FUNCTIONS

LEN
LEN function returns the length of the string on which the LEN function is applied.

Syntax:
LEN (‘String Value’);

Example: Display the Total Length of a string value: DataCeps.

SELECT LEN (‘DataCeps’);

Result: 8

The output is 8 because the length of string value is 8 only.

Example: Display each Employee Name along with Length Of each Employee Names present
in the Employee table.

SELECT EmployeeName,LEN (EmployeeName) AS LengthOfName


FROM [MyEcommerceDB].[dbo].[Employee];

CHARINDEX
The CHARINDEX function in SQL searches for a particular substring in a given string and returns
the exact position of the substring in the main string.

Syntax:
CHARINDEX (‘Substring’, ‘Main String’)

Example: Find the substring ‘ep’ substring in the main string ‘DataCeps’.

SELECT CHARINDEX (‘ep’, ‘DataCeps’) AS


CharacterLocation;

Result: 6

219
SIMPLE SQL

The output is 6 because the position of substring ‘ep’ is on position 6 in the main string
‘DataCeps.’

PATINDEX
PATINDEX function in SQL searches a mentioned pattern in a given string and returns the start-
ing position of that string.

Syntax:
PATINDEX (%StringPattern%, ‘String’)

Where,

StringPattern= String pattern you want to search.


String= String where you want to search the String Pattern.

Although It is pretty similar to the CHARINDEX function, the difference is that the PATINDEX
function uses wildcard characters. In contrast, the CHARINDEX does not use the wildcard
characters.

Example:
Find the substring ‘Ceps’ in the main string ‘DataCeps’ using the PATINDEX function.

SELECT PATINDEX (‘%Ceps%’, ‘DataCeps’) AS CharacterLocation;

Result: 5

LEFT
The LEFT function is used to return the characters from the main string, starting from the left
part to the right part of the main string. The length of the returned characters depends upon the
count value in the main function

220
CHAPTER 8 - MASTERING SQL FUNCTIONS

Syntax:
LEFT (‘String’,CharacterCount)

Example: Extract the 3 character string from the LEFT part of the main string DATACEPS .

SELECT LEFT(‘DATACEPS’, 3);

Result: Dat

Example: Display the left part of each employee name till 3 positions from the Employee Table.

SELECT LEFT(EmployeeName,3) AS LeftPartString


FROM [MyEcommerceDB].[dbo].[Employee];

RIGHT
The RIGHT function returns the characters from the main string, starting from the right part to
the left part of the main string. The length of the returned characters depends upon the count
value in the main function.

Syntax:
RIGHT (‘String’,CharacterCount)

Example: Extract the 3 character string from the RIGHT part of the main string DATACEPS .

SELECT RIGHT(‘DATACEPS’, 3);

Result: Eps

Example: Display the Right part of each employee name till 3 positions from the Employee
Table.

SELECT RIGHT(EmployeeName,3) AS RightPartString


FROM [MyEcommerceDB].[dbo].[Employee];

221
SIMPLE SQL

LTRIM
The LTRIM function helps remove the extra spaces from the left side of the mentioned main
string.

Syntax:
LTRIM (‘ String’)

Example: Remove the extra white spaces from the LEFT side of the main string ‘ DATACEPS’.

SELECT LTRIM(‘ DATACEPS’);

Result: DATACEPS

RTRIM
RTRIM function helps remove the extra spaces from the left side of the mentioned main string.

Syntax:
RTRIM (‘ String’)

Example: Remove the extra white spaces from the RIGHT side of the main string
‘DATACEPS ‘.

SELECT RTRIM(‘DATACEPS ‘);

Result: DATACEPS

222
CHAPTER 8 - MASTERING SQL FUNCTIONS

REPLACE
REPLACE functions helps in replacing all the occurrences of a string value in the main string
value with any other desired new string value.

Syntax:
REPLACE(‘MainString’, ‘OldStringValue’, ‘NewStringValue’)

Example: Replace ‘a’ with ‘e’ in the main string ‘DataCeps’.

SELECT REPLACE(‘DataCeps’, ‘a’, ‘e’);

Result: DeteCeps

Example: Display Employee Name of each employee after replacing letter ‘a’ with letter ‘z’.

SELECT REPLACE (EmployeeName,’a’,’z’) AS ReplacedName


FROM [MyEcommerceDB].[dbo].[Employee];

REPLICATE
REPLICATE function replicates a given repeatedly based on the mentioned number

Syntax:
REPLICATE (‘String ‘, Number)
Where,
Number = Number of times you want the string to repeat.

Example: Replicate the main string ‘DataCeps’ 3 times.

SELECT REPLICATE(‘DataCeps.com’,3);

Result:
DataCeps.comDataCeps.comDataCeps.com

223
SIMPLE SQL

Example: Replicate each Employee Name present in Employee table 4 times.

SELECT REPLICATE(EmployeeName,4) AS ReplicatedName


FROM [MyEcommerceDB].[dbo].[Employee];

REVERSE
The REVERSE function reverses the main string values present mentioned in a function.

Syntax:
REVERSE (‘String’) ;

Example: Reverse the main string ‘DataCeps’using SQL REVERSE function.

SELECT REVERSE (‘DataCeps’);

Result:
speCataD

Example: Display each employee Name present in the Employee after reversing.

SELECT REVERSE(EmployeeName) AS NameReversed


FROM [MyEcommerceDB].[dbo].[Employee];

QUOTENAME
QUOTENAME function returns a string after adding “Quote Character” before and after the
returned string values.
If the value of Quote Character is not mentioned in the function, then the default quote char-
acter will be square brackets ([ ]).

224
CHAPTER 8 - MASTERING SQL FUNCTIONS

Below are the options from where you can choose the values for the Quote Character:

a) Square brackets ([ ])
b) Parenthesis or round brackets ( () )
c) Angle brackets (< >)
d) curly brackets ( { } )

Example: Put the string ‘DataCeps’ inside the curly brackets ( { } ) using SQL function.

SELECT QUOTENAME(‘DataCeps’, ‘{}’);

Result:
{DataCeps}

Example: Display each employee Name present in the Employee table inside the curly brackets
({}).

SELECT QUOTENAME(EmployeeName,’{}’) AS QuotedName


FROM [MyEcommerceDB].[dbo].[Employee];

SPACE
SPACE returns the spaces based on the number that is mentioned in the SPACE function.

Syntax:
SPACE(Number)

Example: Return 5 blank spaces using SQL SPACE function.


SELECT SPACE(5) AS Spaces;

Result:

Figure 8.5

225
SIMPLE SQL

STR
STR function is used to convert a numerical value to a string type value.
The underlying datatype will be changed to string type, and then the converted value can be
stored in a column of string datatype.

Syntax:
STR(NUMBER)

Example: Display and Add the integer value 2022 after converting the integer value 2022 to
string value.

SELECT ‘DataCeps’+STR(2022);

Result:
DataCeps 2022

The part 2022 will be converted to a string value because of the STR function.

STUFF
STUFF function simply replaces the part of a string with a new string value. You need to mention
the “Starting position” and the “Total Length,” where you want to stuff the new string value in
the main string.

Syntax:

STUFF(‘MainString’, StartingPosition, TotalLength, ‘NewString’);

Where,
MainString = String where you want to make changes or do the stuffing.

StartingPosition =The starting position from where your new string will start replacing
the main string.
TotalLength =Total length your new string will cover in the main string space.
NewString = The new string that you want to stuff or replace in the existing one.

226
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example: Replace ‘PQL’ with the string value ‘SQL’ in the string ‘PQL Book.

SELECT STUFF(‘PQL Book’, 1, 3, ‘SQL’);

Example: Replace the 1st 3 Letters of each employee Name present in the Employee table with
SQL.

SELECT STUFF (EmployeeName,1,3,’SQL’) AS New


FROM [MyEcommerceDB].[dbo].[Employee];

SUBSTRING
SUBSTRING function is used to return apart from the main string. So you need to mention the
‘Starting Position’ and the ‘Total length’ of the string you want to extract.

Syntax
SUBSTRING(‘MainString’, StartingPostion, TotalLength)

Where,
‘MainString’ = It is the string from where you want to extract the substring.
StartingPostion = It is the Starting position in the main string from where you want to
extract your substring.
TotalLength = It is the total length of the characters you want to extract from the main
string for your substring.

Example:

SELECT SUBSTRING(‘SQL Mastery’, 1, 3)

Result:
SQL

Example: Display the First 4 letters of each employee name present in the Employee table.

SELECT SUBSTRING(EmployeeName, 1, 3) AS SubstringValue


FROM [MyEcommerceDB].[dbo].[Employee];

227
SIMPLE SQL

LOWER
The LOWER function helps in converting upper case characters to lower case.

Syntax:
LOWER(‘String’)

Example: Convert the string value ‘DATACEPS’ in lowercases using string function?

SELECT LOWER(‘DATACEPS’);

Result:
Dataceps

Example: Display each employee name present in the Employee table in lowercase

SELECT LOWER(EmployeeName) AS LowerCased


FROM [MyEcommerceDB].[dbo].[Employee];

UPPER
The UPPER function helps in converting upper case characters to lower case.

Syntax:
UPPER(‘String’)

Example: Convert the string value ‘dataceps’ in uppercase using string function?
SELECT UPPER (‘dataceps’);

Example: Display each employee name present in the Employee table in Uppercase

SELECT UPPER(EmployeeName) AS UpperCased


FROM [MyEcommerceDB].[dbo].[Employee];

228
CHAPTER 8 - MASTERING SQL FUNCTIONS

SOUNDEX
SOUNDEX function returns a 4-character code for a given string value based on the sound of that
string.

Syntax:
SELECT SOUNDEX(‘DataCeps’);

Result:
D321

DIFFERENCE
DIFFERENCE function compares the SOUNDEX values and returns the integer value on the scale
of 0 to 4.

Syntax:
DIFFERENCE(‘String1’,’String2’)

Where,
In results the value 0 represents lowest similarity.
And 4 represents the highest similarity.

Example: Find the difference between string values ‘DataCeps’ and ‘DataCaps’ using the string
function DIFFERENCE.
SELECT DIFFERENCE(‘DataCeps’,’DataCaps’)

Results: 4

229
SIMPLE SQL

CONCAT
CONCAT function helps in concatenating two or more string values.

Syntax:
CONCAT(‘String1’,’String2’, ……….. ‘String’ (n))

Example:
SELECT CONCAT(‘Data’, ‘Ceps’, ‘.com’);

TRIM
The TRIM function removes extra spaces from both LHS and RHS of the mentioned string value.

Syntax:
TRIM(‘ String ‘)

Example:
SELECT TRIM (‘ DataCeps ‘);

TRANSLATE
TRANSLATE function replaces the characters in the main string with another character value of
your choice.

Syntax:
TRANSLATE (‘Main String’, ‘StringToReplace’, ‘ReplaceWith’)

Where, Main String = It is the main string where you want to make changes/replacement.
StringToReplace = The String value that you want to replace from the main string.
ReplaceWith= The Values that you want to replace in the main string.

Example:
SELECT TRANSLATE(‘[DataCeps]’, ‘[]’, ‘{}’);

230
CHAPTER 8 - MASTERING SQL FUNCTIONS

Results: {DataCeps}

It seems that it works similarly to the REPLACE() function in SQL. However, the difference
between REPLACE and TRANSLATE is basically on how both the function deals with characters.
REPLACE() function replaces the string entirely with another on one go. In comparison, the
TRANSLATE( ) function replaces the characters of a string byte-by-byte.

NCHAR
NCHAR function returns UNICODE character of a mentioned number code.

Syntax:
NCHAR(NumberCode)

Where,
NumberCode = Unicode standard number code.

Example:
SELECT NCHAR(87);

DATALENGTH
DATALENTH function returns the total number of bytes a value or an expression is taking.

Syntax:
DATALENGTH(‘StringValue’/Expression);

Example:
SELECT DATALENGTH(‘www.DataCeps.com’);

Result: 16

231
SIMPLE SQL

CONCAT_WS
CONCAT_WS function returns the concatenation of two or more string values. However, the con-
catenated string will be concatenated using a separator.

Syntax:
CONCAT_WS(‘Separator’, ‘String1’, ‘String1’,’String1’. . . . ‘String (n)’)

Example:
SELECT CONCAT_WS (‘#’, ‘SQL’, ‘PRACTICE’,’REPETITION’);

Result:
SQL#PRACTICE#REPETITION

CONCAT USING +
CONCAT function using a + is used to concatenate two or more strings. In this function, the
strings are concatenated by using the + operator.

Syntax:
‘String1’ + ‘String2’ + ‘String3’+......+ ‘String (n)’;

Example:
SELECT ‘Data’ + ‘Ceps’ + ‘.com’;

Results:
DataCeps.com

Example: Concatenate each employee name with his/her job role in the below format.
(Employee Name) works as (Job Role)

SELECT EmployeeName +’ works as ‘+ Role


FROM [MyEcommerceDB].[dbo].[Employee];

232
CHAPTER 8 - MASTERING SQL FUNCTIONS

After string values, the most common types of values that you will observe in most data-
sets will be date-time. So, SQL offers Date Time Functions to work effectively with date-time
datatypes.

DATE AND TIME FUNCTIONS

Figure 8.6

There are multiple Date and Time functions that SQL offers to work with Date and Time
values present in a dataset or a table.

233
SIMPLE SQL

FUNCTIONS THAT RETURNS CURRENT DATE

GETDATE ()
GETDATE() functions return the current system date along with time. The format in which
GETDATE() returns the date and time is mentioned below:
“YYYY-MM-DD hh:mm:ss.mmm”

Example:
SELECT GETDATE();

Result:
2022-01-01 20:31:58.630

SYSDATETIME()
SYSDATETIME() Returns the system date along with the time of the system. The format in
which SYSDATETIME () returns the date is below.
“YYYY-MM-DD hh:mm:ss.mmm”

Example:
SELECT SYSDATETIME();

Result:
2022-01-01 20:54:58.6367008

GETUTCDATE()
GETUTCDATE() returns the current system UTC date and the time in the below-mentioned
format.
The UTC format is the standard time accepted globally and considered the most precise time
format.
“YYYY-MM-DD hh:mm:ss.mmm”

234
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example:
SELECT GETUTCDATE();

Result:
2022-01-01 16:31:52.127

SYSUTCDATETIME()
SYSUTCDATETIME() is used to return the date and time along with the time zone of the system
on which your SQL SERVER is running. The format of the SYSUTCDATETIME() is mentioned
below:
“yyyy-mm-dd hh:mm:ss.nnnnnnn”

Example:
SELECT SYSUTCDATETIME()

Result:
2022-01-01 16:51:44.9841485

FUNCTIONS THAT RETURN PART OF A DATE AND TIME:

DATETIME ()
DATENAME() function extracts and returns a specific part from the mentioned date in the
function.

NOTE: The datatype of the value that a DATENAME function returns is of character string type.

Syntax:
DATENAME (PartOfDate, YourMainDate)

Where,
YourMainDate= The main date from which you want to extract values.
PartOfDate = The PartOfDate is the part you want to extract and display from the main
input date.

235
SIMPLE SQL

Below are the options that can be extracted and returned from the main string:

yy,yyyy,year: To extract the only year from the main date.


mm,m,month: To extract the month from the main date.
dy,y,day: To get day from the date.
qq,q, quarter: To extract the quarter from the mentioned date.
Dayofyear: To extract the day of the current year for the main date.
wk,ww,week: to extract the week part from the main date.
dw,w, weekday: To extract the weekday from the main date mentioned.
hh,hour: To extract the hour from mentioned main date.
n, mi, minute: To extract the minute from the mentioned main time.
s, ss, second: To extract the seconds part from the mentioned main time.
ms, millisecond: To extract the milliseconds part from the mentioned main time.

Example: Select and display the day from the date – ‘2021-11-04 17:38:05.1874283’.
SELECT DATENAME (DAY, ‘2021-11-04 17:38:05.1874283’);

Result: 4

Example:

Select and display which day in the year it is for the date – ‘2021-11-04 17:38:05.1874283’.

SELECT DATENAME (DAYOFYEAR, ‘2021-11-04 17:38:05.1874283’);

Result: 308

Example:

Select and display which week in the year it is, for the date – ‘2021-11-04 17:38:05.1874283’.

SELECT DATENAME (WEEK, ‘2021-11-04 17:38:05.1874283’);

Result: 45

236
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example:
Select and display which day in the year it is for the date – ‘2021-11-04
17:38:05.1874283’.

SELECT DATENAME (DAYOFYEAR, ‘2021-11-04 17:38:05.1874283’);

Result: 308

DATEPART
DATEPART() function is also used to extract a specific part from the specified date in the function.

NOTE: The datatype of the value that a DATEPART function returns is of integer type.

Syntax:
DATEPART (PartOfDate, YourMainDate)

Where,
PartOfDate = The PartOfDate is the part that you want to extract and display from the
main input date.

The previous mentioned options can be used in the PartOfDate arguments from the main
string. For example, yy for year, mm for month etc

DAY
DAY function only extracts the day part from the main input date.

Syntax:
DAY(date)

Example: Select and display only day part from the date -‘2021-11-25’
SELECT DAY(‘2021-11-25’);

Result: 25

237
SIMPLE SQL

MONTH
The MONTH function is used to extract only the month part from the main input date.

Syntax:
MONTH(date)

Example:
SELECT MONTH(‘2021-11-25’);
Result: 11

YEAR
YEAR function is used to extract only the month part from the main input date.

Syntax:
YEAR(date)

Example: Select and display only the year part from the date -‘2021-11-25’
SELECT YEAR(‘2021-11-25’);

Result: 2021

SQL FUNCTIONS TO MODIFY DATE VALUES

DATEADD
DATEADD function is used to add interval/number to the part of the main input date value.

Syntax:
DATEADD (PartOfDate,Value,YourMainDate);

Where,
PartOfDate = The PartOfDate is the part that you want to extract and display from the
main input date.
The previous mentioned options can be used in the PartOfDate arguments from the main
string. For example, yy for year, mm for month etc

238
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example: Add 3 years in the date value –’2020-11-25’.


SELECT DATEADD(yyyy, 3, ‘2020-11-25’);

Results:
2024-02-25 00:00:00.000

Example: Add 3 months in the date value -- ‘2020-11-25’.


SELECT DATEADD(mm, 3, ‘2020-11-25’);

Results:
2021-02-25 00:00:00.000

DATEDIFF
DATEDIFF function is used to take the difference between two date values. You just need to
mention the Part of date from where you want to subtract values.

Syntax:
DATEDIFF (PartOfDate,Date1, Date2);
Where,
PartOfDate = The PartOfDate is the part from where you want to subtract the main
input date.
The previous mentioned options can be used in the PartOfDate arguments from the main
string.
For example: yy for year, mm for month etc.

Date1,Date2= The two dates where you want calculate the differences.

Example: Find the difference between the two date values -- ‘2015-11-25’ and ‘2020-11-25’.
SELECT DATEDIFF(yyyy, ‘2015-11-25’, ‘2020-11-25’);

Results:
5

239
SIMPLE SQL

Example: Subtract months in the date value -- ‘2015-11-25’ and ‘2020-11-25’.


SELECT DATEDIFF(mm, ‘2015-11-25’, ‘2020-11-25’);

Result:
60

WORKING WITH NUMERIC/MATH FUNCTIONS


In SQL, we can have a wide variety of data loaded into tables. It includes data of string data
type, date time datatype as well as numerical data type.
That’s why SQL offers mathematical functions to make things and calculations easy when
working with the mathematical and numerical values.

Figure 8.7

240
CHAPTER 8 - MASTERING SQL FUNCTIONS

COS
COS function returns the cosine values of the mentioned number.

Syntax:
COS (Number)

Example:
SELECT COS(3);

Result:
-0.989992496600445

COT
The COT function is primarily used to find the Cotangent value of the mentioned number.

Syntax:
COT(Number)

Example:
SELECT COT(2);

Result:
-0.457657554360286

SIN
Calculates and returns the Sine value of a mentioned number.

Syntax:
SIN (Number)

Example:
SELECT SIN (27);

Result:
0.956375928404503

241
SIMPLE SQL

TAN
Calculates and returns the Tangent value of a mentioned number.

Syntax:
TAN (Number or Expressions)

Example:
SELECT TAN(-7);

Result:
-0.871447982724319

ACOS
ACOS datatype returns the Arc cosine of a mentioned number.

Syntax:
ACOS (Number)

Where, Number = The number range for which you want to find out arc cosine values.
Usually, the range is -1 to 1.

Example:
SELECT ACOS(-1) AS ArcCosine;

Result:
3.14159265358979

ASIN
ASIN function in SQL returns the Arc Sine of the number mentioned inside the ASIN function.

Syntax:
ASIN (Number)

242
CHAPTER 8 - MASTERING SQL FUNCTIONS

Where, Number = The number range for which you want to find out Arc sine values. Usually,
the range is -1 to 1.

Example:
SELECT ASIN(-1) AS ArcSine;

Result:
-1.5707963267949

ATAN
ATAN function in SQL returns the Arc Tangent of the number mentioned inside the ATAN function.

Syntax:
ATAN (Number)
Where, Number = The number range for which you want to find out Arc sine values. Usually,
the range is -pi/2 to pi/2.

Example:
SELECT ATAN(-43) AS ArcTangent;

Result:
-1.54754470398443

ATN2
ATN2 function in SQL returns the Arc Tangent of the two numbers, that’s mentioned inside the
ATN2 function.

Syntax:
ATN2(FirstNumber, SecondNumber)

Where,
FirstNumber and SecondNumber are the values for which you need find the Arc Tangent
of.

243
SIMPLE SQL

Example:
SELECT ATN2(1, -2);

Result:
2.67794504458899

CEILING
CEILING function returns the integer value bigger than or equal to the mentioned value inside
the function.

Syntax:
CEILING (Number)

Example:
SELECT CEILING(7.75);

Result:
8

DEGREES
DEGREES function in SQL coverts the mentioned value from radian to degrees.

Syntax:
DEGREES (Number)

Example:
SELECT DEGREES(3.6);

Result:
206.264806247096373681

244
CHAPTER 8 - MASTERING SQL FUNCTIONS

EXP
If you want to calculate the exponential value of a given number, then EXP function can help
you. It returns the exponential value of any given number.

Syntax:
EXP(Number)

Where,
Number= The value for which you want to get the exponential value.
This is basically determined e raised to the power Number.
Here, e is a mathematical constant that has value of -2.71828182845905.

Example:
SELECT EXP(3);

Result:
20.0855369231877

FLOOR
FLOOR function returns the biggest integer value that is less than or equal to the mentioned value
passed in the function as a parameter.

Syntax:
FLOOR (Number)

Example:
SELECT FLOOR(71.19);

Result:
71

245
SIMPLE SQL

LOG
If you want to find out the logarithmic value of a mentioned number, the LOG function can be
useful.

Syntax:
LOG (Number, BaseForLog)

Where,
Number= The main value for which you want to calculate the logarithm.
BaseForLog= It is an optional value. Basically, it is the base for which the logarithm will
be calculated.

Example:
SELECT LOG(2, 3);

Result:
0.5

LOG10
LOG10 function is used to return the logarithm value of a number with base 10.

Syntax:
LOG10(Number)

Example:
SELECT LOG10(5.5);

Result:
0.740362689494244

246
CHAPTER 8 - MASTERING SQL FUNCTIONS

PI
PI function returns the value of PI (π).

Syntax:
PI()

Example:
SELECT PI();

Result:
3.14159265358979

POWER
The POWER function is used to calculate the power of a given base value raised to the power
exponent value.

Syntax:
POWER (BaseNumber,ExponentNumber)

Example:
SELECT POWER(2, 3);

Result:
8

RADIANS
RADIANS helps in converting a degree value into radian values.

Syntax:
RADIANS (Number)

Example:
SELECT RADIANS(180);

Result:
3

247
SIMPLE SQL

RAND
Whenever you want to generate Random decimal values, the RAND function comes in handy and
returns a random decimal value. The random value changes every time it is executed over the
server.

Syntax:
RAND();

Example:
SELECT RAND();

Result:
0.291524901550145

ROUND
The ROUND function is useful to get the rounded value of a given number. You need to enter the
value for which you want to get the rounded value, and then the function calculates and returns
the round value for it.

Syntax:
ROUND(Number, DecimalPlace, Operation)

Where,
Number = The main number for which you want to get the rounded value.
DecimalPlace= The Decimal places you want to round your main number.
Operation= Default value for this is 0. When the value is 0, it rounds the result to the num-
ber of decimal values.

If this value is other than 0, then it basically truncates the results, to the number of decimal
values.

Example :
SELECT ROUND(123.321252123, 3, 0);

Result:
123.321000000

248
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example:
SELECT ROUND(123.321252123, 6, 0);

Result:
123.321252000

SIGN
If you want to return the sign of a value, the sign function can be used.
If the number mentioned in the function is:

a) Greater than 1 (Number>1), the function returns the value 1.


b) Less than 1, then the function returns the value -1.
c) Equals to 0, then it returns the value 0.

Syntax:
SIGN (Number)

Example:
SELECT SIGN (-121);

Result:
-1

SQRT
SQRT functions helps in calculating the Square root of any value, it can be quickly done using
the SQL SQRT function.

Syntax:
SQRT (Number)

Example:
SELECT SQRT(324);

Result:
18

249
SIMPLE SQL

SQUARE
SQUARE is used to find out the Square of a given value, the SQUARE function can be used.

Syntax:
SQUARE (Number)

Example:
SELECT SQUARE (11);

Result:
121

This brings me to the end of this section about the System defined functions and how they
make things so efficient and easy for us. However, SQL also allows the users to create functions
on their own, known as User-defined functions.
Before we dive deep into what user-defined functions are, please learn about some program-
ming fundamentals that will help you to understand and master User-defined functions.
You can skip this section and directly jump to the User-defined section if you already know
these fundamentals.

REFRESHING SOME PROGRAMMING FUNDAMENTALS


No matter what type of coding language you choose to learn, some fundamentals are common
across all the languages. These programming fundamentals are Syntax, Datatypes, Variables,
Parameters, Loops, conditions, etc.
I have already explained the Syntax for SQL statements and the datatypes used in SQL.
Loops and conditions are something that I believe doesn’t fit the scope of this book; maybe I
will cover it in the next advanced to the expert edition of the SQL book. However, in my opin-
ion, understanding the variables and parameters will help you out in the upcoming chapters.
Therefore, I want to explain to you about variables and Parameters.

Variable is memory locations used to store a value that can change or modify throughout
the execution of a program or code. You can say that a variable acts as a temporary container to
store and manage values. You can create a variable of any datatype, and it will start storing the
values for that type of datatype.
For example: If you have to store integer type data, you will need to declare an integer
variable.

250
CHAPTER 8 - MASTERING SQL FUNCTIONS

Now let me explain to you about Parameters...

A Parameter is a special type of variable that is utilized to pass the data and information
between functions. The data that is being passed is considered as arguments.

USER DEFINED FUNCTIONS


A user-defined function (UDF) is a function that a user can create based on their custom
requirements. The purpose of creating user-defined functions is to use a complex logic multiple
times without rewriting it again and again.
You can create a logic for a specific requirement and create a function for that logic. Then
that function can be used in other SQL statements, triggers, procedures, etc.

User-Defined Functions can be of two types:

a) Scalar Functions
b) Table-Valued functions

Let’s discuss each one of the above-mentioned functions:

SCALAR FUNCTIONS
Scalar functions are user-defined functions that returns a single scalar value every time they’re
executed. The data that is returned by the scalar function can be of any data type other than the
below-mentioned data types:

i) timestamp
ii) image
iii) cursor
iv) text
v) ntext

A scalar function can have 0 parameters, and it can also accept multiple parameters.

251
SIMPLE SQL

In order to create a scalar function below syntax is used:

Syntax of creating a scalar function:


CREATE Function FunctionName ( Parameter1 Datatype1, Parameter2 Datatype2 . . . .
Parameter(n) Datatype(n) )

RETURNS ReturnDataType
AS
BEGIN

Statement1,
Statement2,
.
.
.
.
Statement(n)

RETURN ReturnValue
END

As you can observe in the above Syntax, when we create a function, we can create it using
CREATE statement and then function name, and then we can mention the Parameters along with
the datatype that we want to use in the function.

NOTE: A function can have up to 1024 parameters.

I also mentioned what kind of DataType this Scalar function will return. So a user can and
must decide the datatype that a function returns while creating it for the first time.
Also, Keep in mind the data type that can’t be used in a scalar function. The function’s body
starts from BEGIN and ends with END statements.
The SQL statements of the function, along with the final value it returns, must be written
inside the scalar function’s body.

Let me explain it with an example:

252
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example of a scalar function:


Create a function that returns the Total Salary of the Employees present in the Employee
Table.

CREATE FUNCTION TotalEmpSalary ()


RETURNS INT
AS
BEGIN

RETURN (SELECT SUM(Salary)


FROM [MyEcommerceDB].[dbo].[Employee])

END

Approach: We will use the above syntax to create the function. And inside the body of the
function will use a SQL statement that will return the Total Salary of Employee present in the
Employee Table.
As you can see, To keep it simple, I am directly returning the result set of the query using the
RETURN statement. However, It’s better to store the result set in a variable and then return the
variable.
Now, you can use such a custom-created function to calculate or find a similar output across
any other SQL statements, stored procedures, etc.

EXECUTING a User Defined scalar function:


To execute a user-defined scalar function, below are the different ways we can do it.
Execute the function and display the values the function returns.

Syntax:
SELECT SchemaName.FunctionName();

Example:
SELECT dbo.TotalEmpSalary();

Execute the function using EXEC command.

Syntax:
EXEC SchemaName.FunctionName;

253
SIMPLE SQL

Example:
EXEC dbo.TotalEmpSalary;

INLINE TABLE-VALUED FUNCTIONS


Inline table-valued function returns a virtual table based on the SQL statements mentioned
inside the body of the function. In simple words, whenever the function executes, it returns the
table as an output.
Also, Unlike Scalar functions, Inline table-valued functions don’t have BEGIN and END blocks
for the function’s body.

To create an inline table-valued function, below syntax can be used:

CREATE FUNCTION FunctionName


(@Parameter1 DataType1, @Parameter2 DataType1 . . . . @Parameter (n) DataType(n))

RETURNS TABLE
AS
RETURN (SELECT Statement)

Syntax to Execute/Call an Inline Table Valued Function:

SELECT * FROM FunctionName(ValueForParameter1, ValueForParameter2 . . .


ValueForParameter(n));

Let me try to explain it with an example:

Example: Create a parameterized inline table-valued function that returns tabular data. The
returned table data must always be less than the parameterized value passed for the Salary
Column.

Approach: To create an inline function that returns a table data of book details table, the
returned values must have the price lesser than the value supplied in the parameter of a
function.
First, we need to create the function based on the CREATE FUNCTION syntax for inline
tables. Then the SELECT statement that is used inside needs to be compared.

254
CHAPTER 8 - MASTERING SQL FUNCTIONS

The function will look something like this:

CREATE FUNCTION SalaryLesserThan (@ParameterSalary INT)


RETURNS TABLE
AS
RETURN (SELECT * FROM dbo.Employee WHERE Salary<=@ ParameterSalary)

To call the function, we can use the below query with different parameters. Every time you
change the parameter, the function will return a different dataset.

SELECT * FROM SalaryLesserThan (125000);


The above query will return Employee Details that have Salary lesser than 125000.

SELECT * FROM SalaryLesserThan (100000);

The above query will return Employee Details that have Salary lesser than 100000.

User defined functions provides the flexibility to developers to create custom functions for
their applications and avoid doing repetitive calculations. I hope you now have entirely under-
stood about how functions work. The next section of this chapter is all about levelling up your
game with some advanced functions that advance developers and expert developers use to com-
pare, contrast and extract insights from the data.

LEVELING UP THE GAME WITH ADVANCED FUNCTIONS

WINDOW Function in SQL.


Functions are the backbone of data analytics and insights. Different functions allows us to
play with data, the way aggregate functions allow us to perform calculations on the extracted
data. Then we can order that particular data in ascending and descending order based on our
requirements.
Similarly, window functions or ranking functions in the SQL server allows us to create ranks
for the extracted records. window functions assign a number to each record that represents the
rank of each record present in the dataset.
Before I explain to you the different types of the window function.

255
SIMPLE SQL

Let me explain to you the different components used in these ranking functions.
These components of the window function are PARTITION BY and OVER clause.

PARTITION BY clause:

As the name suggests, the PARTITION BY clause divides the dataset into partitions based
on the column on which it wants to create the partition. In Figure 8.8 , you can see how a table
is divided in multiple partitions.

Figure 8.8

After creating the partition, you can implement any function over that partition and say
something meaningful about that partition. The function that can be used with these datasets
are COUNT(), SUM (), AVG(), MIN(), MAX(), ROW_NUMBER(), RANK(), DENSE_RANK etc.
PARTITION BY clause looks similar to GROUP BY Clause due to their functionalities.
However, there are significant differences between them. Some of these differences are mentioned
in the Figure 8.9.

Figure 8.9

256
CHAPTER 8 - MASTERING SQL FUNCTIONS

OVER clause:
The OVER clause is commonly used with PARTITION BY clause . To create rankings, we
might need to break a dataset into multiple partitions and then assign a rank to those particular
partitions. Then we can apply ranking or even other functions over those partitions.

Below is the syntax:


FUNCTION (...) OVER ( PARTITION BY ColumnName)

Example:
SELECT EmployeeName,Location,COUNT (Location) OVER (PARTITION BY Location) AS
PartitionCount
FROM [MyEcommerceDB].[dbo].[Employee];

COUNT (Location) OVER (PARTITION BY Location) will first break the dataset into
partitions based on the value present in the Location column.
And then will display the count for each partition using the COUNT() function. Now let me
explain about different types of ranking functions, but before that. Please check the results of
above queries in your SQL Server

ROW_NUMBER()
Whenever you want to assign a unique sequence to records of the output , in that case, ROW_
NUMBER() can be really useful.
The numbering or ranking of the records will begin from 1 and will continue until the last
record of the extracted dataset.

Syntax:
ROW_NUMBER () OVER ( [PARTITION BY Expression...] ORDER BY SortingExpr...)

Where,
The PARTITION BY clause is optional. But ORDER BY is mandatory!
Expression = The Column or value on which you want to partition.
SortingExpr = The Column or value you want to implement ORDER BY. Either in
ASCending or DESCending order.

257
SIMPLE SQL

Example:
Let’s take an example of a table — Employee.
Currently, The Employee tables has the data as below:

Figure 8.10

Let’s create a column with a unique sequence of numbers based on the decreasing EmployeeID.
To do that, the below query will work:

SELECT EmployeeID,EmployeeName , Role


,ROW_NUMBER() OVER (ORDER BY EmployeeID DESC) AS RowNumber
FROM [MyEcommerceDB].[dbo].[Employee];

Basically, in the above query, we have used the ROW_NUMBER function OVER the sorted order
of decreasing EmployeeID to assign the unique number to each descending sorted record.

The results after executing the above query are displayed in Figure 8.11.

258
CHAPTER 8 - MASTERING SQL FUNCTIONS

Figure 8.11

Now, If I want to partition the dataset based on the values present in the Role column and
implement the ROW_NUMBER() function, then it will start the numbering for each partition and
then end numbering when that particular partition ends. This will be repeated for each partition
until all the partitions are assigned with some unique values.

Let me explain it with an example:

SELECT EmployeeID,EmployeeName , Role,ROW_NUMBER() OVER (PARTITION BY Role ORDER


BY EmployeeID DESC) AS RowNumber
FROM [MyEcommerceDB].[dbo].[Employee];

Below is the result of above query:

259
SIMPLE SQL

Figure 8.12

The above query will return datasets with multiple partitions over the Role column. And
the ROW_NUMBER() function will assign a unique incremental number to each record of that
partition.

RANK()
RANK() is a window function used to find out the rank of each record in the dataset. The
RANK() function returns an incremental ranking of values starting from 1 over a column.
The ordering of columns is mandatory to calculate the rank. Therefore ORDER BY clause is
mandatory to calculate the ranking of the dataset.
PARTITION BY clause is optional. Suppose we partition the dataset based on the values of
a column. It will restart the ranking from 1 for that particular partition. If we don’t mention the
partition, the system will consider the whole dataset as a single partition.
In the RANK() function, The ranking of two similar values or ties will be the same. But the
next ranking for the next values will be a total number of rows before that particular row in that
partition plus 1.

Syntax:
RANK() OVER ( [PARTITION BY Expression...] ORDER BY SortingExpr...)

Where,
Expression= The Column or value on which you want to do the partition.
SortingExpr= The Column or value on which you want to implement ORDER BY. Either
in ASCending or DESCending order.

260
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example: Creating Ranking on table values (Single Partition)

SELECT EmployeeID,EmployeeName , Role ,Salary

,RANK() OVER (ORDER BY Salary DESC) AS RankBySalary

FROM [MyEcommerceDB].[dbo].[Employee];

Results:

Figure 8.13

As you can see, the RANK() function has assigned a rank to each record based on the values
in the Salary column (See, Figure 8.13 for reference ). The numbering will begin from the 1st
record in the partition and continue until the partition is completed.

In this example, I have not explicitly mentioned the partition. Therefore, the whole dataset
acts as a single partition. Hence, the partition starts from 1 and is incrementing with +1 to the
last assigned rank. Now, if you look closely in a partition, you’ll observe that the RANK() func-
tion assigns the same rank to similar values. (Check in the table of Figure 8.13, that rank 13 is
assigned to four rows).
However, the next rank will be 17. That is the count of previous numbers plus 4.
It appears as if the number is skipped in the rankings. This will be repeated for an entire
partition.

261
SIMPLE SQL

Let me explain how the rankings will be when we have multiple partitions.
In case of RANK() function with multiple partitions. For each partition, The ranking will begin
from 1 and for the records with same values in the ordered column ( that’s ordered by ORDER
BY clause) it will have same rankings.
However, Whenever RANK() encounters a different value in the same partition for the
ordered column.
The ranking will be a number of rows before that particular row in that partition plus 1.

Example: Creating ranking on table data ( Multiple Partitions)

Ranking Within Subgroups with PARTITION BY


Let me create partition over the same dataset over the column DepartmentID.

SELECT EmployeeName,DepartmentID ,Role,Salary

,RANK() OVER (PARTITION BY DepartmentID ORDER BY Salary DESC) AS RankBySalary

FROM [MyEcommerceDB].[dbo].[Employee];

So, in above query, I have created partitions over DepartmentID. Also, I have added the
DepartmentID column in the SELECT list.
Now, for every partition, the ranking will be assigned by the rank function, and the ranking
will begin from and will end when the partition is finished. Then it will again begin from 1 and
then incrementally will assign rankings. In every partition the ranking will be based on the salary
of employees present in that partition.
The final results of the above query is displayed in Figure 8.14:

262
CHAPTER 8 - MASTERING SQL FUNCTIONS

Figure 8.14

PRO TIP:
While creating rankings, especially using the rank function. Try to visualize it in partitions.
When you start visualizing datasets, it becomes easier to play with the data.

DENSE_RANK()
DENSE_RANK() is a window function that is used to find out the rank of each record in
the partitioned dataset. The DENSE_RANK() function returns an incremental ranking of values
starting from 1 over a column.
The ordering of columns is mandatory to calculate the DENSE RANK. Therefore, ORDER BY
clause is mandatory to calculate the ranking of the dataset.
PARTITION BY clause is optional. For example, suppose we partition the dataset based on
the values of a column. It will restart the ranking from 1 for that particular partition. If we don’t
mention the partition, the system will consider the whole dataset as a single partition.
All the above properties of dense rank are similar to rank function. But in DENSE_RANK()
function, The ranking of two similar values or ties will be the same. But for the next ranking, the
next values will be the last ranking in that partition plus 1.

263
SIMPLE SQL

Syntax:
DENSE_RANK() OVER ( [PARTITION BY Expression...] ORDER BY SortingExpr[ASC |
DESC]...)

Where,
Expression= The Column or value on which you want to do the partition.
SortingExpr= The Column or value on which you want to implement ORDER BY. Either
in ASCending or DESCending order.

Example: Creating Dense Ranking on table values (Single Partition)

SELECT EmployeeID,EmployeeName,DepartmentID,Role,Salary
,DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRankBySalary
FROM [MyEcommerceDB].[dbo].[Employee];

In the above query, I have added DENSE_RANK() function in the SELECT part of the query.

Figure 8.15

And as you can see in the Figure 8.15, DENSE_RANK() function ranks the records with a
twist.
It assigns the same ranking to rows with the same values for the particular column. But the
ranking for the next value starts with the last ranking number plus 1.

264
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example: Creating Dense Ranking on table values (Multiple Partition) / Ranking Within
Subgroups

SELECT EmployeeID,EmployeeName,DepartmentID,Role,Salary
,DENSE_RANK() OVER (PARTITION BY DepartmentID ORDER BY Salary DESC) AS
DenseRankBySalary
FROM [MyEcommerceDB].[dbo].[Employee];

The final result of the above query will be:

Figure 8.16

As you can see in the Figure 8.16, that the rankings are now allocated for each partition.

The RANKING will be the same for values with same Salaries for records of the same department.

Basically, in DENSE_RANK(), the ranking for a single partition will always be the same for
records on which the order by clause is implemented. And whenever it encounters a different
value in that column, it will change the rank.

The new rank will be the last rank assigned to the previous record plus 1. In cases of multiple
partitions, the rank for each partition will always start from 1, and for the same values of the
ORDER BY Column, it will assign the same rank.

So, If you compare RANK() with DENSE_RANK(), you can say that rank allows a gap in the
ranking it creates. At the same time, DENSE_RANK()does not allow any gap in ranking.

265
SIMPLE SQL

NTILE()
NTILE() function is also a window function that helps in distributing data in groups. The num-
ber of groups needs to be specified in the NTILE() function. The records will be divided based
on the number we specify in the NTILE() function.

Syntax:
NTILE(NumberOfGroups) OVER ([PARTITION BY Expression, ... ] ORDER BY SortingExpr
[ASC | DESC]...,)

Where,
NumberOfGroups= The number of groups you want to divide your dataset into. Suppose
the total records are not evenly divisible by this number. Then the group’s size will be a mix of
larger and smaller groups.
Expression= The Column or value on which you want to do the partition.
SortingExpr= The Column or value on which you want to implement ORDER BY. Either
in ASCending or DESCending order.

NOTE: NTILE() function can only be implemented over an ordered list of data records.
Therefore, the ORDER BY clause is mandatory. PARTITION BY clause is optional.

Example:
SELECT EmployeeID,Role,DateOfBirth,
NTILE(2) OVER (ORDER BY DateOfBirth ASC) AS NTILEValue
FROM [MyEcommerceDB].[dbo].[Employee];

In the above query, I have used the NTILE(2) function with the NumberOfGroups value
as 2. This means the entire dataset will be divided into two groups. The data is sorted over the
column DateOfBirth.
The results after executing the above query are mentioned in Figure 8.17.

266
CHAPTER 8 - MASTERING SQL FUNCTIONS

Figure 8.17

The entire dataset is now divided into two different datasets.

Example: Distribute the query results coming from the Employee table into 4 groups using
NTILE() function.
SELECT EmployeeID,Role,DateOfBirth,
NTILE(4) OVER (ORDER BY DateOfBirth ASC) AS NTILEValue
FROM [dbo].[Employee];

267
SIMPLE SQL

Results:

Figure 8.18

DEALING WITH NULL VALUES USING FUNCTIONS


When dealing with huge amounts of data coming from different sources, that represents differ-
ent attributes of a particular entity. For example, we might get many NULL values in the table to
handle.
To deal with NULL values, we have different functions in SQL that can help.
I will explain different functions that help deal with NULL values one by one.

ISNULL function:
ISNULL function checks the first expression passed in the function, and then if the value of
the expression is in NULL, it replaces it with the value passed in the function.

Syntax:
ISNULL(Expression, ReplacingValue)

268
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example: Display First Name and Job Title from the table Employee. While displaying Replace
all the NULL values in the Location column and replace it with ‘_’

SELECT EmployeeName,Role,ISNULL (Location, ‘_’ ) AS LocationFixed


FROM [MyEcommerceDB].[dbo].[Employee];

NULLIF function:
NULLIF function is a bit different. It doesn’t work on NULL values. Instead, it generates a NULL
value when the expressions present in the NULLIF function don’t match.
Let me explain..
When the expression 1 and expression 2 in the NULLIF function are equal, the NULLIF func-
tion returns NULL. If it is not equal, then it returns the first expression.

Syntax:
NULLIF( Expr1, Expr2 )

Where,
Expr1: Expression 1, is the first expression in the NULLIF function.
Expr2: Expression 2, is the second expression in the NULLIF function.

Example:
SELECT NULLIF(‘DataCeps’, ‘DataCeps’ );

The result of above query using NULLIF function to compare two similar strings will be:
NULL

This is because both the strings are equal. Let’s change the string value in the 2nd expression
and then execute the query.

SELECT NULLIF(‘DataCeps’, ‘SQL’ );

The output of the above query is:


DataCeps

This is because when the strings of both the expression don’t match, the NULLIF function
returns the expression 1 only.

269
SIMPLE SQL

COALESCE function
COALESCE() function checks all the values present in the function and returns the first non-
NULL value encountered.

Syntax:
COALESCE(Value1,Value2,Value3, ...., Value(n));

Example:
SELECT COALESCE(NULL, NULL,’DataCeps.com’, NULL, ‘SQL Mastery’);

270
CHAPTER 8 - MASTERING SQL FUNCTIONS

EXERCISE
1) Find the ASCII Value of Character ‘D’?

2) Find the CHAR Value of ASCII Code ‘77’?

3) Find the position of the string value ‘ta’ in the main string ‘Dataceps’?

4) Find the substring pattern ‘ade’ in the main string ‘Dane Wade’ using the PATINDEX
function?

5) Extract and Display 4 Characters from the LEFT part of the main string ‘Data Is The Oil’

6) Extract and Display 4 Characters from the RIGHT part of the main string ‘Data Is The Oil’?

7) Replicate the String ‘DATA’ 5 Times using SQL function.

8) Display the string ‘DATA’ in reverse?

9) Put the string “Data Is The New Oil” inside square brackets.

10) Stuff the value “Future” in the place of “New Oil” in the main string “Data Is The New Oil”

11) Convert and Display the character strings ‘data is the new oil’ in uppercase.

12) Display your current system date with time?

13) Return the DAY from the date ‘2022-12-25’.

14) Select and display which week in the year it is, for the date – ‘2022-12-25’.

15) Add 7 Days in the date ‘2022-12-25’

16) Calculate the difference between the two date values in days -- ‘2015-12-15’ and ‘2018-12-17’.

17) Create a function that returns the MAX Salary from the Employee table.

18) On Employee Table, Display all columns along with row numbers over partition of
DepartmentID and Order by Salary lowest to highest.

271
SIMPLE SQL

19) On Employee Table , Display all columns along with Rankings over partition of
DepartmentID and Order by salary lowest to highest.

20) On Employee Table , Display all columns along with dense rankings over partition of
DepartmentID and Order by salary lowest to highest

21) Display First Name, Department and Job Title from the table Employee. While dis-
playing Replace all the NULL values in the Department column and replace it with ‘NA’

272
CHAPTER 8 - MASTERING SQL FUNCTIONS

ANSWERS
1)
SELECT ASCII(‘D’);

2)
SELECT CHAR(‘77’);

3)
SELECT CHARINDEX(‘ta’,’DataCeps’);

4)
SELECT PATINDEX(‘%ade%’,’Dane Wade’);

5)
SELECT LEFT (‘Data Is The Oil’,4);

6)
SELECT RIGHT (‘Data Is The Oil’,4);

7)
SELECT REPLICATE (‘DATA’,5);

8)
SELECT REVERSE (‘DATA’);

9)
SELECT QUOTENAME(‘Data Is The New Oil’,’[]’);

10)
SELECT STUFF (‘Data Is The New Oil’,13,7,’Future’);

273
SIMPLE SQL

11)
SELECT UPPER (‘Data Is The New Oil’);

12)
SELECT SYSDATETIME();

13)
SELECT DATENAME( DAY,’2022-12-25’);

14)
SELECT DATENAME(WEEK,’2022-12-25’);

15)
SELECT DATEADD(DD,7,’2022-12-25’);

16)
SELECT DATEDIFF(DAY,’2015-12-15’,’2018-12-17’);

17)
CREATE FUNCTION MaxSalary ()
RETURNS INT
AS
BEGIN

RETURN (SELECT MAX(Salary)


FROM [MyEcommerceDB].[dbo].[Employee])

END

274
CHAPTER 8 - MASTERING SQL FUNCTIONS

18)
SELECT *, ROW_NUMBER() OVER ( PARTITION BY DepartmentID ORDER BY Salary ASC) AS
RowNumberRankings
FROM Employee;

19)
SELECT *, RANK() OVER ( PARTITION BY DepartmentID ORDER BY Salary ASC) AS
Rankings
FROM Employee;

20)
SELECT *, DENSE_RANK() OVER ( PARTITION BY DepartmentID ORDER BY Salary ASC) AS
Rankings FROM Employee;

21)
SELECT EmployeeName,ISNULL (DepartmentID, ‘NA’ ) AS DepartmentID
FROM [MyEcommerceDB].[dbo].[Employee];

275
SQL
CHAPTER 9

LEVELLING UP
THE GAME WITH SUBQUERIES

A fter learning about various operators, functions and playing with data, I am sure your con-
fidence level is up, and you’re fired up to learn some more advanced-level stuff. Until now,
we have been working with a single dataset and playing with the data present in that.
As you’re leveling up, I want you to become a pro in SQL. So, it becomes my duty to teach
you how to work with multiple datasets. See, in real-life scenarios, you will have to work with
multiple datasets to compare, contrast and combine various datasets.

Below are the different ways we can use to work with multiple datasets:

a) Subqueries
b) Set Operators: UNION,UNION ALL,INTERSECT,MINUS.
c) Joins: LEFT JOIN, RIGHT JOIN, INNER JOIN and RIGHT JOIN.

This chapter is dedicated to teaching you how to combine, compare, and contrast multiple
datasets using SQL subquery.

What is a SUBQUERY?
A subquery is basically a query within another query, Also known as a nested query.
A subquery is helpful when we want to compare the results of the main query, with some
other dataset. Also, the subquery can be helpful in filtering data and generating temporary val-
ues. Basically, a subquery allows us to work with multiple datasets simultaneously.
Working with a subquery is relatively easy; however, you need to consider a few rules to
work efficiently with SQL subqueries.

277
SIMPLE SQL

These rules are:

a) First, the subquery is executed , and then the resultset of that inner subquery is used by
the outer query.
b) Always enclose the subquery with parenthesis ( ).
c) Always keep subquery on the right side of the comparison operators
d) The inner subquery can’t use ORDER BY. However, it can be used by the OUTER main
query.
e) Only use single-row operators with subqueries that return single rows. Use multiple-row
operators when subqueries return multiple rows.

Figure 9.1

EXPLORING POSSIBILITIES WITH SUBQUERIES

Filtering Data With Subqueries (in the WHERE clause):


A subquery similarly returns the dataset as a normal query does.
Subqueries can be used after the WHERE clause to get the desired dataset we want to extract,
and then that extracted dataset can be used with SELECT, INSERT, DELETE and UPDATE
statements.

Subqueries Syntax with SELECT:


SELECT ColumnName
FROM NameOfTheTable
WHERE ColumnName OPERATOR
(SELECT Column_Name FROM Table_Name WHERE..);

278
CHAPTER 9 - LEVELLING UP THE GAME WITH SUBQUERIES

Subqueries Syntax with UPDATE:


UPDATE NameOfTheTable
SET ColumnName =’New Value’
WHERE ColumnName OPERATOR
(SELECT Column_Name FROM Table_Name WHERE..);

Subqueries Syntax with DELETE:


DELETE FROM NameOfTheTable
WHERE ColumnName OPERATOR
(SELECT Column_Name FROM Table_Name WHERE..);

Where,
OPERATOR = You can use different comparison operators like IN, BETWEEN <,>, =,<=
and >=.

As you can see, in all the above types, the subquery is used after the WHERE clause, and it is
helping us determine the final dataset on which our outer query will be working.
It returns the dataset to our outer main query. And the returned dataset of Subqueries can
have a single value, and it can also return multiple values.

Example: Only using subqueries, Display Employee ID, Birthdate and Job Role of Employees,
who have birthdate greater than the date ‘1970-12-31’.

SELECT EmployeeID,DateOfBirth,Role
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE EmployeeID IN
(SELECT EmployeeID
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DateOfBirth>’1970-12-31’);

As you can see in the above-mentioned query. We are getting data for only the EmployeeID
column who have Birthdate Greater than the value ‘1970-12-31’. And then, we take the results
of the subquery and then extract Employee ID, Birthdate, and Job Role columns for those par-
ticular EmployeeID that are coming from the subquery results.
This is just a simple example to understand the concept of subquery. However, the best way
to get the above final result can be done using a single query, like this:

279
SIMPLE SQL

SELECT EmployeeID,DateOfBirth,Role
FROM [MyEcommerce].[HumanResources].[Employee]
WHERE BirthDate>’1970-12-31’

Subqueries help us compare and contrast multiple datasets. The previous example dealt with
the same table’s data. Now let me level this up and bring in another table. And I will show you
how you can work with multiple datasets ( Coming from two different tables).

Example: Employee data is present in the Employee table, and Department Data like
Department ID and Department Name is in the Department table. Both tables have a common
column that helps link the data of the two tables, which is the DeptID of the Department
table. Using subqueries, display the department names of the employees who have job roles as
“Product Designer.”

SELECT DeptID,DepartmentName
FROM [MyEcommerceDB].[dbo].[Department]
WHERE DeptID IN
(SELECT DepartmentID
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Role=’Product Designer’);

In the above requirement, you can observe that we need to display the final results by com-
bining two different datasets. In the subquery, I am extracting the Department ID from the
Employee table that has a ‘Product Designer’ role. And then simply displaying the Department
Names and IDs of those departments in the main query results.

Example:
Display the Department ID and the Department Name from the Department table for the
employees with the location as ‘Sydney.’

Approach: To display the Department ID and Department Name, we need to extract the depart-
ment IDs of employees who have a location as ‘Sydney.’ Then those Department IDs can be fur-
ther used to display the Department name from the table Department.

280
CHAPTER 9 - LEVELLING UP THE GAME WITH SUBQUERIES

SQL query for this requirement is:

SELECT DeptID,DepartmentName
FROM [MyEcommerceDB].[dbo].[Department]
WHERE DeptID IN
(SELECT DISTINCT(DepartmentID)
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Location LIKE ‘Sydney’);

As you can observe, we are extracting multiple rows from the inner subquery. So, we can
extract multiple values from the inner subquery and use that data to get the desired data.

Generate Calculated Columns With Subquery ( Using Subquery in the


SELECT)
In the previous section, I introduced subqueries that were used after the WHERE clause. It was
used liked that because we were trying to pull the result set of the subquery, and then based on
those results, the final result set was displayed.
In this section, We will be using a subquery to generate some calculated columns. And these
Newly generated columns will be used along with already existing columns of the main query.

Let me explain with an example:

Example: Display the average salary by the department along with the average salary of the
whole company.

Approach:
In this requirement, we know that displaying the average salary by the department can be easily
calculated by grouping the department ( using GROUP BY) and then simply calculating the aver-
age salary using AVG() function.

Below query can display average salary by department:

SELECT DepartmentID,AVG(Salary) AS DeptAVGSalary


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY DepartmentID;

281
SIMPLE SQL

But the twist is to display the average salary of the whole company along with the average
by each department.
What we can do here is, take another query that calculates the average salary of all the
employees in the company. The below query can extract and display the average salary of all the
employees in the employee table:

SELECT AVG(Salary) FROM [MyEcommerceDB].[dbo].[Employee];

We can just simply put that query in the SELECT statement of the main query, that was cal-
culating the average salary by the department.

SELECT DepartmentID,AVG(Salary) AS DeptAVGSalary, ( SELECT AVG(Salary) FROM


[MyEcommerceDB].[dbo].[Employee]) AS CompanyAVGSalary
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY DepartmentID;

So, That’s how we can create calculated columns with the help of subqueries.
Subqueries provide us the flexibility to work with multiple datasets with ease. This flexibility
of working with multiple datasets helps carry out useful insights from the data. So whenever you
need to work with various datasets, you can always use subqueries in your SQL code.
In the upcoming chapters, You will discover the other options that will help you work with
multiple datasets.

282
CHAPTER 9 - LEVELLING UP THE GAME WITH SUBQUERIES

EXERCISE
1) Using subqueries , Display the Employee Name and Department ID for People With Role Of
a Project Manager

2) Display All the details of Employee who are working in ‘Marketing’ Department.

283
SIMPLE SQL

ANSWERS
1)
SELECT DeptID,DepartmentName FROM Department
WHERE DeptID IN
(SELECT DepartmentID
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Role=’Project Manager’);

2)
SELECT * FROM Employee
WHERE DepartmentID IN
( SELECT DeptID FROM Department WHERE DepartmentName=’Marketing’)

284
SQL
CHAPTER 10

SQL JOINS MADE EASY

A s you learned in the previous chapter, Using subqueries we can Combine multiple datasets
to extract the desired outcome. It is one of the most valuable and powerful things that we
can do in SQL.
In SQL, we can also combine datasets with the help of JOINS.
JOINS works similar to subqueries, but if you want good performance, then JOINS is always
a better choice. Every complex query usually uses multiple joins, and multiple joins make a query
complex. (You see what I did there? )
Learning and implementing JOINS is one of the most important things. Unfortunately, I
have seen many developers struggling with JOINS and often try to mug up the concept and not
effectively use it.

WHY DO WE NEED JOINS?


Suppose we are working with 2 tables: Employee and Department. The table schema of
the employee table looks something like this:

Figure 10.1

Now, the department table looks something like this:

Figure 10.2

So, If I want to extract the Employee related data from the Employee table, it requires only
a single query.
However, when I want to get the employee name, job role, and the Department’s Name, then
combing the datasets from both the tables using JOINS is the only and the best way.

285
SIMPLE SQL

UNDESTANDING JOINS
A JOIN helps combine two more datasets based on a specified condition on the column.
To combine multiple datasets Cartesian product of data sets is used, and then we implement
the specified condition on the final results to filter out the unnecessary rows.
In order to combine datasets, First, you need to learn about the cartesian product of rela-
tional algebra.
Yes, there is an algebra that’s used to combine relations/tables. (Don’t freak out if you hate
maths, It’s easier than you think). If you understand this concept well, everything else will be a
cakewalk for you.

So, Let’s get started...

When we are JOINING two datasets, we are simply working on a relational model, and each
dataset is a set of data that describes an entity. Cross Product or Cartesian product is simply
the multiplication of each and every record from the 1st table/set with each record present in the
2nd table/set.

Let me explain the cartesian product with 2 sets: Persons and Actions.

Figure 10.3

If we want the Cartesian product of the above two sets— ( i.e.: Persons X Actions) .
it will look something like Figure 10.4

Figure 10.4

286
CHAPTER 10 - SQL JOINS MADE EASY

So, you can see that each record from the first table is multiplied by each record present in
the second table. Cartesian product is popularly known as CROSS product. The final outcome
of this cross product is in Figure 10.5.

Figure 10.5

Now, let’s get back to the concept of joins .There are Multiple Types of joins in SQL to com-
bine different datasets. However, to keep things beginner-friendly this chapter, I will be teach-
ing the below JOINS:

A) CROSS JOIN
B) INNER JOIN
C) OUTER JOINS
i) Left outer joins
ii) Right outer joins
iii) Full outer joins

NOTE: Internally, All types of JOINS combine multiple tables using the cartesian product and
then apply specific conditions based on what we want to see in the final combined dataset.

287
SIMPLE SQL

THE CROSS JOIN


The CROSS JOIN between two tables is simply the CROSS PRODUCT of two table’s records.
It generates a combination of each record from the first table with each record from the second
table. That means if the 1st table has “m” records and the 2nd table has “n” records, then the
total number of records after cross join will be mXn.

Syntax:
SELECT Column1, Column2...ColumnNameN
FROM [Table1]
CROSS JOIN [Table2];

Let’s understand the CROSS JOIN with an example:

Let’s consider the two tables – Employee and Department. If I want to implement the CROSS
JOIN on these two tables using the CROSS-JOIN Syntax.

The final query will look something like:

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
CROSS JOIN [MyEcommerceDB].[dbo].[Department];

The CROSS JOIN query will give us all the data after combining CROSS PRODUCT. The
result of the above query are in Figure 10.6.a and Figure 10.6.b .

Figure 10.6.a

288
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.6.b

The customer table had 20 rows, and the department table had a total of 4 rows.

So, the total number of rows in CROSS JOIN is 20 x 4 à80 rows.

If you want to select only a specific column from the final result set, you will need to tweak
the above query a little bit. To do that, First, we need to make the table alias for the Employee
table as EMP and Department table as DEPT.

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
CROSS JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT;

OR

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee] EMP
CROSS JOIN [MyEcommerceDB].[dbo].[Department] DEPT;

Then select only those columns from those tables that you want to include in your final resultset.

SELECT EMP.EmployeeName,DEPT.DepartmentName
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
CROSS JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT;

289
SIMPLE SQL

EMP is the alias for table Employee, and EmployeeName is the column from the dataset
Employee. The way we can access the column from the given table is:

TableAliasName.ColumnName.

INNER JOIN
INNER JOIN selects all the matching rows that are present in both tables. This JOIN is depen-
dent upon a common column present in both tables. So, whenever we want to combine two
datasets and return the records that are present in both the tables, then INNER JOIN is the best
choice.

The basic syntax for INNER JOIN is:

SELECT ColumnNames
FROM [Table1]
INNER JOIN [Table2]
ON Table1.ColumnA=Table2.ColumnB;

Let’s consider, two tables Table 1 and Table 2, and I want to JOIN these tables using INNER
JOIN over a related common column. Now, the final output after joining these two tables must
only display the records present in both the tables.
All the other records present in Table1 or even in Table 2 that are not matching will not be
displayed in the final result after implementing the join.
Please check the diagram in Figure 10.7 that illustrates the INNER JOIN in a much better
way!

290
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.7

The intersection part represents the common records in the column on which we imple-
mented the INNER JOIN. Internally, each record from the left table is matched with each record
of the second table. (Cartesian Product)
Then only the matching records present in the related column are selected and displayed in
the final results.

Let me explain it with an example:

Figure 10.8

Figure 10.9

To JOIN the above two tables, first, we need to identify a common related column between
them. (The column will be the link for JOINing both tables). The common related column will
be PersonID from the Person table and PersonID from the Actions table.

291
SIMPLE SQL

NOTE: I have added a new column in the Actions table to make you understand this JOIN
concept easily.
This new PersonID column will help to establish the between these two tables easily.

If we want to join these tables using INNER JOIN, then the INNER JOIN syntax will be:

SELECT *
FROM Person P
INNER JOIN Actions A
ON P.PersonID=A.PersonID;

Now, internally all the records from the first table will be multiplied with all the records from
the 2nd table using the cartesian product. ( See Figure 10.10 for Cartesian product results) .

Figure 10.10

The first record of the Person table is multiplied with all the 3 records of the Actions
table. Then, the 2nd record is multiplied with all the 3 records of the Actions table.
The count of records coming from the table Person is 2, and the count of records present
in table Actions is 3. Now, the total number of records in the CROSS PRODUCT of both the
tables is 2 x 3, i.e.:- 6 records.
But as per the INNER JOIN condition, only the records present in both the columns
PersonID ( Actions Table) and PersonID (Person Table) will be selected and displayed in
the outcome. (Figure 10.11 )

292
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.11

So, the actual final outcome of the INNER JOIN is displayed in Figure 10.12.

Figure 10.12

To make this concept much more solidified in your mind, let me explain it with another prac-
tical example:

Let’s retake the Employee and Department table.

Suppose, I want to join these two tables, I will first find the related column, which will act as
the main link for our inner join. The above tables show that the common related column between
these two tables is the DepartmentID column from the Employee table and DeptID from the
Department table. These two columns are related and will link to join both the Department
table and Employee table.

Now, the INNER JOIN condition will be made on these columns.

293
SIMPLE SQL

Hence the final query after implementing the INNER JOIN will look something like this:

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
INNER JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT
ON DEPT.DeptID=EMP.DepartmentID ;

Where the condition is over the related columns DEPT.DeptID=EMP.DepartmentID.


This represents that the output of the INNER JOIN will only SELECT matching records
present in both the tables for the columns DeptID and DepartmentID.

The output of the above query is displayed in Figure 10.13 .

Figure 10.13

OUTER JOINS
As you might have observed in INNER JOIN, we combine the records based on CROSS
PRODUCT. INNER JOIN is then only displaying records that are matching for the related col-
umns in both tables. It never shows the unmatched records in the final outcome present in LEFT
or RIGHT tables.
When a join also includes unmatched records in the final result, that join is considered an
OUTER JOIN.

294
CHAPTER 10 - SQL JOINS MADE EASY

There are primarily 3 types of JOINS present:

LEFT OUTER JOIN: LEFT JOIN returns all records from the LEFT table (even the
unmatched records) and, only the matching ones from the RIGHT table.
RIGHT OUTER JOIN: RIGHT JOIN returns all records from the RIGHT table (even the
unmatched records) and , only matching ones from the left table.
FULL OUTER JOIN: FULL OUTER JOIN basically returns all records from both LEFT and
the RIGHT table.

Now, let me explain each join one by one…

LEFT OUTER JOIN


LEFT OUTER JOIN selects all the records present in the left tables and only the matched
records present in the right table. This JOIN is also dependent upon a common column present
in both tables.
In other words, LEFT JOIN is when in Addition to INNER JOIN results, we include the all
records present in the LEFT tables as well, even though they’re not matching with any record of
RIGHT table records.

The basic syntax for LEFT OUTER JOIN is:

Syntax:
SELECT ColumnNames
FROM [Table1]
LEFT OUTER JOIN [Table2]
ON Table1.ColumnA=Table2.ColumnB;

Please check the diagram in Figure 10.14 that illustrates the LEFT join in a much better way!

Figure 10.14

295
SIMPLE SQL

Let’s take the example of the Actions and Persons table again, and To create some
unmatched combinations, I have added some records in both tables.

Figure 10.15

Figure 10.16

Now, internally all the records from the first table will be multiplied by all the records from
the 2nd table uses the cartesian product.

The cartesian product of the above tables is displayed in figure 10.17:

296
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.17

First, Matched records in the left and right table for the columns PersonID ( Actions
Table) and PersonID(Person Table) will be selected internally.

Then, As per the LEFT OUTER JOIN condition, even the unmatched records present in the
LEFT table will be included in the final outcome. It will return NULL values for all columns com-
ing from the RIGHT table in the final outcome of the LEFT OUTER JOIN for these unmatched
records.

297
SIMPLE SQL

So, the final outcome of the LEFT OUTER JOIN for the above two tables will be:

Figure 10.18

I hope you have now understood the concept of LEFT OUTER JOIN. Still, I want you to
become the best in this game! That’s why I will show you another example.

Example:
Let’s take the example of Employee and Department table again.
Suppose, If I want to join these two tables, I will first find the related column, which will act
as the main link for our LEFT OUTER JOIN. From the above tables, it is pretty obvious that
the common related column between these two tables is the DepartmentID column from the
Employee table and DeptID from the Department table. These two columns are related and
will link to join both Department and Employee tables.

Now, we want to implement LEFT OUTER JOIN condition on these columns. Hence the final
query after implementing the LEFT JOIN will look something like this:

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
LEFT OUTER JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT
ON DEPT.DeptID=EMP.DepartmentID ;

Where the condition is over the related columns DEPT.DeptID=EMP.DepartmentID.

298
CHAPTER 10 - SQL JOINS MADE EASY

This represents that the output of the LEFT OUTER JOIN will SELECT all records present
in LEFT table along with only the matched records present in the RIGHT table for the columns
DeptID and DepartmentID.
Hence, The final output of the above query is displayed in figure 10.19:

Figure 10.19

RIGHT OUTER JOIN


RIGHT OUTER JOIN selects all the records present in the RIGHT table and only the matched
records present in the LEFT table. This JOIN is also dependent upon a common column present
in both the tables.
In other words, RIGHT JOIN is when, in Addition to INNER JOIN results, we include the
records present in the RIGHT tables even though they’re not matching with any record of LEFT
table records.

The basic syntax for RIGHT OUTER JOIN is:

Syntax:
SELECT ColumnNames
FROM [Table1]
RIGHT OUTER JOIN [Table2]
ON Table1.ColumnA=Table2.ColumnB;

299
SIMPLE SQL

Figure 10.20

Let’s take the example of the Actions and Persons table again, (Figure 10.15 and 10.16 )
Now, internally all the records from the first table will be multiplied by all the records from the
2nd table using the cartesian product.

300
CHAPTER 10 - SQL JOINS MADE EASY

The cartesian product of the above tables is displayed in Figure 10.21.

Figure 10.21

First, Matched records in the left and right table for the columns PersonID ( Actions
Table) and PersonID(Person Table) will be selected internally.
Then, As per the RIGHT OUTER JOIN condition, even the unmatched records present in the
RIGHT table will be included in the final outcome. However, it will return NULL values for all
columns coming from the LEFT table in the final outcome of the RIGHT OUTER JOIN for these
unmatched records.
So, the final outcome of the RIGHT OUTER JOIN for the above two tables will be:

301
SIMPLE SQL

Figure 10.22

Example :
Let’s take the Employee and Department table again.
If I want to join these two tables, I will first find the related column, which will act as the
main link for our RIGHT OUTER JOIN.
In the above tables the common related column between these two tables is the DepartmentID
column from the Employee table and DeptID from the Department table. These two col-
umns are related and will link to join both the Department table and Employee table.

Now, the RIGHT OUTER JOIN condition will be made on these columns.

Hence the final query after implementing the RIGHT JOIN will look something like this:

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
RIGHT OUTER JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT
ON DEPT.DeptID=EMP.DepartmentID ;

Where the condition is over the related columns DEPT.DeptID=EMP.DepartmentID.


This represents that the RIGHT OUTER JOIN output will SELECT all records present in
RIGHT tables and the only the matched records present in the LEFT table.

The final output of the above query is displayed in Figure 10.23:

302
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.23

FULL OUTER JOIN


FULL OUTER JOIN selects all the matched and unmatched records present in both tables.
This JOIN is also dependent upon a common column present in both the tables. So, whenever we
want to combine two datasets and return the matched and unmatched records present in both
tables, FULL OUTER JOIN or FULL JOIN is the best choice.
In other words, FULL OUTER JOIN is when in Addition to INNER JOIN results, we include
the unmatched records that are present in both LEFT and RIGHT tables.

The basic syntax for FULL OUTER JOIN is:

Syntax:
SELECT *
FROM Persons P
FULL OUTER JOIN Actions A
ON P.PersonID=A.PersonID;

303
SIMPLE SQL

Figure 10.24

Let’s take the example of the Actions and Persons table again,
Now, internally all the records from the first table will be multiplied with all the records from
the 2nd table using the cartesian product.
The cartesian product of the above tables is displayed in the Figure 10.25:

304
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.25

Matched records in the LEFT and RIGHT table for the columns PersonID ( Actions
Table) and PersonID(Person Table) will be selected internally.
But as per the FULL OUTER JOIN condition, even the unmatched records present in both
tables are returned in the final outcome.
In the Figure 10.24 You can see that PersonID 3 (in LEFT table) has no match in the
RIGHT table. Similarly NULL from the LEFT table has no matching records in the LEFT table.
In such cases, these unmatched records will still be included in the final outcome.

305
SIMPLE SQL

However, The unmatched records in LEFT will have NULL values for the columns of the
RIGHT table and, the unmatched records in the RIGHT table will have NULL values for the
columns of the LEFT table.
So, the final outcome of the FULL OUTER JOIN for the above two tables will look some-
thing like Figure 10.26.

Figure 10.26

Let’s take another example to understand the concept of FULL OUTER JOIN.
Let’s take the Employee and Department table again.
Suppose, I want to join these two tables, I will first find the related column, which will act as
the main link for our FULL OUTER JOIN.
In the above tables the common related column between these two tables is the DepartmentID
column from the Employee table and DeptID from the Department table.
Now, the FULL OUTER JOIN condition will be made on these columns. For this par-
ticular example, I am pulling Employee ID ,Employee Name From the Employee Table and
Department Name from the Department table.

Hence the final query after implementing the FULL OUTER JOIN will look something like
this:

SELECT EMP.EmployeeID,EmployeeName,DEPT.DepartmentName
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
FULL OUTER JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT
ON DEPT.DeptID=EMP.DepartmentID ;

The final output of the above query is displayed in Figure 10.27.

306
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.27

As you can see in the output that the FULL OUTER JOIN Displayed Employee ID, Employee
Name from the Employee tables and Department Name from the Department table.
Working with multiple datasets seems quite daunting initially to some people, but I believe
it is the most important thing one can learn and master in SQL. This is because most complex
queries are built on JOINING multiple datasets.
Combining multiple datasets can help us in gaining more insights from data. It allows relat-
ing one entity’s data with another entity. In this chapter, I explained to you about joining two
datasets with each other using different joins that SQL offers. If you want, you can try joining
more tables as well. You can have multiple joins in a SQL query. The number of tables and joins
depends on what data you want to include in your outcome.

307
SIMPLE SQL

EXERCISE
SCENARIO #1:
Author

AuthorID Name Email Country BookID


A1111 Dane abc@gmail.com United States B3
A1112 Russell def@gmail.com United Kingdom NULL
A1113 Will ijk@gmail.com Canada B1
A1114 Chris lmn@gmail.com United States B2

Book

BookID Name Category Pages


B1 Keto For Beginners Weight Loss 200
B2 How To Grow Vegetables Gardening 150
B3 SQL for Begginers Computers And Technology 300

After Creating the above tables in your database, implement the below mentioned joins:

a) CROSS JOIN between Book and Author tables and display all Columns in the final result
set.
b) INNER JOIN between Book and Author and display Author Name and Book Name and
Pages Column in the final results.
c) LEFT JOIN between Book and Author table. Also, display all records from Author Table
and only category from books table.
d) RIGHT JOIN between Book and Author table. Also, display Author Name, Email from
author table and, all columns from the books table.

SCENARIO #2

Country

CountryID CountryName Continent CityID


CY111 Serbia Europe NULL
CY112 United States Of America North America CT1
CY113 Poland Europe NULL
CY114 Bulgaria Europe NULL
CY115 Canada North America CT2

308
CHAPTER 10 - SQL JOINS MADE EASY

City

CityID CityName AverageIncome


CT1 New York 32320
CT2 Vancouver 48682
CT3 London 39700

After Creating the above tables in your database, implement the below mentioned joins:

a) CROSS JOIN between Country and City and display all Columns in the final result set.
b) INNER JOIN between Country and City , then display Country Name From Country
Table with City Name and Average Income From City Table.
c) LEFT JOIN between Country and City table. Then, display all columns from Country
Table and only City Name from City table.
d) RIGHT JOIN between Country and City table. Then, display Country Name, Continent
from Country table and, City Name from the City table.

309
SIMPLE SQL

ANSWERS
SCENARIO #1:
In the database MyEcommerceDB, Create Book and Author tables.

CREATE TABLE Book


(
BookID nvarchar(25) PRIMARY KEY,
BookName varchar(50),
Category varchar(55),
Pages int
);

INSERT INTO Book


(BookID,BookName,Category,Pages)
VALUES
(‘B1’,’Keto For Beginners’,’Weight Loss’,’200’),
(‘B2’,’How To Grow Vegetables’,’Gardening’,’150’),
(‘B3’,’SQL for Begginers’,’Computers And Technology’,’300’);

CREATE TABLE Author


(
AuthorID nvarchar(20) PRIMARY KEY,
AuthorName varchar(50),
Email nvarchar(60),
Country varchar(80),
BookID nvarchar(25) FOREIGN KEY REFERENCES dbo.[Book] (BookID)
);

INSERT INTO Author (AuthorID,AuthorName,Email,Country,BookID)


VALUES
(‘A1111’,’Dane’,’abc@gmail.com’,’United States’,’B3’),
(‘A1112’,’Russell’,’def@gmail.com’,’United Kingdom’,NULL),
(‘A1113’,’Will’,’ijk@gmail.com’,’Canada’,’B1’),
(‘A1114’,’Chris’,’lmn@gmail.com’,’United States’,’B2’)

310
CHAPTER 10 - SQL JOINS MADE EASY

Then,

INNER JOIN:
SELECT A.AuthorName,B.BookName,B.Pages
FROM Author A INNER JOIN Book B
ON A.BookID=B.BookID

LEFT JOIN:
SELECT A.AuthorID, A.AuthorName,A.Email,A.Country,A.BookID,B.Category
FROM Author A
LEFT JOIN Book B
ON A.BookID=B.BookID

RIGHT JOIN:
SELECT A.AuthorName,A.Email,A.Country,A.BookID,B.BookName,B.Category,B.Pages
FROM Author A
RIGHT JOIN Book B
ON A.BookID=B.BookID

SCENARIO #2:
CREATE TABLE City
(
CityID nvarchar(22) PRIMARY KEY,
CityName nvarchar(22),
AverageIncome money
);

INSERT INTO City


(CityID,CityName,AverageIncome)
VALUES (‘CT1’,’New York’,’32320’),
(‘CT2’,’vancouver’,’48682’),
(‘CT3’,’London’,’39700’);

311
SIMPLE SQL

CREATE TABLE Country


(
CountryID nvarchar(25) PRIMARY KEY,
CountryName varchar(55),
Continent varchar(55),
CityID nvarchar(22) FOREIGN KEY REFERENCES City(CityID)
);

INSERT INTO Country


(CountryID,CountryName,Continent,CityID)
VALUES
(‘CY111’,’Serbia’,’Europe’,NULL),
(‘CY112’,’United States Of America’,’North America’,’CT1’),
(‘CY113’,’Poland’,’Europe’,NULL),
(‘CY114’,’Bulgaria’,’Europe’,NULL),
(‘CY115’,’Canada’,’North America’,’CT2’);

Then,

CROSS JOIN:
SELECT * FROM Country CY CROSS JOIN City CT
INNER JOIN:
SELECT CY.CountryName,CT.CityName,CT.AverageIncome
FROM Country CY
INNER JOIN City CT
ON CY.CityID=CT.CityID;

LEFT JOIN:
SELECT CY.CountryID,CY.CountryName,CY.Continent,CT.CityName,CT.CityID
FROM Country CY
LEFT JOIN City CT
ON CY.CityID=CT.CityID;

RIGHT JOIN:
SELECT CY.CountryName,CY.Continent,CT.CityName FROM Country CY
RIGHT JOIN City CT
ON CY.CityID=CT.CityID;

312
SQL
CHAPTER 11

SETS IN SQL

S QL is all about working with data; we play with data sets and get the desired dataset by
implementing multiple operations, joins, functions, and whatnot! A dataset in SQL is the
outcome of a SQL SELECT statement. Whenever we run a SQL query to get some output, we
get a SET of data or dataset. In live projects, We have to combine multiple result sets to get the
desired outcome.
To work effectively with multiple datasets, we have 4 different types of SET operators in
SQL, mentioned below:

UNION
In SQL, The UNION operator helps combine two result sets coming from 2 different SQL
SELECT statements.
The condition for UNION is that it combines only those result sets that have the same number
of columns, and the datatype for those columns should also be the same in both the result set.
While combining similar datasets, the possibility of duplicate records arises. But if we use the
UNION operator, it automatically removes all the duplicate records.
Figure 11.1 illustrates the UNION operator in a better and easier way!

Figure 11.1

313
SIMPLE SQL

Syntax of UNION:
SELECT ColumnName FROM Table1
UNION
SELECT ColumnName FROM Table2;

Example:
Let’s consider two tables, Location1, and Location2. Both the tables have a LocationID
column with LocationName and contain the list of cities present in the united states.

Location1 table:

Figure 11.2

Location2 table:

Figure 11.3

SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location1]
UNION
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location2];

314
CHAPTER 11 - SETS IN SQL

Final Results:

Figure 11.4

UNION ALL
The UNION operator also helps combine two different result sets coming from 2 different
SQL SELECT statements. But it doesn’t remove the duplicates from the final result set.
Figure 11.5 illustrates the UNION operator in a better and easier way!

Figure 11.5

Syntax of UNION ALL:


SELECT ColumnName FROM Table1
UNION ALL
SELECT ColumnName FROM Table2;

315
SIMPLE SQL

Example: Combine the tables Location1 and Location2 using UNION ALL operators.
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location1]
UNION ALL
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location2];

Figure 11.6

INTERSECT
INTERSECT operation combines two result sets but only returns the common result set in
the outcome. INTERSECT operator also combines the data sets with the same datatype and the
same number of columns.
Figure 11.7 illustrates the UNION operator in a better and easier way!

Figure 11.7

316
CHAPTER 11 - SETS IN SQL

Syntax of INTERSECT:
SELECT ColumnName FROM Table1
INTERSECT
SELECT ColumnName FROM Table2;

Example:
Intersect the tables Location1 and Location2.

SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location1]
INTERSECT
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location2];

Final Results:

Figure 11.8

EXCEPT
The EXCEPT set operator in SQL, combines two sets but only returns the records present in
one set that are not in the second one. If we have a set A and B, then it will return the records
that are present in set A and are absent in set B.

Figure 11.9 illustrates the UNION operator in a better and easier way!

317
SIMPLE SQL

Figure 11.9

Syntax of EXCEPT:
SELECT ColumnName FROM Table1
EXCEPT
SELECT ColumnName FROM Table2;

Example: Use Except operator for queries returning the data from the tables Location1 and
Location2.
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location1]
EXCEPT
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location2];

Final Outcome:

Figure 11.10

318
CHAPTER 11 - SETS IN SQL

EXERCISE
SCENARIO #1:
Author

AuthorID Name Email Country BookID


A1111 Dane abc@gmail.com United States B3
A1112 Russell def@gmail.com United Kingdom NULL
A1113 Will ijk@gmail.com Canada B1
A1114 Chris lmn@gmail.com United States B2

NewAuthor

AuthorID Name Email Country BookID


A1111 Dane abc@gmail.com United States B3
A1117 Tedd opq@gmail.com Canada NULL
A1115 Barney rst@gmail.com Canada NULL
A1114 Chris lmn@gmail.com United States B2

1. After Creating the above tables in your database and inserting the records, implement the
below mentioned operations on the datasets:
1) UNION
2) UNION ALL
3) INTERSECT
4) EXCEPT

SCENARIO #2
COUNTRY

CountryID CountryName Continent CityID


CY111 Serbia Europe NULL
CY112 United States Of America North America CT1
CY113 Poland Europe NULL
CY114 Bulgaria Europe NULL
CY115 Canada North America CT2

319
SIMPLE SQL

NewCOUNTRIES

CountryID CountryName Continent CityID


CY114 Kosovo Europe CT3
CY115 Palau Oceania CT1
CY116 East Timor Asia NULL

1. After Creating the above tables in your database and inserting the records, implement the
below mentioned operations on the datasets:
1) UNION
2) UNION ALL
3) INTERSECT
4) EXCEPT

320
CHAPTER 11 - SETS IN SQL

ANSWERS
SCENARIO #1:
UNION:
SELECT AuthorID,AuthorName,Email,Country,BookID FROM NewAuthor
UNION
SELECT AuthorID,AuthorName,Email,Country,BookID FROM Author;

UNION ALL:
SELECT AuthorID,AuthorName,Email,Country,BookID FROM NewAuthor
UNION ALL
SELECT AuthorID,AuthorName,Email,Country,BookID FROM Author;

INTERSECT:
SELECT AuthorID,AuthorName,Email,Country,BookID FROM NewAuthor
INTERSECT
SELECT AuthorID,AuthorName,Email,Country,BookID FROM Author;

EXCEPT:
SELECT AuthorID,AuthorName,Email,Country,BookID FROM NewAuthor
EXCEPT
SELECT AuthorID,AuthorName,Email,Country,BookID FROM Author

SCENARIO #2:
UNION:
SELECT CountryID,CountryName,Continent,CityID
FROM Country
UNION
SELECT CountryID,CountryName,Continent,CityID
FROM NewCOUNTRIES

UNION ALL:
SELECT CountryID,CountryName,Continent,CityID
FROM Country
UNION ALL
SELECT CountryID,CountryName,Continent,CityID
FROM NewCOUNTRIES

321
SIMPLE SQL

INTERSECT:
SELECT CountryID,CountryName,Continent,CityID
FROM Country
INTERSECT
SELECT CountryID,CountryName,Continent,CityID
FROM NewCOUNTRIES

EXCEPT:
SELECT CountryID,CountryName,Continent,CityID
FROM Country
EXCEPT
SELECT CountryID,CountryName,Continent,CityID
FROM NewCOUNTRIES

322
PART 3
ADVANCE LEVEL
STUFF
SQL
CHAPTER 12

VIEWS AND INDEXES IN SQL

W hen we code using any programming language, the ideal scenario is to create a code that
executes in the minimum amount of time efficiently. In this chapter, I will explain to you
about two ways by which we can increase the efficiency, security and reusability of SQL code—
These two ways are harnessing the power of Views and Indexes.

VIEWS
A View in SQL is a virtual table; Data in views is in the rows and columns format like normal
tables. But the data that is presented in the view comes either from a single underlying table or
combination of multiple tables data. The data that is presented in views comes from the underly-
ing tables. If the underlying tables are deleted or if the data is removed, the view will not display
any data.
In simple words, a view is a set of saved SQL statements.
The data presented in the view is dynamically loaded and produced from the underlying que-
ries whenever the view is referenced.
Once a view is created, it behaves like a simple SQL table. You can query a view as well as
use it to implement a JOIN with other tables.

WHY USE VIEWS?


There are numerous reasons for using views, and some of these reasons are mentioned below:

Increase Security With Views


The main benefit of a view is that it can act as a filter over the underlying tables because it
restricts the direct access of the end-user to the underlying tables. In addition, this increases the
security factor of the data because no user has direct permission to access the table data.

325
SIMPLE SQL

Increase Relevance and Reduce Complexity


In addition to this, we can also decide which data the user can see and on which data the user
is allowed to make changes.

Reusability
The best part is that, once you have created a view for a particular purpose, it can be reused
multiple times again . And you’ll not write complex SQL statements repeatedly to get the same
datasets.

Syntax to Create a VIEW:

CREATE VIEW ViewName AS


SELECT Column1, Column2.....Column(n)
FROM TableName
WHERE Condtion;

To display the data present in a view, we can query a view using a SELECT statement, just
like the way we query normal tables.

Syntax To Query A View:


SELECT Column1,Column2....Column(n) FROM ViewName;

Tables that I will be using to explain the creation of the Index will be:

a) Employee Table
b) Department Table

Let me explain this concept to you with an example:

Example:
Suppose you want to display all the information about employees in an application, where
the higher management can see the information of all employees ( to make some internal deci-
sions). But showing the salary of each employee salary would be pretty awkward.

Because the people in the higher management will also have their records in the Employee
table.

326
CHAPTER 12 - VIEWS AND INDEXES IN SQL

To make these requirements easy, creating views can help. So, to work on this, you can create
a view that extracts all the records from the Employee table, except the salary of the employees.
The name of the view should be EmpNoSal.

CREATE VIEW EmpNoSal AS


(
SELECT [EmployeeID]
,[EmployeeName]
,[DepartmentID]
,[Location]
,[Role]
,[DateOfBirth]
,[HireDate]
FROM [MyEcommerceDB].[dbo].[Employee]
);

Run the below statement to query the above view:

SELECT * FROM EmpNoSal;

Example:
Create a view Named EmployeeWithDepartment, that displays EmployeeID,
EmployeeName, HireDate, and Department Name for all the Employees present in the
Employee table.

Approach: So, as it’s pretty clear from the requirement, the final resultset can be achieved with
the help of a LEFT JOIN. So, first, we need to create a view, and inside that view, the result set
will be reflected with the help of the LEFT JOIN.

So, let me use the above create view syntax to create the view:

CREATE VIEW EmployeeWithDepartment AS


(
SELECT Emp.[EmployeeID],Emp.[EmployeeName],Dept.[DepartmentName]
FROM [MyEcommerceDB].[dbo].[Employee] Emp
LEFT JOIN [MyEcommerceDB].[dbo].[Department] Dept
ON Emp.DepartmentID = Dept.DeptID
);

327
SIMPLE SQL

Run the below statement to query the above view:

SELECT * FROM EmployeeWithDepartment ;

TYPES OF SQL VIEWS


Broadly there are two types of views in SQL. The first one is System defined views, and the
other one is user-defined views.
Let me explain the System defined views first. System-defined views are basically views that
already exist in the RDBMS. There are multiple System defined views present in an RDBMS that
have their own purpose. If I talk about the System defined views present SQL Server, There are
many System defined views that are dedicatedly created to provide internal information about
the database (SQL server) and the system properties.

Some of these System defined views are:

a) [INFORMATION_SCHEMA].[TABLES] (This view is used to get the list of procedures


present in a database.)
b) [INFORMATION_SCHEMA].[CHECK_CONSTRAINTS] ( this view allows user to see
CHECK constraints present in your database )
c) [INFORMATION_SCHEMA].[TABLE_CONSTRAINTS] ( This allows User to get all the
constraints for each table present in the database )

d) [INFORMATION_SCHEMA].[TABLE_PRIVILEGES] (This view displays the list of table


privileges present)

And these are many more views than the above-mentioned views in the SQL server.

Apart from this, The other category of view is the User Defined views:

328
CHAPTER 12 - VIEWS AND INDEXES IN SQL

USER-DEFINED VIEWS
A user-defined view is a type of view that is created and defined by a user. SQL allows a user
to create views based on their requirements, and then these views can be used just like a simple
table.
There are two main types of user-defined views:

a) SIMPLE VIEWS or Updatable Views


b) COMPLEX VIEWS

Let me explain simple views first...


Simple views are the views in which we are working with a single table.
We can do DML operations in simple views, which means operations like INSERT, UPDATE,
and DELETE can be done with a simple view.

Some of the examples for simple views are:

SELECT operation in a simple view:


Create a view that selects only the EmployeeID, EmployeeName, and DepartmentID
from the Employee table.

CREATE VIEW viewEmpDeptID


AS
(
SELECT [EmployeeID],[EmployeeName],[DepartmentID]
FROM [MyEcommerceDB].[dbo].[Employee]
);

INSERT operation in Simple View:

inserts a record into the simple view.

INSERT INTO viewEmpDeptID ([EmployeeID],[EmployeeName],[DepartmentID])


VALUES (‘131’,’Test’,’D3’);

329
SIMPLE SQL

Now, you’ll see the results after inserting this new record in the simple view. You’ll see that
the view has a new record.
Also, after inserting the record in the view, even the record has been inserted into the under-
lying table as well.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee];

After executing the above query to check the results, we can see that the underlying table has
a new record with the values ( 131, Test, D3).

UPDATE operation in Simple Views:


In simple views, we can also implement update operations as UPDATE is also a DML opera-
tion. Let’s try to update the EmployeeName present in the view viewEmpDeptID with a new
value, ‘Harry’.

UPDATE viewEmpDeptID SET EmployeeName=’Harry’


WHERE EmployeeID=’131’;

execute the below query to check the results in the view.


SELECT * FROM [MyEcommerceDB].[dbo].[viewEmpDeptID];

Now, execute the below query to check the results in the main .
SELECT * FROM [MyEcommerceDB].[dbo].[Employee];

DELETE operation in simple Views:

Now, let me try to do a DELETE operation in a simple view.

DELETE FROM viewEmpDeptID


WHERE EmployeeID=’131’;

330
CHAPTER 12 - VIEWS AND INDEXES IN SQL

Execute the below query to check the results in the view.

SELECT * FROM [MyEcommerceDB].[dbo].[viewEmpDeptID];

Now, execute the below query to check the results in the main .

SELECT * FROM [MyEcommerceDB].[dbo].[Employee];

Simple views are quite easy to create and a good choice when you want to do DML operations
on your views and eventually in the underlying tables. However, things get a bit different when
we are working with complex views.

Complex Views are the views in which there are multiple underlying tables. The dataset coming
from these tables is combined using JOINS, and we can also implement GROUP BY, ORDER
BY, and other group functions, which makes it difficult to do DML operations on these views
directly.

Let me explain it with an example:

Example: Creating a Complex View


Create a view that displays the Employee Name, Job Role, Salary, and Department Name of
Employees who have a salary greater than 100000.

Approach: In order to create this view, that displays specific columns on the given condition
from multiple tables ( Employee and Department ). We first need to create a SELECT query
that will display the desired results.

SELECT EmployeeName,Role,Salary,DepartmentName
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
INNER JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT
ON DEPT.DeptID=EMP.DepartmentID
WHERE Salary>=’100000’;

331
SIMPLE SQL

Now, simply we will create a view that will include this query in its body.

CREATE VIEW viewEmpOver100k


AS
(
SELECT EmployeeName,Role,Salary,DepartmentName
FROM [MyEcommerceDB].[dbo].[Employee] AS EMP
INNER JOIN [MyEcommerceDB].[dbo].[Department] AS DEPT
ON DEPT.DeptID=EMP.DepartmentID
WHERE Salary>=’100000’
);

Execute the below query to check the results in the view.

SELECT * FROM [MyEcommerceDB].[dbo].[viewEmpOver100k];

Always remember, whenever you want to hide the underlying tables or want to display only
a part of a dataset. Then, views is always an ideal choice.

INDEXES
What is an Index in SQL?
Indexes in SQL are used for faster retrieval of data, improving query performance, and sort-
ing of records quickly. Indexes in SQL are pretty similar to the index of a book.
Suppose you want to look up a particular chapter or topic in a book. There are two ways to
do it, first go to each chapter and each topic one by one and figure out if that is what you want
to search.
The second way to do it is by simply going to the index of the book and quickly figuring out
the page number of the topic you were searching for. The second way to search the topic, which
is a much faster way to get your desired results. SQL indexes also work like that.
Suppose you want to display the Name and salary of employees who have a salary between
80,000 and 100,000.
In order to extract the records that fall under this category, we can either scan the whole table
records, compare each record with our condition and then display the records that match with
the condition.
Or, we can apply an index on the salary column. This will help the database engine to reduce
the area to scan for the matching records.

332
CHAPTER 12 - VIEWS AND INDEXES IN SQL

Syntax To Create INDEX:


CREATE INDEX IndexName ON TableName;

Syntax To Create INDEX on a single column:


CREATE INDEX IndexName ON TableName(ColumnName);

Example:
Let’s try to implement the indexes on the example that I discussed for the Employee table.
For that we need to create an index on the salary column of the Employee table with CREATE
INDEX statement.

CREATE INDEX IndexSalary


ON [MyEcommerceDB].[dbo].[Employee] (Salary DESC);

The way I implemented an index in a single column, similarly index can be applied on multi-
ple columns. When we apply indexes on multiple columns, then it is considered as multi-column
indexes or composite indexes in SQL.

Syntax To Create Multi-column index:


CREATE INDEX IndexName ON TableName(ColumnName1, ColumnName2, ColumnName3….
ColumnName(n));

The rows in the table after implementing the multi-column index will be ordered by the 1st col-
umn, then the 2nd column, and so on...

Let me explain it with an example..

Example:
Apply multi-column index on the table Employee on salary column and employee name column.

CREATE INDEX IndexSalaryEmployeeName


ON [MyEcommerceDB].[dbo].[Employee] (Salary DESC,EmployeeName ASC);

333
SIMPLE SQL

Syntax To Drop INDEX:


DROP INDEX IndexName;

Although indexes are quite useful in increasing the performance of a SQL query and help the
data analysts, Database administrators, and even the applications to extract the desired results
fast.
However, when it comes to INSERT and UPDATE data in a table, Indexes can actually slow
down the performance. The reason for that is that, When we create indexes on a table, a space
in the database is assigned for indexes. And when we update or insert any new row in the table,
the indexes for that data also need to be maintained.

334
CHAPTER 12 - VIEWS AND INDEXES IN SQL

EXERCISE
1 ) Create a view Named vw_EmpDeptRt, that displays EmployeeID, EmployeeName,
HireDate, and DepartmentName from Department table. Make sure that all
Department Names must be displayed in the final outcome.

HINT: Employee Table and Department must be in joined using a RIGHT join

2) Create Index on the Department table on the department name column ( ascending )

335
SIMPLE SQL

ANSWERS
1)
CREATE VIEW vw_EmpDeptRt
AS
(
SELECT E.EmployeeID,E.EmployeeName,E.HireDate,D.DepartmentName
FROM Employee E
RIGHT JOIN Department D
ON E.DepartmentID=D.DeptID
)

2)
CREATE INDEX IX_Department
ON [MyEcommerceDB].[dbo].Department (DepartmentName ASC);

336
SQL
CHAPTER 13

STORED PROCEDURES,
CURSOR AND TRIGGERS

C oding is all about creating algorithms that help in solving a problem or carrying out some
operations. As you know, SQL statements help in inserting, managing, and deleting data
from databases efficiently.
In a big database where there are multiple operations transactions going on, there are some
tasks that we need to carry out over and over again. Instead of doing each task over and over
again each time it needs to be done, we can set up some processes and create leverage using those
processes.
SQL provides many functionalities and ways we reuse and reutilize certain set of code that it
creates leverage and get things done quickly with less manual intervention. In this chapter, I will
teach you different ways in SQL, that can help you out in creating leverage using your SQL code.

UNDERSTANDING STORED PROCEDURES


A stored procedure is stored SQL statements based on the desired process of execution that
can be used over and over again.
We can call a particular stored procedure, and it will execute and do the task smoothly. The
best part about stored procedures is that we can also pass some parameters, and based on the
value passed in parameters, the stored procedure will execute.
On the surface level, It seems like the Stored procedure works similar to a SQL function. But
they’re quite different. We can do DML operations along with SELECT in a Stored procedure,
whereas with SQL functions, we can only do SELECT.
With stored procedures, the security of the database increases as the users will not have direct
access to the underlying tables present in the stored procedure.
In addition to this, stored procedures are stored in the database in a compiled state. Hence,
it reduces the compilation time whenever it is executed. This basically improves the overall per-
formance of the execution.

337
SIMPLE SQL

Syntax to Create Stored Procedure without parameters:

CREATE PROCEDURE ProcedureName


AS
SQL_Statements
GO;

Execute Stored Procedure:


EXEC ProcedureName;

Example:
Create a stored procedure that displays the Employee ID, Employee Name, and Salary of the
TOP 3 employees from the Employee Table.

CREATE PROCEDURE Top3Emp


AS
SELECT TOP 3 [EmployeeID],[EmployeeName], [Salary]
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE Salary>=’85000’
GO

In order to execute the above-stored procedure and get the top 3 employees that have salaries
higher than 85000. We just need to execute the stored procedure using the below command.

EXEC Top3Emp;

Syntax to Create Stored Procedure with parameters:


CREATE PROCEDURE ProcedureName @Parameter DataType(size)
AS
SQL_Statements
GO

Creating a stored procedure with parameters requires declaring the Parameter and its
datatype.
Parameterized stored procedures allow passing this value to the SQL statements in the body
of stored procedures. Then this value can be used in the SQL statements to get the desired result
we want.

338
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

Example:
Create a parameterized stored procedure that allows changing the job role of employees
where the existing role is of a developer, hiring date is greater than or equal to 2009-01-01, and
the salary is equal to 80,000.

CREATE PROCEDURE ChangeRole @ParRole nvarchar(50)


AS
UPDATE [MyEcommerceDB].[dbo].[Employee]
SET Role=@ParRole
WHERE Role=’Developer’
AND HireDate <=’2009-01-01’
AND Salary>=’80000’;
GO

To execute the above created stored procedure, we can simply execute it using the below
command.

EXEC ChangeRole ‘Programmer’;

Such parameterized stored procedures allow programmability, reusability, and flexibility in the
database.

Syntax To Create Stored Procedure With An Output Parameter

CREATE PROCEDURE ProcedureName @InputParameter DataType , @OutputParameter


DataType(size) OUTPUT
AS
SQLStatements;
GO

In order to create a procedure with an output parameter, we need to declare the output
parameter (@OutputParameter). This output parameter can then be used to capture the final
output of the SQL statements that will be executed inside the body of the stored procedure.
Now in order to execute such stored procedures, we need to use the below syntax:

339
SIMPLE SQL

Syntax To Execute Stored Procedure With Output Parameter

DECLARE @OutputParameter DataType(size)


EXEC ProcedureName ParameterValue, @OutputParameter OUTPUT;
PRINT @OutputParameter;

In the above syntax to execute the stored procedure with output parameters:

a) First, we need to declare a variable that will hold the value returned by the stored
procedure.
b) Then the procedure will be executed by supplying an input parameter value that will
return a value that will be captured in the output parameter.
c) Then in the third line, we print the output parameter value.

Example: Create a stored procedure that displays the name of the top employee as output who
have hiredate less than the date 2009-01-01 and salary greater that a particular variable value.
The value of salary variable must be an input for the stored procedure.

CREATE PROCEDURE SelectEmp @ParSalary int ,@EmpName varchar(255) OUTPUT


AS
SELECT TOP 1 @EmpName= EmployeeName FROM [MyEcommerceDB].[dbo].[Employee]
WHERE HireDate <=’2009-01-01’
AND Salary>=@ParSalary;
GO

Now, in order to execute the above-stored procedure. We can simply use the syntax to call
the stored procedure.

DECLARE @OutputEmp varchar(255)


EXEC SelectEmp 80000, @OutputEmp OUTPUT;
PRINT @OutputEmp;

340
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

In the above commands, we declare a parameter to store the output coming from the stored
procedure. Then EXEC command will execute the stored procedure SelectEmp along with a
value 80000. The value of 80000 will then be supplied into the stored procedure after the exe-
cution of the SQL statements ( SQL select query in this case).
A final result will be supplied to the output variable from the stored procedure to the variable
@OutputEmp.
Then the last line will simply print the value present in the output variable @OutputEmp.
There are many more things we can do with stored procedures because of the flexibility and
the reusability factor it provides.

TRIGGERS
In SQL, a Trigger is a type of stored procedure that gets executed automatically whenever
there is an ‘event’ executed in the database.
The database “event” can be anything from the execution of DML or DDL statements to a
logon event.
Whenever there is an “event” like this in the database, we can set up our trigger in a way
that it will execute automatically and will perform the desired action. The best part is that you
can create a trigger in a way that it can execute after an event happens and even can make some
executions “instead of” the actual database event that was being executed in the first place.
These actions can be anything like INSERT or UPDATE statements that are triggered by the
SQL trigger.
Unlike stored procedures, triggers only get executed once there is an event in the database
for which the trigger is created and can’t be called directly. Whereas, in order to execute a stored
procedure, we need to call it explicitly.

a) No Manual execution
b) No parameters
c) Event-driven
d) Ensures data integrity (logo style)

341
SIMPLE SQL

TYPES OF TRIGGERS
As I am teaching you most of the things in SQL Server. I will share with you the different types
of triggers present in the SQL server. But the concept of triggers is the same in other RDBMS too.
In this book, I will be discussing two main types of triggers:

DDL Triggers
DML Triggers ( BEFORE and INSTEAD OF triggers)

Let me explain each trigger, one by one...

DDL TRIGGERS
Data Definition Language triggers, also known as DDL triggers, respond to DDL statements
like CREATE, DROP or ALTER, etc.
Whenever any of the DDL statements execute on the database object on which we have cre-
ated, the trigger is created. The trigger will automatically fire and take the action we have set.

Syntax:
CREATE TRIGGER TriggerName
ON DATABASE
FOR [DDLEventName1, DDLEventName2, DDLEventName3... DDLEventName(n)]
AS
BEGIN
{SQL_Statement or Print_Message}
END

Where DDLEventName1, DDLEventName2 etc. represent the DDL Events.

DDL events are events that are raised whenever a DDL command is executed on database
objects ( Table, Stored Procedure, functions, etc.) For example, if I drop a table from a database,
an event will be raised!

342
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

The name for the drop table event is DROP_TABLE. Similarly, there are multiple DDL
events on different database objects. Like if you create a stored procedure, the event CREATE_
PROCEDURE will be raised.

We are basically creating triggers for these raised events.

Some of the other database events are:

For Tables: CREATE_TABLE,ALTER_TABLE,DROP_TABLE


For Functions: CREATE_FUNCTION,ALTER_FUNCTION,DROP_FUNCTION

To check the full list of DDL events for other database objects for SQL server,
VISIT: https://docs.microsoft.com/en-us/sql/relational-databases/triggers/ddl-events?view=sql-
server-ver15

Example of DDL triggers


USE MyEcommerceDB
GO
CREATE TRIGGER TableSecurity
ON DATABASE
FOR DROP_TABLE
AS
BEGIN
PRINT ‘Dropping tables not allowed for this database’
ROLLBACK;
END

And if I execute the below command:

DROP TABLE [MyEcommerceDB].[Actions];

It will give an output mentioning that the dropping of tables is not allowed for this database (See
Figure 13.1 for reference)

343
SIMPLE SQL

Figure 13.1

As you can see in the results above when I tried dropping a table from the database on which
I created the trigger. I could not drop the table as the trigger fires the moment I execute the
DROP TABLE command. Internally, it invoked the DROP_TABLE event.

DROP TABLE (command) à DROP_TABLE (event) à TRIGGER

Similarly, we can create triggers on many DDL commands, and the trigger will simply exe-
cute and do the actions which we want it to perform...
Isn’t it amazing?
We can create a trigger that can also get fired up on DML commands. These are called DML
triggers.

DML TRIGGERS
Data Manipulation Language triggers, popularly known as DML triggers, basically respond
to DML statements like INSERT, UPDATE, and DELETE.
Unlike DDL triggers, we create DML Triggers on tables because of the manipulation of data
happens in tables, right?

Now, DML triggers can be classified into two types:

344
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

AFTER TRIGGERS (DML)


After Triggers are the type of DML triggers that trigger after the DML command has been
executed; when these DML statements like UPDATE, INSERT, DELETE get executed, it then fires
the AFTER TRIGGER.

Syntax of AFTER DML trigger:


CREATE TRIGGER TriggerName
ON TableName
FOR
INSERT,UPDATE,DELETE
AS
BEGIN
SQL_Statements;
END

Example:
CREATE TRIGGER CustomerDataSecurity
ON Customers
FOR
DELETE
AS
BEGIN
PRINT ‘DELETION OF Record is not allowed for Customer table’;
ROLLBACK;
END

If I try to delete the above record, with below DELETE SQL statement.

DELETE FROM [Customers] WHERE CustomerId=’112’;

The result of the DELETE statement will be:

Figure 13.2

345
SIMPLE SQL

INSTEAD OF TRIGGERS (DML)


When we talk about INSTEAD OF triggers, The DB engine basically executes the SQL state-
ments present in the body of the trigger before the execution of the DML event.
Let me explain,
Suppose I implement an instead of trigger on a table for any of the DML statements (INSERT,
UPDATE, DELETE). The DB engine will execute the SQL statement present in the triggers
INSTEAD OF the DML statement I wanted to execute.

Illustration:
DML Event à Instead of trigger à SQL statements/action in body of trigger.
--Xà(DML statement action)

Syntax of INSTEAD OF DML triggers:


CREATE TRIGGER TriggerName
ON TableName
INSTEAD OF INSERT,DELETE,UPDATE
AS
BEGIN
SQL_Statement;
END

Now, let’s try to understand the concept with the help of a practical example.

Example:
Create a trigger on the Employee table on the DELETE statement. The triggers should print
a message instead of deleting the data present in the table.

346
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

The text message that the trigger must display is:

‘We are displaying this message INSTEAD OF Deletion!’

CREATE TRIGGER InteadOfTrigger


ON Employee
INSTEAD OF DELETE
AS
BEGIN
SELECT ‘We are displaying this message INSTEAD OF Deletion!’
AS Result;
END

When I try to execute the DELETE statement to delete the record from the Employee Table
with the below SQL Statement.

DELETE
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE EmployeeID=’130’

The result of the above DELETE SQL statement are displayed in Figure 13.3:

Figure 13.3

And when I execute the SELECT query, I can see that the record is not deleted from the table.
You can see the results in figure 13.4.

Figure 13.4

347
SIMPLE SQL

ALTER AND DISABLE TRIGGERS

After the creation of triggers, there might be a possibility that you want to alter a trigger
because of some additional execution you want it to make.

ALTER TRIGGER SYNTAX:

ALTER TRIGGER TriggerName


ON TableName
FOR
INSERT,UPDATE,DELETE
BEGIN
SQLStatements;
Additional changes or updates;
END

Basically, to alter a trigger, we need to replace CREATE with ALTER in the main create trigger
command to alter it. Just add or replace the changes in the SQL statements to implement the
changes.

DROPPING TRIGGER SYNTAX:


To drop an existing trigger, you can use the below syntax:

DROP TRIGGER TriggerName;

Triggers provide an awesome level of leverage, and we don’t require to manually execute a
trigger, and it gets executed automatically whenever there’s a database event.
We can utilize a trigger in many ways. One of them is quite obvious – increasing the integrity
of our data in the database.

348
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

CURSORS
In RDBMS, most of the operations are carried out on the set of records, whether it is com-
bining multiple data sets together or it is updating data records based on a particular condition.
Most operations are done on a set of data, But sometimes we might need to do operations one
row at a time.
In SQL, we can even perform these row-by-row operations with the help of cursors.

What is Cursor in SQL?


A cursor is a temporary database object that allows extracting data from the dataset one
record at a time. The cursor then will loop through each record one by one on the dataset that
is present in the cursor.
Basically, it acts as a pointer that points to one record at a particular time.

The Syntax and workflow of SQL cursor:

There is a process to use cursors in order to do the row-by-row processing, and below is the
step-by-step workflow to work with cursors.

STEP 1: Declare a cursor


The first step of the workflow of the SQL cursors is to Declare the name of the cursor. In this
part, we also need to include the SQL statement that will return the dataset on which we will be
going to do the operations one row at a time.

Syntax:
DECLARE CursorName CURSOR FOR SELECT * FROM TableName;

The SELECT * FROM TableName is the SQL statement that will extract the dataset.

349
SIMPLE SQL

STEP 2: Open Cursor


Once a cursor is declared, then it is opened to store the extracted data from the SQL Statements.

Syntax:
OPEN CursorName;

STEP 3: Fetching Records


After a cursor is opened, then we fetch records from the cursor one row at a time. After a row
is fetched, then we can do DML operations on the fetched cursor.
There are six ways to fetch records from the dataset present in the cursor block.

FIRST: first helps to fetch the 1st row from the dataset of the cursor block.

Syntax:
FETCH FIRST FROM CursorName

LAST: Last helps to fetch the last row from the dataset of the cursor block.

Syntax:
FETCH LAST FROM CursorName

NEXT: Next is used to fetch the next row present in the data cursor block. The direction of the
next movement is in the forward direction.

Syntax:
FETCH NEXT FROM CursorName

PRIOR: Prior is used to fetch the row present in the back direction.

Syntax:
FETCH PRIOR FROM CursorName

350
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

ABSOLUTE: Moves the cursor to a specific nth record present in the cursor block.

Syntax:
FETCH ABSOLUTE (n) FROM CursorName
Where n can be any number.

RELATIVE: can be used to move the cursor either way -- Forward or backward from the current
position. In order to move forward, use the positive number; to move backward, use a negative
number.

Syntax:
FETCH RELATIVE (n) FROM CursorName
Where n can be any integer with negative or positive value. For eg: -3,-4, 4,7

STEP 4: Closing the cursor Syntax:


CLOSE CursorName

STEP 5: Deallocate the cursor


The last and final step is to deallocate the cursor and release the underlying resources that
were involved in making all this happen. Just closing the cursor is not enough; we need to deal-
locate the cursor.

Syntax:
DEALLOCATE CursorName

Example of a simple cursor


Create a simple cursor that just fetches the next row it encounters in the dataset of the
employee table.

Approach:
By using the above syntax, we can create a cursor that will extract the data from the employee
table and load it into the cursor block.
Then I will write a code to open the block, and inside that block, there will be a code state-
ment to fetch the next record.

351
SIMPLE SQL

After that, simply close the cursor and deallocate the memory.

DECLARE CursorEmployee CURSOR FOR SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


OPEN CursorEmployee
FETCH NEXT FROM CursorEmployee
CLOSE CursorEmployee
DEALLOCATE CursorEmployee

Example of a cursor with loop


Create a cursor that fetches EmployeeID and Employee name from the employee table.

Approach: As per syntax , the above cursor can be created. But in order to print each and
every record, I implement a WHILE loop and some variables to store the EmployeeID and
EmployeeName.

DECLARE CursorEmployee CURSOR FOR SELECT EmployeeID,EmployeeName


FROM [MyEcommerceDB].[dbo].[Employee]

OPEN CursorEmployee

DECLARE @emp_id int, @emp_name varchar(50);


FETCH NEXT FROM CursorEmployee INTO @Empid,@EmpName

PRINT ‘Employee_ID Employee_Name’

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ‘ ‘ + CAST(@Empid as varchar(10)) +’
‘+
CAST(@EmpName as varchar(20))

FETCH NEXT FROM CursorEmployee


INTO @Empid,@EmpName
END
CLOSE CursorEmployee
DEALLOCATE CursorEmployee

352
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

Results:
Employee_ID Employee_Name
111 Joey
112 Samantha
113 Ross
114 Barbara
115 Gunther
116 Monika
117 Shane
118 Yvonne
119 Douglas
120 Janeth
121 Richard
122 Lionel
123 Brenda
124 Alejandro
125 Fred
126 Kevin
127 Shammi
128 Rajesh
129 Lorraine
130 Paula

Where @@FETCH_STATUS is a function that returns a value coming from the last fetch
statement.
The possible values for @@FETCH_STATUS are displayed in figure 13.5

Figure 13.5

353
SIMPLE SQL

As you can see, the cursor creates a temporary database object, where we can do the row-by-
row operation. When we use cursors, we don’t need to allocate a huge chunk of memory space
for it.
So, This was the last section of this book about SQL. You have come a long way, my friend! If
you read all the concepts and practiced all the questions mentioned in this book, I can assure you
that you’re now an Advanced SQL developer. You’re no longer a beginner; when you learned
about creating joins and practiced a few joins, you started to evolve after that point. Just by
reaching this point, you have earned my respect!
Learning all the concepts present in this book one time would have definitely boosted your
confidence in your abilities. However, I am sure there is a huge positive difference between you
from the day you started this book and today! I expect that you will take this positivity and
confidence and start practicing more and more.
Mastering SQL requires years of practice, and, I hope you’ll not stop practicing code. But, the
actual value of this book is when you take this knowledge and keep on working hard on your
SQL skills.
I believe that there are three levels of mastering anything in life:

KNOWING: This is the 1st level of mastery. When you acquire the knowledge, this level is great,
but most people are stuck at this level and think that just acquiring more and more knowledge
will be helpful.

DOING: This is the 2nd level of mastery when you start implementing and practicing what
you’ve learned. At this level, you gain a different understanding of what you’ve learned, and
things and concepts begin to make more profound sense and meaning.

LIVING: This is the ultimate level. This level comes when you practice repeatedly and keep on
DOING and practicing what you’ve learned. At this level, whatever you’ve learned becomes a
part of you.

Suppose you think this book has helped you anyway. Then make sure you REVIEW it and
SHARE it with people who might need this.

354
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

EXERCISE
1) Create a Stored procedure (sp_EmpDept) that displays the Employee name, Salary and
Department name of employees. Make sure that details of employees present in employee
table must be displayed in the final outcome.
HINT: LEFT JOIN between Employee and Department table

2) Create a stored procedure that displays the name of the top employee as output who has
a hire date greater than the date 2009-01-01 and salary greater than a particular variable
value. The value of the salary variable must be an input for the stored procedure.

3) Create a trigger (DeleteDeptTrigger) on the Department table on the DELETE statement.


The triggers should print a message instead of deleting the data present in the table.

“Deletion Of Department Table Is Prohibited” !

4) Write a command to drop the trigger DeleteDeptTrigger.

355
SIMPLE SQL

ANSWERS
1)
CREATE PROCEDURE sp_EmpDept
AS

SELECT EMP.EmployeeName,EMP.Salary,DEPT.DepartmentName
FROM [MyEcommerceDB].[dbo].[Employee] EMP
LEFT JOIN
[MyEcommerceDB].[dbo].[Department] DEPT
ON EMP.DepartmentID=DEPT.DeptID

To execute the stored procedure sp_EmpDept below command:


EXEC sp_EmpDept;

2)
CREATE PROCEDURE sp_selectTopEmp @ParSalary int ,@EmpName varchar(255) OUTPUT
AS
SELECT TOP 1 @EmpName= EmployeeName FROM [MyEcommerceDB].[dbo].[Employee]
WHERE HireDate >=’2009-01-01’
AND Salary>=@ParSalary;

GO

To execute the stored procedure sp_selectTopEmp below command:

DECLARE @OutputEmp varchar(255)


EXEC sp_selectTopEmp 120000, @OutputEmp OUTPUT;
PRINT @OutputEmp;

3)
CREATE TRIGGER DeleteDeptTrigger
ON Department
INSTEAD OF DELETE
AS
BEGIN
SELECT ‘Deletion Of Department Table Is Prohibited!’
AS Result;
END

356
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

4)
DROP TRIGGER DeleteDeptTrigger;

5)
DECLARE CursorDepartment CURSOR FOR SELECT DeptID,DepartmentName FROM
[MyEcommerceDB].[dbo].[Department]

OPEN CursorDepartment

DECLARE @dept_id varchar(25), @dept_name varchar(50);


FETCH NEXT FROM CursorDepartment INTO @dept_id,@dept_name

PRINT ‘Employee_ID Employee_Name’

WHILE @@FETCH_STATUS = 0
BEGIN
PRINT ‘ ‘ + CAST(@dept_id as varchar(25)) +’ ‘+
CAST(@dept_name as varchar(20))

FETCH NEXT FROM CursorDepartment


INTO @dept_id,@dept_name
END
CLOSE CursorDepartment

357
SQL
RESOURCES and REFERENCES

Wikipedia Contributors. (2022, January 22). Codd’s 12 rules. Wikipedia; Wikimedia


Foundation. https://en.wikipedia.org/wiki/Codd%27s_12_rules#:~:text=5%20Further%20
reading-

Codd, E. F. (2002). A Relational Model of Data for Large Shared Data Banks. In Software
Pioneers (pp. 263–294). https://doi.org/10.1007/978-3-642-59412-0_16

tdoshin. (n.d.). Download and install Azure Data Studio - Azure Data Studio. Docs.microsoft.
com. Retrieved April 21, 2022, from https://docs.microsoft.com/en-us/sql/azure-data-studio/
download-azure-data-studio?view=sql-server-ver15

How do I fix the error “Named Pipes Provider, error 40 - Could not open a connection to”
SQL Server’? (n.d.). Stack Overflow. Retrieved April 21, 2022, from https://stackoverflow.
com/questions/9945409/how-do-i-fix-the-error-named-pipes-provider-error-40-could-not-
open-a-connec

How to install SQL Server on Mac. (n.d.). Setapp. Retrieved April 21, 2022, from
https://setapp.com/how-to/install-sql-server

LitKnd. (n.d.). Reserved Keywords (Transact-SQL) - SQL Server. Docs.microsoft.com.


Retrieved April 21, 2022, from https://docs.microsoft.com/en-us/sql/t-sql/language-elements/
reserved-keywords-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15

stevestein. (2017, March 14). Views - SQL Server. Microsoft.com. https://docs.microsoft.com/


en-us/sql/relational-databases/views/views?view=sql-server-ver15

Drkusic, E. (2020, February 21). Learn SQL: Set Theory. SQL Shack - Articles about Database
Auditing, Server Performance, Data Recovery, and More. https://www.sqlshack.com/learn-
sql-set-theory/

SQL server DateTime vs Datetime2. (2021, July 7). SQL Server Guides. https://sqlserverguides.
com/sql-server-datetime-vs-datetime2/

DateTimeOffset in SQL server. (2021, January 26). TekTutorialsHub.


https://www.tektutorialshub.com/sql-server/datetimeoffset-in-sql-server/

359

You might also like