80% found this document useful (5 votes)
2K views

SIMPLE SQL Begginers Guide To Master SQL and Boost Career

Uploaded by

shazil shaik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
80% found this document useful (5 votes)
2K views

SIMPLE SQL Begginers Guide To Master SQL and Boost Career

Uploaded by

shazil shaik
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 425

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 without 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 program-
ming language.

For more information, address: [email protected].

Copyright © 2022 by dataceps.com

www.dataceps.com
SQL

Table of Contents

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

PART 1: THE FUNDAMENTALS......................................................................................... 7

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


THE EVOLUTION OF DATABASES................................................................ 12
DIFFERENT TYPES OF DATABASES............................................................... 14
UNDERSTANDING DATABASE MANAGEMENT SYSTEMS......................... 20
DIVING INTO THE CONCEPT OF DATA MODELLING.............................. 23
ONE TO ONE............................................................................................. 25
ONE TO MANY AND MANY TO ONE.................................................... 26
MANY-TO-MANY...................................................................................... 27
SELF-REFERENCING RELATIONSHIPS................................................... 28
ENTITY-RELATIONSHIP MODEL.................................................................. 29
ENTITY....................................................................................................... 29
ATTRIBUTES............................................................................................... 29
RELATIONSHIP.......................................................................................... 30
ONE............................................................................................................. 30
MANY......................................................................................................... 30
1 AND ONLY 1........................................................................................... 30
1 OR MANY............................................................................................... 31

v
SIMPLE SQL

ZERO OR ONE........................................................................................... 31
0 OR MANY............................................................................................... 31
REPRESENTING CARDINALITY BETWEEN ENTITIES USING
RELATIONSHIP NOTATIONS......................................................................... 32
SCENARIO: A SIMPLE ECOMMERCE SALES ER MODEL........................... 33
STEP 1: IDENTIFYING THE ENTITIES..................................................... 33
STEP 2: IDENTIYING THE RELATIONSHIPS........................................... 34
STEP 3: CREATING THE ER DIAGRAM................................................... 34

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


THE RELATIONAL MODEL........................................................................... 37
SOME KEY TERMS OF RELATIONAL MODEL....................................... 38
KEYS IN A TABLE....................................................................................... 43
CHARACTERISTICS OF A RELATIONAL TABLES........................................ 46
RELATING MULTIPLE TABLES ..................................................................... 48
DEPENDENCIES IN A TABLES.................................................................. 50
NORMALIZATION.................................................................................... 51
CODD’S RULES OF RELATIONAL MODEL.................................................. 54
RELATIONAL DATABASE MANAGEMENT SYSTEM (RDBMS)................... 58
SQL AND ITS IMPACT.................................................................................... 60
ADVANTAGES OF SQL.................................................................................... 60
HISTORY AND BIRTH OF SQL...................................................................... 61

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


UNDERSTANDING DATATYPES.................................................................... 67
NUMERIC DATA TYPES............................................................................ 70
APPROXIMATE DATA TYPE...................................................................... 74

vi
Table of Contents

STRING DATATYPES....................................................................................... 76
BINARY DATA TYPES...................................................................................... 78
DATE TIME DATATYPES IN SQL.................................................................... 80
METADATA: DATA ABOUT DATA.................................................................. 83

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

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


SQL SERVER INSTALLATION FOR WINDOWS............................................ 90
SQL SERVER INSTALLATION IN MAC OS.................................................. 113
PART 1: INSTALLING DOCKER.............................................................. 114
PART 2: DOWNLOAD AND INSTALL SQL SERVER ON MAC............. 122
PART 3: AZURE DATA STUDIO INSTALLATION................................... 127

CHAPTER 5: MASTERING SQL QUERIES ....................................................... 133


SQL QUERIES, STATEMENTS, and CLAUSES............................................... 133
NUT AND BOLTS OF SQL STATEMENTS.............................................. 134
PRACTICING SQL COMMANDS............................................................ 143

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


DESIGNING AND CREATING TABLES ....................................................... 167
STEP 1: IDENTIFYING ENTITIES............................................................ 169
STEP 2: IDENTIFYING ATTRIBUTES...................................................... 169
STEP 3: IDENTIFYING THE KEYS ATTRIBUTES .................................. 169
STEP 4: IDENTIFYING THE CONSTRAINTS......................................... 170
STEP 5: CREATING TABLES USING SQL STATEMENTS....................... 194

vii
SIMPLE SQL

BEST PRACTICES FOR CREATING TABLES THAT EVERY


DEVELOPER WILL RESPECT YOU FOR...................................................... 195
CHOOSING THE RIGHT CASES AND STICKING TO IT:...................... 195
AVOID SPELLING MISTAKES:................................................................. 197
ADDING COMMENTS IN YOUR SQL STATEMENTS:.......................... 197
ADDING ALIASES:................................................................................... 199
INSERTING, UPDATING and DELETING THE DATA IN
THE TABLES............................................................................................. 200

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


THE SELECT CLAUSE................................................................................... 214
TOP........................................................................................................... 215
DISTINCT................................................................................................. 215
THE FROM CLAUSE...................................................................................... 216
THE WHERE CLAUSE................................................................................... 217
THE GROUP BY CLAUSE.............................................................................. 218
COUNT ().................................................................................................. 220
SUM ()....................................................................................................... 221
AVG ()........................................................................................................ 222
MIN () ....................................................................................................... 224
MAX ()...................................................................................................... 226
THE HAVING CLAUSE.................................................................................. 227
THE ORDER BY CLAUSE.............................................................................. 230
ADVANCED FILTERING (Operators in WHERE clause ).............................. 232
COMPARISON OPERATORS IN SQL...................................................... 233
LOGICAL OPERATORS IN SQL.............................................................. 236
EVALUATION AND PROCESSING OF SQL QUERY ................................... 243

viii
Table of Contents

CHAPTER 8: MASTERING SQL FUNCTIONS ................................................. 249


SYSTEM DEFINED FUNCTIONS.................................................................. 251
AGGREGATE FUNCTIONS........................................................................... 252
MAX ()...................................................................................................... 252
MIN ()........................................................................................................ 253
SUM()........................................................................................................ 253
AVG()......................................................................................................... 253
COUNT()................................................................................................... 254
STRING FUNCTIONS.................................................................................... 254
ASCII ........................................................................................................ 256
CHAR........................................................................................................ 256
LEN........................................................................................................... 257
CHARINDEX ........................................................................................... 257
PATINDEX ............................................................................................... 258
LEFT.......................................................................................................... 259
RIGHT ...................................................................................................... 260
LTRIM ...................................................................................................... 260
RTRIM ..................................................................................................... 261
REPLACE ................................................................................................. 261
REPLICATE............................................................................................... 262
REVERSE................................................................................................... 263
QUOTENAME.......................................................................................... 263
SPACE........................................................................................................ 264
STR............................................................................................................ 265
STUFF ....................................................................................................... 265

ix
SIMPLE SQL

SUBSTRING.............................................................................................. 266
LOWER..................................................................................................... 267
UPPER ...................................................................................................... 268
SOUNDEX................................................................................................. 268
DIFFERENCE............................................................................................ 269
CONCAT................................................................................................... 269
TRANSLATE ............................................................................................ 270
NCHAR..................................................................................................... 271
DATALENGTH......................................................................................... 271
CONCAT USING + ................................................................................... 272
DATE AND TIME FUNCTIONS..................................................................... 273
FUNCTIONS THAT RETURNS CURRENT DATE.................................. 274
FUNCTIONS THAT RETURN PART OF A DATE AND TIME:............... 275
SQL FUNCTIONS TO MODIFY DATE VALUES...................................... 279
WORKING WITH NUMERIC/MATH FUNCTIONS............................... 281
REFRESHING SOME PROGRAMMING FUNDAMENTALS....................... 292
USER DEFINED FUNCTIONS ...................................................................... 293
SCALAR FUNCTIONS.............................................................................. 293
INLINE TABLE-VALUED FUNCTIONS................................................... 296
LEVELING UP THE GAME WITH ADVANCED FUNCTIONS.................... 298
WINDOW Function in SQL....................................................................... 298
ROW_NUMBER()...................................................................................... 300
RANK()...................................................................................................... 303
DENSE_RANK()........................................................................................ 306
NTILE()..................................................................................................... 310
DEALING WITH NULL VALUES USING FUNCTIONS ......................... 313

x
Table of Contents

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


What is a SUBQUERY? .................................................................................. 322
EXPLORING POSSIBILITIES WITH SUBQUERIES....................................... 323
EXERCISE....................................................................................................... 328
ANSWERS....................................................................................................... 328

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


WHY DO WE NEED JOINS?......................................................................... 329
UNDESTANDING JOINS............................................................................... 330
THE CROSS JOIN..................................................................................... 333
INNER JOIN............................................................................................. 336
OUTER JOINS........................................................................................... 341
LEFT OUTER JOIN................................................................................... 341
RIGHT OUTER JOIN............................................................................... 347
FULL OUTER JOIN.................................................................................. 351

CHAPTER 11: SETS IN SQL............................................................................... 363


UNION........................................................................................................... 363
INTERSECT.................................................................................................... 367
EXCEPT ......................................................................................................... 368

xi
SIMPLE SQL

PART 3: ADVANCE LEVEL STUFF............................................................................... 375

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


VIEWS............................................................................................................. 377
WHY USE VIEWS?.................................................................................... 378
TYPES OF SQL VIEWS............................................................................. 381
USER-DEFINED VIEWS............................................................................ 382
INDEXES........................................................................................................ 385

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


UNDERSTANDING STORED PROCEDURES............................................... 391
TRIGGERS...................................................................................................... 396
TYPES OF TRIGGERS............................................................................... 397
CURSORS....................................................................................................... 404

RESOURCES and REFERENCES......................................................................... 415

xii
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 was quickly onboarded to 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 had hated SQL since my college days. Even in college, I used to delegate all my
SQL development work to my college project mates. As SQL coding was always tricky
for me;
I started to think that I must quit this job, and I even tried looking out 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 train-
ing. 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, and the quality of my
work was pathetic.
I was terrible at memorizing the syntax of different SQL statements; complex que-
ries that senior developers gave me were difficult to understand. Creating even simple
queries was a nightmare for me.
I had no idea or path to know where to even start from?
When I searched for study material online, it was either not explained thoroughly,
or I had to structure it myself in my mind.
But I persisted and decided that I would master this language. So I started practic-
ing SQL on my laptop for a couple of weeks, things began to change for me. I started
to understand complex queries and write some advanced-level queries. My confidence

1
SIMPLE SQL

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 a skill that 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. I have been appreciated for my work
so many times by my seniors, which eventually boosted my confidence in my abilities.
SQL is just like other skills that might seem difficult at the start, but once you keep
practicing it and solve problems in SQL, you'll eventually master it.
Even if you want to build your database or learn this skill to become a SQL free-
lancer, 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 data-
base, datatypes, 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 fin-
ishing the previous sections before jumping to this part to become an advanced
professional in SQL.

2
INTRODUCTION

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.
Learning SQL boosted my career and confidence, and I want you to experience the
same.
Are you ready to thrive?? Then keep reading….

3
PART 1
THE
FUNDAMENTALS
SQL

CHAPTER 1

MASTERING THE
FUNDAMENTALS & DATABASES

M astering the fundamentals is something that will help you in learning any new
skills in life. That's why I always spend a big chunk of my time mastering the
fundamentals first, and then I move to the advanced level stuff.
That's why this chapter is all about the essential fundamental concepts and knowl-
edge before learning about SQL programming.
I am sure you are ready and super-excited to learn and discover about the most
used data skill—SQL ! SQL is one of the foundational languages while working with
data, and it has made it so more manageable for us "developers" to extract meaning
and insights from data. Before learning 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 the single click of a button!
Isn't that amazing?

9
SIMPLE SQL

( Figure 1.1)

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 in 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)

10
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

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 that is dedicated to serving a website. The website data and
information are stored in this type of server.
Email server: The dedicated server handles and manages to send and receive emails
over networks.
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 infor-
mation in the database is stored in a way that anyone can quickly access that infor-
mation whenever it is required.

( Figure 1.3)

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


Databases are the backbone of the present digital age! Everyone needs a data-
base to store data for better decision-making, data management, and efficient data
storage!
Businesses, government agencies, small vendors, 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 database is stored so that anyone can access that Information
whenever required.

11
SIMPLE SQL

So 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 information. 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
computerized data storage and access methods.

THE EVOLUTION OF DATABASES


Before the Computer Age
Data used to be stored in files, folders,
card catalogs, etc. However, storing, manag-
ing, and retrieving the required data was slow
and required manual labor.

(Figure 1.4 a)

Early Computer Age


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

(Figure 1.4 b)

12
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

1960

Charles Bachman laid the foundation of computer data-


bases. Charles designed the first-ever computer database
known as an 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 rela-
tional 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 commu-
(Figure 1.4 d) nicate and manage relational databases.

2000

In the early 2000s, when the internet became a thing, the


data generated 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)

13
SIMPLE SQL

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
information.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:

14
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

Personal Database:

(Figure 1.5 a)

A database designed for a single person, to be used on a personal computer.


Personal databases 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 cen-
tralized location.

15
SIMPLE SQL

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.)

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 central-
ized 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.

16
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

Commercial Database:

( Figure 1.5 d)

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


mercial database. 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.

Relational Database
Any database that stores structured data in tables 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)

17
SIMPLE SQL

Relational databases is one of most used databases in the world and in this book.
We will be discussing in depth about relational databases only.

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

( Figure 1.5 f)

Graph Database

( Figure 1.5 g)

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

18
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

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.

19
SIMPLE SQL

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.

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 discussed most of them.
But in this book, we are primarily focused on 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 pro-
vides 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)

20
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

( Figure 1.6)

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 this physical location, in magnetic patterns groups (each
group is popularly known as bit). (See ,Figure 1.8, for reference)

21
SIMPLE SQL

( 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, vid-
eos, etc., are first converted in this format and 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 stor-
ing it in those hard disks!

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 storages.

22
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

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 it. 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’s height is 6ft
• Joey loves food
• Joey is an Actor

All this information is about one entity— Joey!

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

23
SIMPLE SQL

By tangible entities, I mean anything that has “physical existence” in this world.
And “intangible 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 below meaningful information related to it
(Also called its attributes), which describes it perfectly.

( Figure 1.10)

24
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

ENTITY: Dog
• Dog’s Name: Bruno
• Dog’s Breed: Pug
• Dog’s Colour: Brown
• Dog’s Height: 1.5 Feet
• Dog’s Weight: 8 Kilo grams
• 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 apparent 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 e.g.:
a) dog is an entity that is related to an owner. Both entities have their own attri-
butes 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
that have some sort of 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 relation-
ships or links between each entity, and hence there are different types of relationships
between entities:

ONE TO ONE
Whenever one record of 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).

25
SIMPLE SQL

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.”

( Figure 1.11)

ONE TO MANY AND MANY TO ONE


Whenever one entity can have a relationship with multiple entities, that is consid-
ered 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 number).
And every credit card has only one customer linked with it and establishes one-to-
many relationships.

( Figure 1.12)

26
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

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

( Figure 1.13)

For e.g.: Joey, Ross, and Sara started taking some courses for their professional develop-
ment 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 taking some courses online from
Udemy.

27
SIMPLE SQL

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)

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.

28
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

ENTITY-RELATIONSHIP MODEL
The Entity-Relationship Model is a logical model and representation of entities
and their relationships. Once this logical model is created, it gets easier to store data
in relational databases.
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 relation-
ships. Below are the different shapes and elements of an ER Model:

ENTITY
An entity is represented with a rectangular shape. ( 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)

29
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 relation-
ships, 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)

30
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

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

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)

Above notation represents the relationship that there can either be 0 or 1 connec-
tion between the entities.

0 OR MANY

( Figure 1.23)

Above notation represent either 0 or Many relationships can be present between


the mentioned entities.

31
SIMPLE SQL

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 credit card

( Figure 1.24)
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 got a better idea of how entities and relationships are repre-
sented in ER models.
To understand this concept on a much deeper level, 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.

32
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

SCENARIO: A SIMPLE ECOMMERCE SALES ER


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

STEP 1: IDENTIFYING THE ENTITIES


First, we need to identify the entities an e-commerce sales system has. So, in every
commerce system. There are below essential entities.

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

Although there are many more entities that are present e-commerce system, to
keep it simple to understand, we will only take a few of them. And will create an ER
model based on that.
let’s consider these 6 entities and create ER model on top of that.

33
SIMPLE SQL

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 effects.
d) Many orders are processed and delivered to a customer by one shipping
department.

STEP 3: CREATING THE ER DIAGRAM


We will create an ER diagram based on the information we have for this scenario.

( Figure 1.27)

34
CHAPTER 1 - MASTERING THE FUNDAMENTALS & DATABASES

As you can see 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.
We are surrounded by so much data that it needs to be organized so that anyone
can understand 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 foun-
dation for your career in the data field. The following section is dedicated to that
model popularly known as the Relational Model!

35
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 in
the market. That’s why understanding the relational model becomes quite essential.
In this chapter, I will be discussing 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 to you about relational databases systems, SQL,
and much more.

THE RELATIONAL MODEL

In the year 1970, a historical event happened that basically


changed the course of how we stored, processed, changed
data. Dr. Edgar F Codd published a paper “A Relational
Model of Data for Large Shared Data Banks” in the
research lab of IBM.
This relational model was then adopted by many big cor-
porations and companies for commercial purposes.
The concepts and terminology present in the relational
model are different than the ER model. Both models are dif-
( Figure 2.1) ferent and have their own techniques to represent the data.

37
SIMPLE SQL

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 ( mathematical discipline). A set is basically a collection
of unique elements ( i.e., without any duplicates )
Therefore, in the relational model, some constraints and rules that tell us how data
MUST be stored in the tables.
One of them is that the data is only stored in tables, which helps to get rid of dupli-
cate data entries. Removal of duplicates is done with the help of a unique identifier,
also known as a “Primary Key.”
The foundational concept we need to understand is the concept of keys, even
before we 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’s first understand some foundational concepts and build-
ing 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 can also be called a field. To be honest, most devel-
opers use fields instead of “attributes.”

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

a) StudentID

38
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

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

The Student table will be represented in Figure 2.2:

(Figure 2.2)

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

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

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

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

39
SIMPLE SQL

(Figure 2.3)

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

(Figure 2.4)

NULL Records: In a table ( or relation ), sometimes there is no value available for a


particular field ( attribute ), or the data is inappropriate. It is then represented by a
BLANK space in the table. NULL is entered whenever there is no value for an attri-
bute for a field.

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’s just used to describe “I don’t know” or the “information is
missing.”

40
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

(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) are called
attributes.

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

It is 6.

41
SIMPLE 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.

42
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

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 identi-
fying other attributes of a table.
The concept of keys is dependent on the concept of Determination.

Determination here means that if you know the value of an attribute of 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 the online platform. For this,
you just need Joey’s ID for that table.

That means StudentID DETERMINES CourseID

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.

43
SIMPLE SQL

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 candidate 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 col-
umns), which helps make every data row a UNIQUE row. While designing the data-
base, 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.

(Figure 2.9)

44
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

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)

45
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 with 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 rela-
tional table.
There are specific characteristics that define if a table is relational or not.

a) Sequence columns and rows are insignificant: Data in columns and rows can
exist without 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”. W
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 a relational tables!

(Figure 2.11 a)

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

46
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

(Figure 2.11 b)

c) No duplicate table name: In one relational database, the table name must be
unique. i.e., notable names with the same name can 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)

47
SIMPLE SQL

e) Column values must of same kind: All the values in a particular column must
be of the same kind—basically the same “datatype.” We will discuss what data
type is in the upcoming 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 relational 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 char-
acteristics of a table are in the relational model. Now, we will discuss how multiple
tables are connected in a relational database.

RELATING MULTIPLE TABLES


As I have discussed earlier, in a relational model, data is stored in the tabular for-
mat, 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 establish a relational model, those entities need to be con-
nected somehow, and the required information 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, that key is said to be a foreign key for table B.

48
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

The foreign key must be a primary key in the reference table.

(Figure 2.13)

These primary and foreign key relations help build relationships between tables
and eventually extract desired information. Although relating multiple tables with the
help of foreign keys helped establish complex relationships. But it created 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 is interdependent with each other and has some
meaningful associations and relationship with each other. Also In reality, data changes
updates and gets deleted from the tables, creating anomalies in the databases.
Let me explain about table dependencies and anomalies first..

49
SIMPLE 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 of 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, inconsis-
tency, 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:
A new course is added to the online course platform. But there is no student for
that course yet. In this case, we can’t assign value to the table student.

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


bute in a table in which we have dependent attributes. We can’t update or modify it

50
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

completely without creating inconsistency. We will need to update all the related rows
to ensure data is consistent in the table.

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 occurs in a database when we try to delete data
from a table, and that data is dependent on data present in any other attributes.

Example: Suppose any course creator decides to take down the course from the plat-
form 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 students’ 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.”

51
SIMPLE SQL

When the first rule is observed in the database, it is said to be in first 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.

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 present in the
data still, some discrepancies were still there. These were then removed by some higher
normal forms.
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 anoma-
lies 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.

52
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

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 understand 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 normalization is basically relating multiple tables of a complex sys-


tem without having any data anomalies. These relationships between the tables, makes
RDBMS better than other traditional database management systems.Other traditional
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.
Therefore, Codd presented rules of the relational model to make people aware
and understand what a relational database is. Any database management system that
follows these rules can be considered as RDBMS.
These rules are mentioned as below:

53
SIMPLE SQL

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 combin-
ing 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 information. 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 authorized users using queries.

Breakdown: Usually, we store some data of an organization, Application, e-com-


merce systems, etc. These databases 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?
All the little information can be extracted using SQL by authorized users.
For example: An authorized user can check the number of columns for any table
by executing a SQL command.

54
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

#Rule 5: The Rule Of Comprehensive Data SubLanguage


There must be one “well-structured” language that helps in accessing, manipulat-
ing, managing 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 a
later chapter ). 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 has 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 opera-
tions like union, intersection, and minus.

55
SIMPLE SQL

Breakdown:
As per Codd, the database management system must allow the users to manipu-
late 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.

#Rule 8: The Rule Of Physical Data Independence


The changes at the table’s physical location must not impact the data at the appli-
cation level.

Breakdown:
According to this rule, the changes or modifications on 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 application or programs. And the integrity constraints must be stored in the
database catalog.

56
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

Breakdown:
There are different kinds of data being stored and accessed in the database and,
there are specific rules or constraints in a table (You will learn about them in later
chapters) 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 maintain its integrity.

#Rule 11: The Rule Of Distribution Independence


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

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, database 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 lan-
guage 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 a RDBMS.
Now let me explain more on RDBMS..

57
SIMPLE SQL

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 most of the DBMS applications are RDBMS. Some of them are:

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

58
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

(Figure 2.14)

After looking at the benefits RDBMS provides, many major corporations devel-
oped their own RDBMS based on the relational model developed by EF Codd.
I have listed 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 favourite as it’s open-
source and free.
c) Oracle Database: Developed by oracle corporation and used by leading indus-
tries for secure data management.

59
SIMPLE SQL

d) IBM DB2: Developed by IBM for advanced data management and data analyt-
ics capabilities.
e) PostgreSQL: Another free and open-source RDBMS that is a favourite of devel-
opers and leading corporations.

And the list goes on…


There are hundreds of RDBMS nowadays present in the market today.
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 what I want you to master.

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
complexity. Unlike other programming languages, SQL is relatively easy.
Portablility: 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.

60
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

HISTORY AND BIRTH OF SQL


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

(Figure 2.15)

61
SIMPLE SQL

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.
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 working with SQL.
The primary purpose of the development of SQL was to do four types of funda-
mental operations that provide control over data and databases:

CREATE: This operation helps in creating a database. There are specific commands
that help create database tables and insert values in those tables.

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 and 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 commu-
nicating and manipulating data present in the database.

62
CHAPTER 2 - THE RELATIONAL MODEL, RDBMS AND SQL

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 of 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 behavioural data, their likes and dislikes. These data points are critical deci-
sion-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.

63
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

64
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

65
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

66
SQL

CHAPTER 3

DATACEPTION:
Data, Datatypes and Metadata

I n this chapter, you’re going to learn more about datatype and types of datatypes.
Also, you’ll be exploring about metadata a well in this chapter. When you under-
stand how the data is stored, 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 it 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 understand-
ing the basics mentioned in this part of the book. All the topics in this section are care-
fully chosen and hold a massive value for individuals aspiring to build their careers in
the IT industry.
Now, lets get back the main topic…

UNDERSTANDING DATATYPES
Till now, you know about relational database and know 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 a specific datatype based on the type of information the column holds.
Let me explain with an analogy.

67
SIMPLE SQL

suppose we have three buckets; we allowed to only store water in bucket 1. In


bucket 2, we 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)

(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 and not alphabetical. Similarly, a student’s name must be of an alpha-
betical type and not of any other type like numerical. This maintains the quality of
data, and when we are trying to sort and access data, it becomes more readable and
uniform across all applications.

68
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

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 par-
ticular data type.
To design tables and other database objects. This is the essential step to do because
what kind of data will be in columns of tables ensures the data quality, ease of access,
and readability.
Based on what type of relational database management system (RDBMS) a devel-
oper 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 datatype, we will use MS SQL Server datatypes.
Datatypes are classified into 3 categories:

a) Numeric Datatypes: Numeric datatypes helps in storing 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 that 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 a few of them to make this book beginner-friendly.

Let’s take the category of numeric datatype first:

69
SIMPLE SQL

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.
Example: The pi (π) value is represented as 3.141592654 in calculators and other
systems, not because the values are limited to 10 digits only. But because of ease of
calculation and representation.

(Figure 3.2)

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

Exact Numeric and Approximate Numeric.

70
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

(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 par-
ticular column.
Whereas scale (s) is the number of digits allowed after the decimal.

(Figure 3.4)

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

TINYINT
SMALLINT
INTEGER

71
SIMPLE SQL

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 potential numeric values are allowed for this column.
For example, The table of your online test (Test) has a column Student_Score, and
the maximum marks a student can score in that test is for 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

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.

72
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807


Storage Space: 8 Bytes

DECIMAL
To store the decimal data, this datatype is widely used. While designing table,
we need to enter the details about how many digits are allowed before and after the
decimal.
In order to do this, below syntax is used.
Decimal (p,s)
For example, decimal (6,2) will allow total values of 6 (precision) and 2 values after
the decimal (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 “func-
tionally” 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.
Range for SMALL MONEY datatype: -214,748.3648 to 214,748.3647
Storage Space for SMALL MONEY in SQL Server: 4 bytes

73
SIMPLE SQL

MONEY
MONEY datatype is also a dedicated datatype especially designed to handle cur-
rency 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
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 data-
type, can be easily represented using approximate data type. It is best to use this data-
type 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 numbers keep on
“Floating” in floating numbers.

74
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

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.

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 pre-
cision 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

75
SIMPLE SQL

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…

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
database, 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 is 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)

76
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

Where n means for 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

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 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.

77
SIMPLE SQL

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 numerical 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 rep-
resents 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 in disks.
Now let me tell you the syntax of the binary datatype.

78
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

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 behaviour 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
hexadecimal 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 manip-
ulates it at a deeper level.

BINARY (5) column can store up to 5 binary bytes 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 in a “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”;

79
SIMPLE SQL

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

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 maxi-
mum 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.
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.

80
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

DATETIME
This datatype is used to store the “Date and Time” values in a column. This data-
type is
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

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 tables 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. [. frac-
tional seconds]”
Example: In a column with datetime2 datatype below values can be stored easily

2025-05-21 10:15:30.5555555

81
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

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

A Time zone is a place in a geographical region where the people residing and
traveling observe at 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 << add the relavant content here>
[{+|-}hh:mm] are used to represent offset values.

82
CHAPTER 3 - DATACEPTION: Data, Datatypes and Metadata

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]

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 informa-
tion about these entities.
Basically, It’s Data about Data, also known as Metadata.
For Example, An Image is data that is collected by your phone’s camera. The infor-
mation about that image is, the image’s metadata.

83
SIMPLE SQL

(Figure 3.6)

Below is the type 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 much other related information.

84
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)

85
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

86
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 precious time learning the foundational topics in part 1 of this book, your excite-
ment level to learn SQL might be going through the roof!
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 uses SQL, so learning SQL and database fundamentals are much
more important 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 work with.
This chapter is completely dedicated 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 windows and get the software installation com-
pleted today!

89
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 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.

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

90
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(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)

91
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)

Options are:

a) Basic: If you select this 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.

92
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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

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)

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 instal-
lation or add features… section.” ( See Figure 4.1 f for reference.)

93
SIMPLE SQL

(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 installa-
tion setup, Tick the checkbox to check for any new updates. ( See Figure 4.1 h for
reference.)

(Figure 4.1 h)

94
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)

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.

95
SIMPLE SQL

(Figure 4.1 j)

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!

96
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

13th Step: Now, it will move to the product key section (Figure 4.1 k)); for us, we
will 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)

97
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)

98
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

15th Step: Once you agree and click next, the next section will be “feature selec-
tion.” 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)

99
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” in the instance name and instance ID field in
my system. i.e., SQL_SERVER. Once done, click “Next.”

(Figure 4.1 n)

100
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

17th Step: In 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.
Click next and proceed to the next step.

(Figure 4.1 o)

101
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)

102
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)

103
SIMPLE SQL

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

(Figure 4.1 r)

104
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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

(Figure 4.1 s)

105
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 management studio.
https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-stu-
dio-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)

106
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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

(Figure 4.1 u)

(Figure 4.1 v)

107
SIMPLE SQL

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

(Figure 4.1 w)

108
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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

(Figure 4.1 x)

109
SIMPLE SQL

26th Step: Setup is now finished!

(Figure 4.1 y)

Finally Access Your SQL Server: Now you have installed the SQL Server
Management studio. You can now access the newly installed software on your laptop
or PC.

110
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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)

111
SIMPLE SQL

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 we were doing the
installation.
As you can see (figure name).
In my case, I tried connecting to a server and faced an error. This is because I have
not mentioned the name of the Instance, I wanted to connect.
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.

112
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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

(Figure 4.2 c)

In the upcoming chapters, You will be spending a lot of time in the studio. You will
be creating many databases and database objects and will be learning 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.

113
SIMPLE SQL

PART 1: INSTALLING DOCKER


STEP 1: Install and Configure Docker
To install docker on your system visit, the 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
To select one of them, you must first identify if your MAC has an Intel chip or
Apple chip.

114
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(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)

115
SIMPLE SQL

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)

116
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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)

117
SIMPLE SQL

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

(Figure 4.3 h)

(Figure 4.3 i)

118
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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)

119
SIMPLE SQL

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

(Figure 4.3 k)

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.

120
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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.

121
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.

sudo docker pull microsoft/mssql-server-linux

122
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(Figure 4.3 n)

Wait until the download is completed.

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.

123
SIMPLE SQL

-e ‘ACCEPT_EULA=Y’ : This part of the above command accepts the user


license agreement, 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 pass-
word 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 basi-


cally selects the image file for the docker.

(Figure 4.3 n)

(Figure 4.3 o)

124
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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)

125
SIMPLE SQL

(Figure 4.3 r)

126
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

PART 3: AZURE DATA STUDIO INSTALLATION


Till now, we have downloaded the SQL Server in our system. But, still, to access
SQL Server to create and execute queries, we require a management tool with a graph-
ical 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-server-ver15
scroll down a bit, click and download the azure data studio .zip file.

(Figure 4.3 s)

127
SIMPLE SQL

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.

(Figure 4.3 t)

128
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

(Figure 4.3 u)

129
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)

130
CHAPTER 4 - INSTALLATION OF SOFTWARE TOOLS

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)

131
SIMPLE SQL

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 be studying how to work on SQL Server
Be ready to get your hands dirty with SQL.

132
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 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 considered 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 about ‘what’s the
phone number of Joey?’ and the Database will answer!

133
SIMPLE SQL

To communicate and ask questions to a database, a standard and structured lan-


guage (SQL) are 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 manipulating the data in databases tables.

NUT AND BOLTS OF SQL STATEMENTS


I hope till now you understand the scope and usage of SQL. Now, in this section, I
will present different types SQL statements that we will be using frequently.
As I told you before, In SQL, whenever we want to do some operation, we just
need simply write our statements in the SQL server and we can expect a desired result.
The only thing we need to keep in mind is that the SQL statements that we are writing
are 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 data-
base to get the desired results

134
CHAPTER 5 - MASTERING SQL QUERIES

SELECT FirstName,LastName,EmailID
FROM TableEmployee;

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

(Figure 5.3)

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

KEYWORDS
In SQL statements, Keywords are the predefined and reserved keywords. Many
keywords 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.

135
SIMPLE SQL

CLAUSES
A SQL clause is a meaningful part of a SQL statement that uses reserved SQL
keywords to construct an effective SQL statement. From the above SQL Query, let
me explain about 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)

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 data-
set (Using SQL Queries), Creating Databases, Creating and Deleting Tables, and much
more.
To make it easy to work with data present in the database tables, each operation is
categorized into different categories based on the nature of the operation.

136
CHAPTER 5 - MASTERING SQL QUERIES

There are five different 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.

137
SIMPLE SQL

DATA DEFINITION LANGUAGE (DDL)


SQL commands that are used to define, create and modify the structure of a data-
base 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 in changing and modifying the already cre-
ated database structure and database objects.

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

TRUNCATE: TRUNCATE command deletes all the rows and data present in a
table at 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 in a database table.

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

DELETE: The purpose of 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 that has a command used to
retrieve data from the database. DQL has only one command—SELECT; This com-
mand does the fetching the data.

138
CHAPTER 5 - MASTERING SQL QUERIES

SELECT
The SELECT command helps in retrieving data from a table. This command can
also be used with different clauses to filter out the results we want to extract, based on
the condition we mention in the SQL statement.
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 partic-
ular command.

DATA CONTROL LANGUAGE (DCL)


Data Control Language ( DCL ) category has the commands that are used to con-
trol access, permissions, and rights for a user in a database. These commands help in
enforcing security in the database.
In simple words, DCL commands help distribute and revoke the responsibilities to
users. 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.

139
SIMPLE SQL

UNDERSTANDING PRIVILEGES
Privileges are basically the “rights” given to a user to access a database object
or perform 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 restau-
rant, 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

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 database 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 working on live projects.

140
CHAPTER 5 - MASTERING SQL QUERIES

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: user 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 in a table.

UPDATE: A user with UPDATE privileges can execute the UPDATE com-
mand and modify the existing values in a table.

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

TRANSACTION CONTROL LANGUAGE (TCL)


In live projects, applications and users constantly extract, load, and modify data.
For example, 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.
Whenever the COMMIT command is executed in a database, the transactions and
changes made get solidified.

141
SIMPLE SQL

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 perma-
nently in database tables.

Syntax:
COMMIT;

SAVE TRANSACTION:
SAVE TRANSACTION command temporarily saves transactional data in a data-
base. 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 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;

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.

142
CHAPTER 5 - MASTERING SQL QUERIES

PRACTICING SQL COMMANDS

CREATING SIMPLE DATABASES AND DATABASE OBJECTS


WITH DDL
I hope you understood about the SQL commands and the different categories of
the SQL commands until now. I have presented most of the foundational concepts and
now, in this section, You and I will use these commands create a 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 attri-
butes 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..

143
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)

144
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


Execute the below command in order to create a Database in SQL server with the
name MyEcommerceDB.

CREATE DATABASE MyEcommerceDB ;

145
SIMPLE SQL

Step 5: Exploring the newly created database.


Go to the object explorer, expand the database section and see your newly created
database!

(Figure 5.6 c)

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

146
CHAPTER 5 - MASTERING SQL QUERIES

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)

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

147
SIMPLE SQL

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,
..
..
..
..
);

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:

148
CHAPTER 5 - MASTERING SQL QUERIES

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 create products
table. ( See Figure 5.7 for reference)

(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.

149
SIMPLE SQL

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 Sellers
table.
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
);

150
CHAPTER 5 - MASTERING SQL QUERIES

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),
);

Now, Execute the SQL Statement.


Now we have created a database and objects with the DDL statements. The next
step is to insert data and view the data we inserted in each table.

151
SIMPLE SQL

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;

152
CHAPTER 5 - MASTERING SQL QUERIES

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, then use the below syntax.

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 the 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.

153
SIMPLE SQL

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’;

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 in the customer table with the help of INSERT com-
mand. 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)

154
CHAPTER 5 - MASTERING SQL QUERIES

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’);

(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)

155
SIMPLE SQL

(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)

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;

156
CHAPTER 5 - MASTERING SQL QUERIES

(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
will encounter 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’);

157
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;

158
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 columns 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.

159
SIMPLE SQL

The syntax for UPDATing a particular record is:

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

The above SQL Statement will only update the record to satisfy the condition
mentioned 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 satisfy 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.

160
CHAPTER 5 - MASTERING SQL QUERIES

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.

(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.

161
SIMPLE 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 seems 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.
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’;

162
CHAPTER 5 - MASTERING SQL QUERIES

(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.

163
SIMPLE SQL

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

164
CHAPTER 5 - MASTERING SQL QUERIES

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)

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 Student Address columns from Students table

165
SIMPLE SQL

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;

166
SQL

CHAPTER 6

UNDERSTANDING
TABLES IN DEPTH

I n the previous chapter, I explained you that creating tables comes under the cate-
gory of Data Definition Language commands in SQL. You also learned to Create
simple tables in the last chapter.
In this chapter, you will be levelling up your game! 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 have discussed more about the basics of designing and
building simple tables with one primary key and a few columns to store data. In this
section, I will be discussing about creating tables that can be used in advanced rela-
tional 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 few 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

167
SIMPLE SQL

entities and the data that needs 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.

(Figure 6.1)

168
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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 identi-
fied in that entity. For example, suppose you have identified a “Student” as an entity.
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 attributes becomes.

STEP 3: IDENTIFYING THE KEYS ATTRIBUTES


The next step is to identify the key attributes and constraints you want for your
table.
Let’s break this process down in a step-by-step manner:

169
SIMPLE SQL

IDENTIFYING THE KEY ATTRIBUTES:


Once all the potential attributes are identified for the table, that 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 is Student and Courses, and both have
below identified entities:
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.

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 col-
umn of a table. These rules help limit the type of data inserted in the column.

170
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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 con-
straint, a NULL value will not 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.

171
SIMPLE SQL

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’);

172
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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.

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’);

173
SIMPLE SQL

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 hav-
ing 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.

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.

174
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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’,’[email protected]’);

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


VALUES (‘102’,’Will’,’James’,’[email protected]’);

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


VALUES (‘103’,’William’,’McBeth’,’[email protected]’);

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.

175
SIMPLE SQL

(Figure 6.3 a)

See in Figure 6.3 a, when we try to enter duplicate values in a column with a
UNIQUE constraint, 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 system must insert the record in the table.

176
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

Let’s find out.

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


VALUES (‘103’,’William’,’McBeth’,’[email protected]’);

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

(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.

177
SIMPLE SQL

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)
);

(Figure 6.4 a)

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

178
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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


VALUES (‘111’,’Andrew’,’Mikkelson’,’[email protected]’);

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


VALUES (‘112’,’George’,’Keller’,’[email protected]’);

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


VALUES (‘111’,’Sia’,’wade’,’[email protected]’);

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

(Figure 6.4 b)

179
SIMPLE SQL

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’,’[email protected]’);

180
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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

(Figure 6.4 d)

The above example displays that a column with PRIMARY KEY CONSTRAINT
can’t have duplicate values.
Now, to 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’,’[email protected]’);

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

181
SIMPLE SQL

(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’,’[email protected]’);

(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.

182
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

(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 relation-
ship is quite helpful because it helps in referential Integrity in the database.
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 con-
nected using a relationship must always be in sync during data manipulation opera-
tions (INSERT, UPDATE and DELETE).

183
SIMPLE SQL

Let’s discuss using an example to understand the concept of foreign key constraint
and referential 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 company’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:

CREATE TABLE Employee


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

184
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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 data-
base needs to enter this event in the database. As you can see, the column data of
DepartmentID 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 ref-
erencing 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 addi-
tion, 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’);

185
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)

186
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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 mentioned 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 refer-
ential integrity.
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, inserting values 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’;

187
SIMPLE SQL

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)

(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 reliability 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.

188
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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;

(Figure 6.4 l)

189
SIMPLE SQL

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, the related records are
present 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 that you want to delete from both parent and child
tables.
3rd Step: ADD constraint back again.

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.

190
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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 col-
umns, 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’);

191
SIMPLE SQL

As you can see in the above mentionedInsert 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 automatically put 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 a statement for the table. When
the condition is satisfied, only then is the record inserted. Else the record will not be
inserted in 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.

192
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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.
[email protected]’,’999’);

(Figure 6.4 o)

193
SIMPLE SQL

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’,’[email protected]’,
’1000’);

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

(Figure 6.4 p)

After identifying the correct constraint requirement for the table, you’re building.
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.

194
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

BEST PRACTICES FOR CREATING TABLES THAT


EVERY DEVELOPER WILL RESPECT YOU FOR
I am pretty confident that you have learned how to design and create tables until
now. 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-de-
veloper. 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 their tables. So, the best practices for creating tables
are:

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 consis-
tency. 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’.

195
SIMPLE SQL

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.

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.

196
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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!

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 data-
base 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 complex 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.

197
SIMPLE SQL

You can add your comments in two ways:


Entering a single line: 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 com-
ments in the query.
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: When you want to enter an entire paragraph to explain what-
ever 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]

198
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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.

ADDING ALIASES:
Alias in SQL is a temporary name that 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;

199
SIMPLE SQL

INSERTING, UPDATING and DELETING THE DATA IN


THE TABLES
Once you have created tables that you want for the entities, that you have iden-
tified. It’s an obvious 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.
All these operations are done using the DML commands. Although, I have already
discussed this previously, but in you will learn some more advanced stuff related to all
these DML commands in this section.

POPULATING DATA IN TABLES USING INSERT


There are many different ways to enter data in a table. In the initial chapters, I
taught you how to insert data in a table in the easiest way possible. I discussed about
the simple way you can insert the records in a table. There are multiple ways you can
use to insert data in 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.

200
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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,
..
..
..
);

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!

201
SIMPLE SQL

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 values in the column. Then entering values for those specific col-
umns 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 columns 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 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 state-
ment, 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?

202
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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 state-
ment is below:

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 created the new table, I will execute the below sql statement to import data
from the Employee table to the newly created table (EmployeeNew).

203
SIMPLE SQL

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


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

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 automati-
cally and put all the data from SourceTable into it.
Here the * represents that all the rows and column 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.

204
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

Let me show this to you with an example. First, let me try to copy only a few col-
umns 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.
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 out some time for the exercises at the end of this chapter before
moving ahead for better understanding about the concepts covered in this chapter.

205
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


SQL For
B101 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)

206
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

GeoID CountryName Region


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

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


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

BankAccount ( AccountID, AccountName, CustomerName, CustomerID)

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

207
SIMPLE SQL

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..

8) 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.

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

CourseID CourseName CourseType CoursePrice


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

208
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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.

209
SIMPLE SQL

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,

210
CHAPTER 6 - UNDERSTANDING TABLES IN DEPTH

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

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 SCIPT 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’);

211
SIMPLE SQL

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

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 ;

212
SQL

CHAPTER 7

PLAYING WITH DATA


USING SELECT

I n previous chapters, I have 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 simultaneously 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 question decides the quality of the answer we get from the database.
The more specific your question will become, the more detailed, refined, and accu-
rate 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 is can be done with the help of SQL
clauses.

213
SIMPLE SQL

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.

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:

214
CHAPTER 7 - PLAYING WITH DATA USING SELECT

TOP
TOP is commonly used after the SELECT clause and before the column names. It
is also popularly 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 #1:
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 asterisk(*) after the TOP 10. This will display all the available columns.

SELECT TOP 10 * FROM [MyEcommerceDB].[dbo].[Employee];

Example #2:
Display Job Roles and Date Of Birth of Top 5 records from the Employee table.

SELECT TOP 5 Role,DateOfBirth


FROM [MyEcommerceDB].[dbo].[Employee];

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.

215
SIMPLE SQL

Example #1:
SELECT the unique Deparment ID’s from the Employee Table.
Approach: I would apply DISTINCT on the Deparment ID column. The query will
look something like this:

SELECT DISTINCT DepartmentID FROM [dbo].[Employee]

Example #2:
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 #1:
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];

216
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Example #2:
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 filter-
ing 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 #1:
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.

217
SIMPLE SQL

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.

218
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.1

GROUP BY can also be used to see the DISTINCT values present of 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:

219
SIMPLE SQL

COUNT ()
Count() function is used to calculate the total number of rows in a the selected
column.

For 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

220
CHAPTER 7 - PLAYING WITH DATA USING SELECT

SUM ()
SUM () function calculates the sum of all the values present in the selected column.

Example 1:
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 # 2: 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];

221
SIMPLE SQL

Figure 7.5

The above query groups the data based on Job Role and then adds the data of
Salary Separately for each group (ie: Job Role group).

AVG ()
Average function calculates the average value present in a column.

Example #1:
Calculate the average Salary for all the records present in the Employee table.

SELECT AVG(Salary) AS AverageSalary


FROM [MyEcommerceDB].[dbo].[Employee];

222
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.6

Example #2:
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.

223
SIMPLE SQL

Figure 7.7

MIN ()
MIN () function is used to find out the lowest value present in a particular column.

Example #1:
Retrieve the lowest number of SickLeaveHours from the table Employee.

SELECT MIN(Salary) AS LowestSalary


FROM [MyEcommerceDB].[dbo].[Employee];

224
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.8

Example #2:
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

225
SIMPLE SQL

MAX ()
MAX () function calculates the highest value present in a particular column.

Example #1:
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 #2:
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 is grouping the data by the job Role and then selecting the high-
est salary for each group. See the final results after executing in the Figure 7.11 .

226
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.11

THE HAVING CLAUSE


The HAVING clause helps in filtering out the 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 sepa-
rates HAVING from WHERE clause is that HAVING CLAUSE can only be used with
GROUP BY clause.
Whereas the WHERE clause can be used even without GROUP BY.

227
SIMPLE SQL

Syntax:
SELECT Column1, Column2, Column3 . . .
FROM NameOfTheTable
GROUP BY Column1, Column2, Column3. . .
HAVING Condition;

Let me explain this with an example..

Example #1:
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 average Salary of more than
80000.

SELECT Role
FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY Role
HAVING AVG(Salary)>’80000’;

Figure 7.12

228
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Example #2:
Display the headcounts for each job role from Employee Table where the head-
count 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!

Figure 7.13

229
SIMPLE SQL

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 #1:
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;

230
CHAPTER 7 - PLAYING WITH DATA USING SELECT

Figure 7.14

Example #2:
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;

231
SIMPLE SQL

Figure 7.15

So now you understand how clauses help analyse data and make it easy for a
developer to play with data. Analysing 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 fil-
tering 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.

232
CHAPTER 7 - PLAYING WITH DATA USING SELECT

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:

COMPARISON OPERATORS IN SQL

SQL Equal to Operator (=)


SQL Equal To Operator checks if the value present in the left-hand side of equal
to (=) operator matches the value present in the Right-Hand Side of the (=) Operator.
Let me explain this with an example:

Example #1: 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 in the left-hand side of the not
equal to the operator with the value present in 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.

233
SIMPLE SQL

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.

SQL Less Than Operator (<)


The Less Than Operator in SQL only displays data from tables that are less than
the value present in 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 sal-
ary 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.

234
CHAPTER 7 - PLAYING WITH DATA USING SELECT

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’;

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’;

235
SIMPLE SQL

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!

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:

236
CHAPTER 7 - PLAYING WITH DATA USING SELECT

AND
In SQL, Logical operator AND allows us to work with two conditions simultane-
ously in a single query. The conditions are based on Boolean expressions.
Syntax for AND operator:

SELECT Column1, Column2..


FROM NameOfTheTable
WHERE BooleanExpression1 AND BooleanExpression2;

The AND operator will only return TRUE and work properly when both the con-
ditions, separated 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 dis-
play matches both conditions, 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 need to be matched.

SELECT *
FROM [MyEcommerceDB].[dbo].[Employee]
WHERE DateOfBirth<’1973-11-12’
AND Salary <’100000’ ;

The above has displayed the results of the records where it is TRUE for both the
condition where 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. The data needs to satisfy both the conditions in AND operator.

237
SIMPLE SQL

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
will be displayed in the resulting 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 defining 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.

238
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 dif-
ference between IN and EQUAL TO is that EQUAL TO deals with only a single com-
parison. 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…);

239
SIMPLE SQL

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:

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 pat-
terns and values mentioned below:

a) It uses the underscore (_) sign. (_) represents only one character.
b) It uses the percentage (%) sign. Percentage sign can represent 0,1 or even mul-
tiple characters.

240
CHAPTER 7 - PLAYING WITH DATA USING SELECT

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 #1:
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.
It doesn’t matter what the rest of the letters are 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 con-
cern for us.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role LIKE ‘M%’;

Example #2:
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 characters and can be used when we are unaware of the actual number of
characters.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role LIKE ‘%er’ ;

241
SIMPLE SQL

Example #3:
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%’;

Example #4:
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 char-
acter 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. it will return FALSE.
Let me explain this with an example.

Example #1:
Retrieve all the records from the Employee table whose Job Role Does Not Start
With character ‘M.’

242
CHAPTER 7 - PLAYING WITH DATA USING SELECT

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%.’

SELECT * FROM [MyEcommerceDB].[dbo].[Employee]


WHERE Role NOT LIKE ‘M%’;

Till now in this chapter, I explained you about the power of SQL SELECT state-
ment and the different clauses that we can use with SELECT statement and analyse
data effectively.
I want you to also understand how the evaluation and processing of a SQL query
is done.

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 filter-
ing out the records that are grouped together.

243
SIMPLE SQL

The SELECT clause: Eventually, after all the evaluation is done, the SELECT
clause is evaluated in the last.

Figure 7.16

If you have 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 long way to go. Before moving to the next chapter, make
sure to practice all the questions at the end of this chapter.

244
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 val-
ues 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” any-
where in their Name.

245
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’;

246
CHAPTER 7 - PLAYING WITH DATA USING SELECT

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;

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’;

247
SIMPLE SQL

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’;

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%’;

248
SQL

CHAPTER 8

MASTERING SQL FUNCTIONS

W hen we work in 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 mean-
ingful. 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 particular 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 dataset
c) Data types conversion

A function is 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.

249
SIMPLE SQL

There are broadly two categories of functions available in SQL:

a) System Defined Functions


b) User Defined Functions

Figure 8.1

250
CHAPTER 8 - MASTERING SQL FUNCTIONS

SYSTEM DEFINED FUNCTIONS


A system-defined function is a built-in function defined by the database system.
Many system-defined functions are available in RDBMS to make it easier for develop-
ers 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

Figure 8.2

The above-mentioned system-defined functions help us analyse, process, and


manipulate data efficiently and quickly. Let me explain each one of the user-defined
functions one by one.

251
SIMPLE SQL

AGGREGATE FUNCTIONS
Aggregate functions are system-defined functions that help do mathematical oper-
ations 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 maximum or minimum value present in a column.

Figure 8.3

Below mentioned are the aggregate functions used in SQL:

MAX ()
Returns the biggest value present in the selected column on which the function is
applied.

Syntax
SELECT MAX(NameOfTheColumn)
FROM NameOfTheTable;

252
CHAPTER 8 - MASTERING SQL FUNCTIONS

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 () function is applied.

Syntax:
SELECT AVG(NameOfTheColumn)
FROM NameOfTheTable;

253
SIMPLE SQL

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:

254
CHAPTER 8 - MASTERING SQL FUNCTIONS

Figure 8.4

255
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.

256
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 #1:
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 #2:
Display each Employee Name along with Length Of each Employee Names pres-
ent 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’)

257
SIMPLE SQL

Example:
Find the substring ‘ep’ substring in the main string ‘DataCeps’.

SELECT CHARINDEX (‘ep’, ‘DataCeps’) AS


CharacterLocation;

Result: 6
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 starting 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 character. At the same time, the CHARINDEX
does not use the wildcard characters.

258
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example:
Find the substring ‘Ceps’ substring 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 char-
acters depends upon the count value in the main function

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];

259
SIMPLE SQL

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];

LTRIM
The LTRIM function helps remove the extra spaces from the left side of the men-
tioned main string.

Syntax:
LTRIM (‘ String’)

Example: Remove the extra white spaces from the LEFT side of the

260
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

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’);

261
SIMPLE SQL

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)
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

Example:
Replicate each Employee Name present in Employee table 4 times.
SELECT REPLICATE(EmployeeName,4) AS ReplicatedName
FROM [MyEcommerceDB].[dbo].[Employee];

262
CHAPTER 8 - MASTERING SQL FUNCTIONS

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 character will be square brackets ([ ]).
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 ( { } )

263
SIMPLE SQL

Example #1:
Put the string ‘DataCeps’ inside the curly brackets ( { } ) using SQL function.

SELECT QUOTENAME(‘DataCeps’, ‘{}’);

Result:
{DataCeps}

Example #2:
Display each employee Name present in the employee table inside the curly brack-
ets ({}).

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

264
CHAPTER 8 - MASTERING SQL FUNCTIONS

STR
STR function is used to converts 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.

265
SIMPLE SQL

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.

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.

266
CHAPTER 8 - MASTERING SQL FUNCTIONS

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];

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];

267
SIMPLE SQL

UPPER
The UPPER function helps in converting upper case characters to lower case.

Syntax:
UPPER(‘String’)

Example #1:
Convert the string value ‘dataceps’ in uppercase using string function?
SELECT UPPER (‘dataceps’);

Example #2:
Display each employee name present in the employee table in Uppercase

SELECT UPPER(EmployeeName) AS UpperCased


FROM [MyEcommerceDB].[dbo].[Employee];

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

268
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

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 men-
tioned string value.

269
SIMPLE SQL

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]’, ‘[]’, ‘{}’);

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 func-
tion deals with characters.
REPLACE( ) function replaces the string entirely with another on one go. In com-
parison, the TRANSLATE( ) function replaces the characters of a string byte-by-byte.

270
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

CONCAT_WS:
CONCAT_WS function returns the concatenation of two or more string values.
However, the concatenated string will be concatenated using a separator.

Syntax:
CONCAT_WS(‘Separator’, ‘String1’, ‘String1’,’String1’. . . . ‘String (n)’)

271
SIMPLE SQL

Example:
SELECT CONCAT_WS (‘#’, ‘SQL’, ‘PRACTICE’,’REPETITION’);

Result:
SQL#PRACTICE#REPETITION

CONCAT USING +
CONCAT USING + function 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];

After string values, the most common types of values that you will observe in most
datasets will be date-time. So, SQL offers Date Time Functions to work effectively
with date-time datatypes.

272
CHAPTER 8 - MASTERING SQL FUNCTIONS

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.

273
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”

274
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 char-
acter string type.

Syntax:
DATENAME (PartOfDate, YourMainDate)

275
SIMPLE SQL

Where,
PartOfDate = The PartOfDate is the part you want to extract and display from the
main input date.
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.

YourMainDate= The main date from which you want to extract values.

Example #1:
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

276
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example #2:
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 #3:
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

Example #4:
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

277
SIMPLE SQL

DAY
DAY function only extracts the day part from the main input date.

Syntax:
DAY(date)

Example:
SELECT DAY(‘2021-11-25’);
Result: 25

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 YEAR(‘2021-11-25’);
Result: 2021

278
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

Example #1:
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 #2:
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

279
SIMPLE SQL

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 and Date2= The two dates where you want calculate the differences.

Example #1:
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

Example #2:
Subtract months in the date value -- ‘2015-11-25’ and ‘2020-11-25’.
SELECT DATEDIFF(mm, ‘2015-11-25’, ‘2020-11-25’);

Result:
60

280
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

281
SIMPLE SQL

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);

282
CHAPTER 8 - MASTERING SQL FUNCTIONS

Result:
0.956375928404503

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

283
SIMPLE SQL

ASIN
ASIN function in SQL returns the Arc Sine of the number mentioned inside the
ASIN function.

Syntax:
ASIN (Number)
Where, Number = The number range for which you want to find out Arc sine val-
ues. 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

284
CHAPTER 8 - MASTERING SQL FUNCTIONS

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.

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

285
SIMPLE SQL

DEGREES
DEGREES function in SQL coverts the mentioned value from radian to degrees.

Syntax:
DEGREES (Number)
Example:
SELECT DEGREES(3.6);

Result:
206.264806247096373681

EXP
If you want to calculate the exponential value of a given number, then EXP func-
tion 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

286
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

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 loga-
rithm will be calculated.

Example:
SELECT LOG(2, 3);

Result:
0.5

287
SIMPLE SQL

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

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);

288
CHAPTER 8 - MASTERING SQL FUNCTIONS

Result:
8

RADIANS
RADIANS helps in converting a degree value into radian values.

Syntax:
RADIANS (Number)

Example:
SELECT RADIANS(180);

Result:
3

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

289
SIMPLE SQL

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 number of decimal values.
If this value is other than 0, then it basically truncates the results, to the number
of decimal values.

Example #1:
SELECT ROUND(123.321252123, 3, 0);

Result:
123.321000000

Example #2:
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.

290
CHAPTER 8 - MASTERING SQL FUNCTIONS

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

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

291
SIMPLE SQL

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
programming 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 opinion, 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.
Now let me explain to you about Parameters...

292
CHAPTER 8 - MASTERING SQL FUNCTIONS

A Parameter is a special type of variable that is utilized to pass the data and infor-
mation 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 com-
plex 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.

293
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 SQL statement, 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.

294
CHAPTER 8 - MASTERING SQL FUNCTIONS

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:

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 books 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.

295
SIMPLE SQL

Syntax:
SELECT SchemaName.FunctionName();

Example:
SELECT dbo.TotalEmpSalary();
Execute the function using EXEC command.

Syntax:
EXEC SchemaName.FunctionName;

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));

296
CHAPTER 8 - MASTERING SQL FUNCTIONS

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.
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.
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 func-
tions for their applications and avoid doing repetitive calculations. I hope you now
have entirely understood about how functions work. The next section of this chapter
is all about levelling up your game with some advanced functions that advance devel-
opers and expert developers use to compare, contrast and extract insights from the
data.

297
SIMPLE SQL

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 calcula-
tions 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.
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

298
CHAPTER 8 - MASTERING SQL FUNCTIONS

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 function-
alities. However, there are significant differences between them. Some of these differ-
ences are mentioned in the Figure 8.9.

Figure 8.9

OVER clause:
The OVER clause is commonly used with PARTITION BY clause . To create rank-
ings, we 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];

299
SIMPLE SQL

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.
Following are the different types of ranking functions in 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.

Example:
Let’s take an example of a table-- Employee.
Currently, The employee tables has the data as:

300
CHAPTER 8 - MASTERING SQL FUNCTIONS

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 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.

301
SIMPLE SQL

The results after executing the above query are displayed in Figure 8.11.

Figure 8.11

Now, If I want to partition the dataset based on the values present in the Role col-
umn and implement the ROW_NUMBER() function, then it will start the numbering
for each partition and then end it 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];

302
CHAPTER 8 - MASTERING SQL FUNCTIONS

Below is the result of above query:

Figure 8.12

The above query will return datasets with multiple partitions over the Role col-
umn. 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
partitioned 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.

303
SIMPLE SQL

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 number of last rows 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.

Example: Creating Ranking on table values (Single Partition)


SELECT EmployeeID,EmployeeName , Role
,RANK() OVER (ORDER BY Salary DESC) AS RankBySalary
FROM [MyEcommerceDB].[dbo].[Employee];

Results:

Figure 8.13

304
CHAPTER 8 - MASTERING SQL FUNCTIONS

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 increment-
ing with +1 to the last assigned rank. Now, if you look closely in a partition, you’ll
observe that the RANK() function 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.
Let me explain how the rankings will be when we have multiple partitions.

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 EmployeeID,EmployeeName,DepartmentID ,Role


,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:

305
SIMPLE SQL

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 incremen-
tal 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.

306
CHAPTER 8 - MASTERING SQL FUNCTIONS

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.

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 #1:
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];

307
SIMPLE SQL

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.
When comparing the rank and dense rank, the difference is quite clear.
For the record with the same BirthDate (1962-09-13), The ranking is the same for
both the records. However, for the next record RANK() function assigns the ranking
as 25 (count of all the previous records plus 1 in that particular partition).
And DENSE_RANK function has assigned the ranking as 24 (last ranking number
plus 1).

308
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example #1:
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 and for the rows that have the same value for the birthdate column. The
RANKING will be the same.
And the ranking for the next record will be the last ranking number plus 1 in that
particular partition.
So, If you compare RANK() with DENSE_RANK(), you say that rank allows a gap
in the ranking it creates. At the same time, DENSE_RANK does not allow any gap in
ranking.

309
SIMPLE SQL

NTILE()
NTILE() function is also a windows function that helps in distributing data in
groups. The number 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.

310
CHAPTER 8 - MASTERING SQL FUNCTIONS

Example #1:
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 Birthdate.
The results after executing the above query are mentioned in Figure 8.17.

Figure 8.17

The entire dataset is now divided into two different datasets.

311
SIMPLE SQL

Example #2:
Distribute the query results coming from the Employee table into 4 groups.
SELECT EmployeeID,Role,DateOfBirth,
NTILE(4) OVER (ORDER BY DateOfBirth ASC) AS NTILEValue
FROM [dbo].[Employee];

Results:

Figure 8.18

312
CHAPTER 8 - MASTERING SQL FUNCTIONS

DEALING WITH NULL VALUES USING FUNCTIONS


When dealing with huge amounts of data coming from different sources, that
represents different 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)

Example:
Display FirstName and Job Title from the table Employee.
While displaying Replace all the NULL values in the Location column and replace
it with ‘_’

SELECT EmployeeName,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 function returns NULL. If it is not equal, then it returns the first expression.

313
SIMPLE SQL

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.

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’);

314
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’.

315
SIMPLE SQL

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.
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 parti-
tion of DepartmentID and Order by salary lowest to highest

21) Display FirstName, Department and Job Title from the table Employee.While
displaying Replace all the NULL values in the Department column and replace it
with ‘NA’

316
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’);

317
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

318
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];

319
SQL

CHAPTER 9

LEVELLING UP
THE GAME WITH SUBQUERIES

A fter learning about various operators, functions and playing with data, I am sure
your confidence level is up, and you’re fired up to learn some more advanced-
level stuff. Until now, we were working with a single dataset and playing with the data
present in that.
As you’re levelling 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 <<check this
again>>
c) Joins: LEFT JOIN, RIGHT JOIN, INNER JOIN and RIGHT JOIN.

This chapter is dedicated to teach you about how to combine, compare, contrast
multiple datasets using SQL subquery.

321
SIMPLE SQL

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 generat-
ing temporary values. 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.
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

322
CHAPTER 9 - LEVELLING UP THE GAME WITH SUBQUERIES

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 data set 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..);

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.

323
SIMPLE SQL

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 #1:
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 particular 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:

SELECT EmployeeID,DateOfBirth,Role
FROM [MyEcommerce].[HumanResources].[Employee]
WHERE BirthDate>’1970-12-31’

Subqueries help us in compare and contrast with 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).

324
CHAPTER 9 - LEVELLING UP THE GAME WITH SUBQUERIES

Example #2:
Employee data is present in the Employee table, and Department Data like
DepartmentID and Deparment Name is in the Department table. Both the tables
have a common column that helps link the data of two tables, which is the DeptID of
the department table. Using subqueries, display the department names of the employ-
ees 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 combining 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 dis-
playing the Department Names and IDs of those departments in the main query results.

Example #3:
Display the Department ID and the Department Name from the department table
for the employees with location as ‘Sydney.’
Approach: To display the department ID and Department Name, we need to
extract the department IDs of employees who have a location as ‘Sydney.’ Then those
department IDs can be further used to display the department name from the table
Department.

325
SIMPLE SQL

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 sub-
query, and then based on those results, the final result set was being 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 average salary using AVG() function.

326
CHAPTER 9 - LEVELLING UP THE GAME WITH SUBQUERIES

Below query can display average salary by department:

SELECT DepartmentID,AVG(Salary) AS DeptAVGSalary


FROM [MyEcommerceDB].[dbo].[Employee]
GROUP BY DepartmentID;

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 aver-
age 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 calculating the average salary by 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 sub-
queries in your SQL code.
In the upcoming chapters, You will discover the other options that will help you
work with multiple datasets.

327
SIMPLE SQL

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.

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’)

328
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 pow-
erful 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
are always a better choice. Every complex query usually uses multiple joins, and mul-
tiple joins make a query complex. (You see what I did there? )
Learning and implementing JOINS effectively 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

329
SIMPLE SQL

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.

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 dataset, First, you need to learn about the cartesian product
of relational 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, every-
thing 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 about the cartesian product with 2 sets: Person and Actions.

330
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.3

If we want the Cartesian product of the above two sets— ( ie: Persons X Actions).
it will look something like Figure 10.4

Figure 10.4

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 prod-
uct. The final outcome of this cross product is in Figure 10.5.

331
SIMPLE SQL

Figure 10.5

There Multiple Types joins in SQL to combine different datasets. In this chapter,
We will be discussing 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 combines multiple tables using the cartesian
product and then applies specific conditions based on what we want to see in the final
combined dataset.

332
CHAPTER 10 - SQL JOINS MADE EASY

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 .

333
SIMPLE SQL

Figure 10.6.a

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.

334
CHAPTER 10 - SQL JOINS MADE EASY

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;

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

ColumnName.TableAliasName.

335
SIMPLE SQL

INNER JOIN
INNER JOIN selects all the matching rows that are present in both tables. This
JOIN is dependent 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 join-
ing 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!

Figure 10.7

336
CHAPTER 10 - SQL JOINS MADE EASY

The intersection part represents the common records in the column on which we
implemented 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.

337
SIMPLE SQL

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.

338
CHAPTER 10 - SQL JOINS MADE EASY

But as per the INNER JOIN condition, only the records present in both the col-
umns PersonID ( Actions Table) and PersonID (Person’s Table) will be selected and
displayed in the outcome. (Figure 10.11 )

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 practical example:

339
SIMPLE SQL

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 com-
mon 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.
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 are displayed in Figure 10.13 .

Figure 10.13

340
CHAPTER 10 - SQL JOINS MADE EASY

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 columns 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 con-
sidered an OUTER JOIN.
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 left the tables and only the
matched records present in the right table. This JOIN is also dependent upon a com-
mon column present in both the 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;

341
SIMPLE SQL

Please check the diagram in Figure 10.14 that illustrates the LEFT join in a much
better way!

Figure 10.14

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 the tables.

Figure 10.15

342
CHAPTER 10 - SQL JOINS MADE EASY

Figure 10.16

Now, internally all the records from the first table will be multiplied with all the
records from the 2nd table using the cartesian product.

343
SIMPLE SQL

The cartesian product of the above tables is displayed in figure 10.17:

Figure 10.17

344
CHAPTER 10 - SQL JOINS MADE EASY

First, Matched records in the left and right table for the columns PersonID (
Actions Table) and PersonID(Person’s Table) will be selected and displayed in the final
outcome.
Then, As per the LEFT OUTER JOIN condition, even the unmatched records pres-
ent in the LEFT table must return in the final outcome. How it will return NULL val-
ues for all columns coming from the RIGHT table in the final outcome of the LEFT
OUTER JOIN for these unmatched records.
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 #2:
Let’s take the example of Employee and Department table again.
Suupose, 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.

345
SIMPLE SQL

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.


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

346
CHAPTER 10 - SQL JOINS MADE EASY

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;

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 with all the
records from the 2nd table using the cartesian product.

347
SIMPLE SQL

The cartesian product of the above tables is displayed in Figure 10.21.

Figure 10.21

348
CHAPTER 10 - SQL JOINS MADE EASY

First, Matched records in the left and right table for the columns PersonID (
Actions Table) and PersonID(Person’s Table) will be selected and displayed in the final
outcome.
Then, As per the RIGHT OUTER JOIN condition, even the unmatched records
present in the RIGHT table must return 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:

Figure 10.22

Example #2:
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 columns are related and will link to join both the department table
and employee table.

349
SIMPLE SQL

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:

Figure 10.23

350
CHAPTER 10 - SQL JOINS MADE EASY

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;

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.

351
SIMPLE SQL

The cartesian product of the above tables is displayed in the Figure 10.25:

Figure 10.25

352
CHAPTER 10 - SQL JOINS MADE EASY

Matched records in the LEFT and RIGHT table for the columns PersonID (
Actions Table) and PersonID(Person’s Table) will be selected and displayed in the final
outcome.
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.
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 something 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.

353
SIMPLE SQL

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
particular example, I am pulling EmployeeID ,EmployeeName From the Employee
Table and DepartmentName from the Department table.
Hence the final query after implementing the FULL OUTER JOIN will look some-
thing 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.

354
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 DepartmentName 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
relating 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.

355
SIMPLE SQL

EXERCISE
SCENARIO #1:
Author

AuthorID Name Email Country BookID


A1111 Dane [email protected] United States B3
A1112 Russell [email protected] United Kingdom NULL
A1113 Will [email protected] Canada B1
A1114 Chris [email protected] 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 AuthorName,
Email from author table and, all columns from the books table.

356
CHAPTER 10 - SQL JOINS MADE EASY

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

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.

357
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’,’[email protected]’,’United States’,’B3’),

358
CHAPTER 10 - SQL JOINS MADE EASY

(‘A1112’,’Russell’,’[email protected]’,’United Kingdom’,NULL),
(‘A1113’,’Will’,’[email protected]’,’Canada’,’B1’),
(‘A1114’,’Chris’,’[email protected]’,’United States’,’B2’)

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

359
SIMPLE SQL

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’);

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’);

360
CHAPTER 10 - SQL JOINS MADE EASY

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;

361
SQL

CHAPTER 11

SETS IN SQL

S QL is all about working with data; we play with data sets and get the desired data-
set by implementing multiple operations, joins, functions, and what not! 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 oper-
ators in SQL, mentioned below:

UNION
In SQL, The UNION operator helps combine two result sets coming from 2 differ-
ent 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!

363
SIMPLE SQL

Figure 11.1

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

364
CHAPTER 11 - SETS IN SQL

Location2 table:

Figure 11.3

SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location1]
UNION
SELECT [LocationID],[LocationName]
FROM [MyEcommerceDB].[dbo].[Location2];

Final Results:

Figure 11.4

365
SIMPLE SQL

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;

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];

366
CHAPTER 11 - SETS IN SQL

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

367
SIMPLE 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!

368
CHAPTER 11 - SETS IN 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

369
SIMPLE SQL

EXERCISE
SCENARIO #1:
Author

AuthorID Name Email Country BookID


A1111 Dane [email protected] United States B3
A1112 Russell [email protected] United Kingdom NULL
A1113 Will [email protected] Canada B1
A1114 Chris [email protected] United States B2

NewAuthor

AuthorID Name Email Country BookID


A1111 Dane [email protected] United States B3
A1117 Tedd [email protected] Canada NULL
A1115 Barney [email protected] Canada NULL
A1114 Chris [email protected] United States B2

1. After Creating the above tables in your database and inserting the records, imple-
ment the below mentioned operations on the datasets:
1) UNION
2) UNION ALL
3) INTERSECT
4) EXCEPT

370
CHAPTER 11 - SETS IN SQL

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

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, imple-
ment the below mentioned operations on the datasets:
1) UNION
2) UNION ALL
3) INTERSECT
4) EXCEPT

371
SIMPLE 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

372
CHAPTER 11 - SETS IN SQL

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

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

373
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 you about two ways by which we can increase the efficiency, security and
reusability of SQL code— 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 the combination of multiple tables data. The data that is presented
in views comes from the underlying 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 queries 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.

377
SIMPLE SQL

WHY USE VIEWS?


There are numerous reasons for using views, and some these reasons are men-
tioned 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 addi-
tion, this increases the security factor of the data because no user has direct permis-
sions to access the table data.

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 again multiple times. And you’ll not write complex SQL statements repeat-
edly 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 state-
ment, just like the way we query normal tables.

Syntax To Query A View:


SELECT Column1,Column2....Column(n) FROM ViewName;

378
CHAPTER 12 - VIEWS AND INDEXES IN SQL

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 #1:
Suppose you want to display all the information about employees in an applica-
tion, where the higher management can see the information of all employees ( to make
some internal decisions). 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.
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]
);

379
SIMPLE SQL

Run the below statement to query the above view:

SELECT * FROM EmpNoSal;

Example #2:
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
);

Run the below statement to query the above view:

SELECT * FROM EmployeeWithDepartment ;

380
CHAPTER 12 - VIEWS AND INDEXES IN SQL

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 pres-
ent 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 sys-
tem 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 view:

381
SIMPLE 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 about 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, Employee name, 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’);

382
CHAPTER 12 - VIEWS AND INDEXES IN 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 underlying table as well.

SELECT * FROM [MyEcommerceDB].[dbo].[Employee];

After executing the above query to check the results, we can see that the underly-
ing 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 operation. Let’s try to update the Employee name present in the view viewEmp-
DeptID 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’;

execute the below query to check the results in the view.

SELECT * FROM [MyEcommerceDB].[dbo].[viewEmpDeptID];

383
SIMPLE SQL

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 imple-
ment 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’;

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

384
CHAPTER 12 - VIEWS AND INDEXES IN SQL

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, view 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 sorting 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.

385
SIMPLE 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 multiple columns. When we apply indexes on multiple columns, then it is consid-
ered 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 column, 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);

386
CHAPTER 12 - VIEWS AND INDEXES IN 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 needs to be
maintained.

387
SIMPLE SQL

EXERCISE
1 ) Create a view Named vw_EmpDeptRt, that displays EmployeeID, EmployeeName,
HireDate, and Department Name 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 )

388
CHAPTER 12 - VIEWS AND INDEXES IN 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);

389
SQL

CHAPTER 13

STORED PROCEDURES,
CURSOR AND TRIGGERS

C oding is all about creating algorithms that helps in solving a problem or carrying
out some operations. As you know, SQL statements helps 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 setup some processes
and create leverage using those processes.
SQL provides many functionalities and ways we reuse and reutilise certain set of
code that it create 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 creat-
ing leverage using your SQL code.

UNDERSTANDING STORED PROCEDURES


A stored procedure is stored SQL statements based on the desired process of exe-
cution that can be used over and over again.
We can create 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.

391
SIMPLE SQL

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 performance of the execution.

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 EmployeeID, Employee Name, and Salary
of 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

392
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

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
the body of stored procedures. Then this value can be used in the SQL statements to
get the desired result we want.

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

393
SIMPLE SQL

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 then can 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:

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.

394
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

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 are printing 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 syn-
tax to call the stored procedure.

DECLARE @OutputEmp varchar(255)


EXEC SelectEmp 80000, @OutputEmp OUTPUT;
PRINT @OutputEmp;

In the above commands, we are declaring 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 80000 will then be supplied into the
stored procedure and after the execution 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.

395
SIMPLE SQL

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 flex-
ibility and the reusability factor it provides.

TRIGGERS
In SQL, 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 state-
ments 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 trig-
gered 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)

396
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

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 about 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 created, 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!

397
SIMPLE SQL

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)

398
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

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 execute 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, basi-
cally respond to DML statements like INSERT, UPDATE, and DELETE.
Unlike DDL triggers, we create DML Triggers on tables because the manipulation
of data happens in tables, right?
Now, DML triggers can be classified into two types:

399
SIMPLE SQL

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:

400
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

Figure 13.2

INSTEAD OF TRIGGERS (DML)


When we talk about INSTEAD OF triggers, The DB engine basically executes the
SQL statements 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 state-
ments (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.

401
SIMPLE SQL

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.
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 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

402
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

And when I execute the SELECT query, I can see that the record is not deleted
from the table. You can the results in the figure 13.4.

Figure 13.4

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 state-
ments to implement the changes.

403
SIMPLE SQL

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.

CURSORS
In RDBMS, most of the operations are carried out on the set of records, whether
it is combining 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 data-
set 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 is pointing 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.

404
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

STEP 1: Declare a cursor


The first step of the workflow of the SQL cursors is to Declare the name of the cur-
sor. 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.

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 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.

405
SIMPLE SQL

Syntax:
FETCH NEXT FROM CursorName

PRIOR: Prior is used to fetch the row present in the back direction.

Syntax:
FETCH PRIOR FROM CursorName

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 being involved in making all this happen. Just closing the cursor
is not enough; we need to deallocate the cursor.

Syntax:
DEALLOCATE CursorName

406
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

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 statement to fetch the next record.
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: Based on the syntax for the cursor, 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

407
SIMPLE SQL

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

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

408
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

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

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

409
SIMPLE SQL

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.

410
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.

411
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;

412
CHAPTER 13 - STORED PROCEDURES, CURSOR AND TRIGGERS

3)
CREATE TRIGGER DeleteDeptTrigger
ON Department
INSTEAD OF DELETE
AS
BEGIN
SELECT ‘Deletion Of Department Table Is Prohibited!’
AS Result;
END

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

413
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%20
Further%20reading-

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

415
SIMPLE SQL

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/

416

You might also like