0% found this document useful (0 votes)
2 views

SQL1

The document provides an overview of SQL basics, focusing on constraints and functions, including relationships, keys, and their types. It explains different types of relationships in databases, such as one-to-one, one-to-many, and many-to-many, as well as various key types like primary, candidate, and foreign keys. Additionally, it discusses the importance of constraints in maintaining data integrity within SQL tables.

Uploaded by

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

SQL1

The document provides an overview of SQL basics, focusing on constraints and functions, including relationships, keys, and their types. It explains different types of relationships in databases, such as one-to-one, one-to-many, and many-to-many, as well as various key types like primary, candidate, and foreign keys. Additionally, it discusses the importance of constraints in maintaining data integrity within SQL tables.

Uploaded by

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

SQL Basics

Constraints And Functions

Zlata Chernysh
Junior Software Engineer
Tetiana Lampiha
Software Engineer
CONFIDENTIAL | © 2021 EPAM Systems, Inc.
Recommendations

1 M U T E YO U R M I C

2 R A I S E H A N D A S K Q U E ST IO NS

3 D U R AT I O N : 3 H O U R S

4 C O FFEE BRE AK: 15 MINUT ES

5 Q & A A FT E R E A C H MO D ULE

6 T E A M S Q U E S TIO N S C H A NN EL

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 2


Z L ATA C H E R N Y S H

Junior S of tw are Engineer

• EPAM BI Lab 2020 Participant


• EPAM Career Path: Production Project -> DWBI Software
Engineer

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 3


TETIANA LAMPIHA

S of tw are Engineer

• EPAM BI Lab 2019 Participant


• EPAM Career Path: Production Project -> DWBI Software
Engineer

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 4


AGENDA
1 R E L AT I O N S H I P S

2 KEYS

3 C O N ST RA IN TS

4 W I N D O W F U N C T IO NS

5 ST R IN G F U N C TIONS

6 D AT E F U N C T I O N S

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


R ELATIONSHIPS

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Relationships

In a relational database you can connect or relate the data held in different tables. SQL databases are 'relational' as they
basically store relationships between
There are three main types of relationships: data.
• one-to-one
Relationship is a way of indicating the
• one-to-many
fact that two (sometimes one or more)
• many-to-many relations are in a logical relationship
with each other.

There are several types of relationships


which can exist between tables.

Links are organized using keys.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 7


One-to-One

splitting a table with


One to One: One table record relates to another record in another table. many columns
Isolating part of the
EmployeeID 1 FName LName table for security
reasons
1 Peter Pan
2 Jack Brown
storing short-term data
3 Katy Green that can be easily
deleted
1
Parent table Employees
EmployeeID Address InsuranceCard
1 5 av. 3456789
2 Freedom sq. 2349674
3 Times sq. 3435286
Child table Profiles

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 8


One-to-Many

One to Many: One table record relates to many records in another table tale.

1
Room Floor Name
101 1 Cuba
201 2 Bali
202 3 Panama

Parent table Rooms
EmployeeID Room Place
1 101 34
2 201 56
3 101 67

Child table Space

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 9


Many-to-Many

Additional table is
required

Many to Many: More than one table record relates to more than one record in another table.
table Rooms
1 ID can be added to additional
EmployeeID FName LName table
1 Peter Pan
2 Jack Brown
System properties can be
3 Katy Green added to additional table
∞ ∞
1
EmployeeID ProjectId Role ProjectID Description Customer
1 1 Development 1 E-commerce Spark Inc.
2 2 Analyst 2 CRM ASW style
1 2 Testing 3 Web portal Liga school
3 1 Testing table Projects

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 10


KEYS

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


KEY

Key is a relation attribute (or a set of attributes) which helps you to identify a row(tuple) in a relation(table).
It has some specific properties depending on the type of key.
Here are some reasons for using key in the DBMS system:
• Keys help you to identify any row in a table by a combination of one or more columns in that table. In a
real-world application, a table will likely contain thousands of records. Moreover, the records may be
duplicated. Keys ensure that you can uniquely identify a table record despite these challenges.
• Keys allow you to establish a relationship between tables and identify it.
• Keys help you enforce identity and integrity in the relationship.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 12


Primary Key

The primary key:


Primary Key - is a column or group of columns in a table that • identifies the table row;
uniquely identify every row in that table. • organizes relationships between tables.
Remember that in relational database theory, a table (relation) is an Rules for defining Primary key:
initially unordered set of records (tuples). • Two rows can't have the same primary key value
The single way to identify a particular record in this table is to specify • It is a must for every row to have a primary key value.
a set of values ​for one or more fields that would be unique for that • The primary key field cannot be null.
record. • The value in a primary key column can never be modified
or updated if any foreign key refers to that primary key.

StudID Pin FirstName LastName Email


1 56 Polly Pan [email protected]
2 57 Jack Brown [email protected]
primarykey 3 58 Katy Green [email protected]

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 13


Candidate Key

Candidate key is a set of attributes that uniquely identifies tuples in a table. Candidate Key is a super key with no repeated attributes. The Primary
key should be selected from the candidate keys. Every table must have at least a single candidate key. A table can have multiple candidate keys but
only a single primary key.

Properties of Candidate key:


• It must contain unique values
• Candidate key may have multiple attributes
• Must not contain null values
• It should contain minimum fields to ensure uniqueness
• Uniquely identify each record in a table

Example: in the given table Stud ID, Pin and email are candidate keys which help us to uniquely identify the student record i n the table.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 14


Alternate key

Alternate keys are a column or group of columns in a table that uniquely identify every row in that table. A table can
have multiple choices for a primary key but only one can be set as the primary key. All the keys which are not
primary key are called an Alternate Key.
In this table, StudID, Pin, Email are qualified to become a primary key. But since StudID is the primary key, Pin, Email
becomes the alternative key.

StudID Pin FirstName LastName Email


1 56 Polly Pan [email protected]
2 57 Jack Brown br@@gmail.com
3 58 Katy Green [email protected]
alternate keys

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 15


Primary, Alternate and Candidate Keys

candidate key

StudID Pin FirstName LastName Email


1 56 Polly Pan [email protected]
2 57 Jack Brown br@@gmail.com
3 58 Katy Green [email protected]

primarykey alternate key


CONFIDENTIAL | © 2021 EPAM Systems, Inc. 16
Super Key

Super key is a group of single or multiple keys which identifies Super keys: The table has following super keys. All of the
rows in a table. A Super key may have additional attributes that following sets of super key are able to uniquely identify a row of
are not needed for unique identification. the employee table.
How candidate key is different from super key? {Emp_SSN}
Candidate keys are selected from the set of super keys, the only {Emp_Number}
thing we take care while selecting candidate key is: It should not {Emp_SSN, Emp_Number}
have any redundant attribute. That’s the reason they are also {Emp_SSN, Emp_Name}
termed as minimal super key. {Emp_SSN, Emp_Number, Emp_Name}
{Emp_Number, Emp_Name}
Emp_SSN Emp_Number Emp_Name
Candidate Keys: The following two set of super keys are chosen
from the above sets as there are no redundant attributes in
9812345098​ AB05​ Shown​
these sets:
{Emp_SSN}
9876512345​ AB06​ Roslyn​ {Emp_Number}
Only these two sets are candidate keys as all other sets are
having redundant attributes that are not necessary for unique
199937890​ AB07​ James​
identification.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 17


Simple and Composite Keys

Simple key consists of single column that uniquely identifies rows in a table.
Composite key is a combination of two or more columns that uniquely identify rows in a table. The combination of
columns guarantees uniqueness, though individually uniqueness is not guaranteed. Hence, they are combined to
uniquely identify records in a table.

OrderID ProductID ProductName Quantity


0067 JP23456t Spoons 5
0067 SD2343rt Forks 30
0067 CV5657c Knives 23
composite key 0066 KH46669q Plates 77
0066 UI475585z Glasses 45
0065 SD2343rt Forks 7

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 18


Natural Primary Key

The primary key can consist of table information fields (that is, fields containing useful information about the described objects). Such primary key is
called a natural (or intelligent) key.

In practice, the use of natural keys runs into certain difficulties:


• low efficiency (size, need to duplicate in case of migration);
• cascading changes;
• inconsistency with reality (the value of the field selected as the primary key can be specified later).
Examples of natural keys:
• Passport number;
• Flight number;
• Login name; OrderID ProductID ProductName Quantity
• Vehicle registration number.
0067 JP23456t Spoons 5
0067 SD2343rt Forks 30

natural key 0067 CV5657c Knives 23

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 19


Surrogate primary key

Surrogate key is an artificial key which aims to uniquely identify each record. This kind of partial key in DBMS is unique because it is created when
you don't have any natural primary key. They do not lend any meaning to the data in the table. Surrogate key is usually an in teger. A surrogate key is
a value generated right before the record is inserted into a table.
Example below shows shift timings of the different employee. In this example, a surrogate key is needed to uniquely identify each employee.

ID FName LName Start End


1 Polly Lawrence 12:00 13:00
2 Morgan Milles 14:00 15:00
3 Amber Tran 10:00 12:00
4 Isobel Cooper 18:00 19:00

surrogate key

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 20


Natural VS Surrogate Keys

Problems with PK "Passport": Advantages of PK “ID":


• Big size. • Small size.
• Requires cascading changes. • Does not require cascading changes.
• Impossible to insert data in case of • You can insert data even if some information
information absence. is missing.

City Passport LastName City

New York 123456 Smith New York


Los 145678 Johnson Los
Angeles Angeles
Chicago 123908 Williams Chicago
Houston 124567 Brown Chicago
natural key natural key

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 21


Natural VS Surrogate Keys

Problems with PK "Passport": Advantages of PK “ID":


• Big size. • Small size.
• Requires cascading changes. • Does not require cascading changes.
• Impossible to insert data in case of • You can insert data even if some information
information absence. is missing.

CityID Name Passport LastName CityID


1 New York 123456 Smith 1
2 Los Angeles 145678 Johnson 2
3 Chicago 123908 Williams 3
4 Houston 124567 Brown 3

surrogate key surrogate key

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 22


Foreign Key

Foreign key is a column that creates a relationship between two tables. The purpose of Foreign keys is to maintain data integrity and allow
navigation between two different instances of an entity. It acts as a cross-reference between two tables as it references the primary key of
another table.

Parent table Departments

Child table Teachers

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


CONFIDENTIAL 23
Primary VS Foreign Keys

Primary: Foreign:
• Helps you to uniquely identify a record in the • It is a field in the table that is the primary key
table. of another table.
• Primary Key never accepts null values. • A foreign key may accept multiple null values.
• Primary key is a clustered index and data in • A foreign key cannot automatically create an
the DBMS table are physically organized in the index, clustered or non-clustered. However,
sequence of the clustered index. you can manually create an index on the
• You can have a single Primary key in a table. foreign key.
• You can have multiple foreign keys in a table.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 24


Recursive Foreign Key

Recursive foreign key is a foreign key which refers back to the primary key in the same table.

Parent and child table Employees

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


CONFIDENTIAL 25
CONSTRAINTS

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Constraints

SQL constraints are used to specify rules for data in a table.


Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER
TABLE statement.
Syntax (CREATE TABLE):
CREATE TABLE table_name
(
column_name int NOT NULL,
CONSTRAINT constraint_name UNIQUE(column_name)
);
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If
there is any violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level constraints apply to the whole
table.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 27


Constrains

The following constraints are commonly used in SQL:


• NOT NULL- Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column when no value is specified
• INDEX - Used to create and retrieve data from the database very quickly

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 28


NOT NULL Constraint

By default, a column can hold NULL values.

The NOT NULL constraint enforces a column to NOT accept NULL values.

This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL values when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use the following SQL:

ALTER TABLE Persons


ALTER COLUMN Age int NOT NULL;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 29


UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different. To name a UNIQUE constraint, and to define a UNIQUE constraint on
multiple columns, use the following SQL syntax:
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns. CREATE TABLE Persons (
A PRIMARY KEY constraint automatically has a UNIQUE constraint. ID int NOT NULL,
LastName varchar(255) NOT NULL,
However, you can have many UNIQUE constraints per table, but only one
FirstName varchar(255),
PRIMARY KEY constraint per table.
Age int,
The following SQL creates a UNIQUE constraint on the "ID" column when
CONSTRAINT UC_Person UNIQUE (ID,LastName)
the "Persons" table is created:
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE(ID)
);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 30


UNIQUE Constraint

To create a UNIQUE constraint on the "ID" column when the To drop a UNIQUE constraint, use the following SQL:
table is already created, use the following SQL:
ALTER TABLE Persons
ALTER TABLE Persons DROP CONSTRAINT UC_Person;
ADD UNIQUE (ID);
To name a UNIQUE constraint, and to define a UNIQUE
constraint on multiple columns, use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 31


PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table. To allow naming of a PRIMARY KEY constraint, and for defining a
PRIMARY KEY constraint on multiple columns, use the following SQL
Primary keys must contain UNIQUE values and cannot contain NULL
syntax:
values.
CREATE TABLE Persons (
A table can have only ONE primary key; and in the table, this primary key
can consist of single or multiple columns (fields). ID int NOT NULL,
LastName varchar(255) NOT NULL,
The following SQL creates a PRIMARY KEY on the "ID" column when the
FirstName varchar(255),
"Persons" table is created:
Age int,
CREATE TABLE Persons (
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
ID int NOT NULL,
);
LastName varchar(255) NOT NULL,
Note: In the example above there is only ONE PRIMARY KEY (PK_Person).
FirstName varchar(255),
However, the VALUE of the primary key is made up of TWO COLUMNS (ID
Age int, + LastName).
PRIMARY KEY (ID)
);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 32


PRIMARY KEY Constraint

To create a PRIMARY KEY constraint on the "ID" column when the Note: If you use the ALTER TABLE statement to add a primary
table is already created, use the following SQL: key, the primary key column(s) must already have been declared
to not contain NULL values (when the table was first created).
ALTER TABLE Persons
ADD PRIMARY KEY (ID); To drop a PRIMARY KEY constraint, use the following SQL:
To allow naming of a PRIMARY KEY constraint, and for defining a ALTER TABLE Persons
PRIMARY KEY constraint on multiple columns, use the following SQL DROP CONSTRAINT PK_Person;
syntax:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 33


FOREIGN KEY Constraint

A FOREIGN KEY is a key used to link two tables together.


A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or
parent table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the
values contained in the table it points to.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 34


FOREIGN KEY Constraint

The following SQL creates a FOREIGN KEY on the "PersonID" To allow naming of a FOREIGN KEY constraint, and for defining a
column when the "Orders" table is created: FOREIGN KEY constraint on multiple columns, use the following
SQL syntax:
CREATE TABLE MyOrders (
OrderID int NOT NULL, CREATE TABLE MyOrders (

OrderNumber int NOT NULL, OrderID int NOT NULL,


PersonID int, OrderNumber int NOT NULL,
PRIMARY KEY (OrderID), PersonID int,
FOREIGN KEY (PersonID) REFERENCES Persons(ID) PRIMARY KEY (OrderID),

); CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)


REFERENCES Persons(ID)
);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 35


Database Schema

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 36


FOREIGN KEY Constraint

To create a FOREIGN KEY constraint on the "PersonID" column To drop a FOREIGN KEY constraint, use the following SQL:
when the "Orders" table is already created, use the following
ALTER TABLE MyOrders
SQL:
DROP CONSTRAINT FK_PersonOrder;
ALTER TABLE MyOrders
ADD FOREIGN KEY (PersonID)
REFERENCES Persons(ID);
To allow naming of a FOREIGN KEY constraint, and for defining a
FOREIGN KEY constraint on multiple columns, use the following
SQL syntax:

ALTER TABLE MyOrders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(ID);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 37


CHECK Constraint

The CHECK constraint is used to limit the value range that can be To allow naming of a CHECK constraint, and for defining
placed in a column. a CHECK constraint on multiple columns, use the following SQL
If you define a CHECK constraint on a column it will allow only syntax:
certain values for this column.
CREATE TABLE Persons (
If you define a CHECK constraint on a table it can limit the values ID int NOT NULL,
in certain columns based on values in other columns in the row. LastName varchar(255) NOT NULL,
FirstName varchar(255),
The following SQL creates a CHECK constraint on the "Age" Age int,
column when the "Persons" table is created. City varchar(255),
The CHECK constraint ensures that the age of a person must be CONSTRAINT CHK_Person CHECK (Age>=18 AND City='
18, or older: Sandnes')
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 38


CHECK Constraint

To create a CHECK constraint on the "Age" column when the To drop a CHECK constraint, use the following SQL:
table is already created, use the following SQL:
ALTER TABLE Persons
ALTER TABLE Persons DROP CONSTRAINT CHK_PersonAge;
ADD CHECK (Age>=18);
To allow naming of a CHECK constraint, and for defining
a CHECK constraint on multiple columns, use the following SQL
syntax:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND
City='Sandnes');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 39


DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a


column.
The default value will be added to all new records, if no other
value is specified.
The following SQL sets a DEFAULT value for the "City" column
when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 40


DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a The DEFAULT constraint can also be used to insert system
column. values, by using functions like GETDATE():
The default value will be added to all new records, if no other CREATE TABLE Orders (
value is specified. ID int NOT NULL,
The following SQL sets a DEFAULT value for the "City" column OrderNumber int NOT NULL,
when the "Persons" table is created: OrderDate date DEFAULT GETDATE()
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 41


DEFAULT Constraint

To create a DEFAULT constraint on the "City" column when the To drop a DEFAULT constraint, use the following SQL:
table is already created, use the following SQL:
ALTER TABLE Persons
ALTER TABLE Persons DROP CONSTRAINT df_City;
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 42


AUTO INCREMENT

Auto-increment allows a unique number to be generated


automatically when a new record is inserted into a table.
Often this is the primary key field that we would like to be
created automatically every time a new record is inserted.
The following SQL statement defines the "Personid" column to
be an auto-increment primary key field in the "Persons" table:
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
ONLY ONE IDENTITY COLUMN PER TABLE IS ALLOWED!

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 43


AUTO INCREMENT

Auto-increment allows a unique number to be generated The MS SQL Server uses the IDENTITY keyword to perform an
automatically when a new record is inserted into a table. auto-increment feature.

Often this is the primary key field that we would like to be In the example above, the starting value for IDENTITY is 1, and it
will increment by 1 for each new record.
created automatically every time a new record is inserted.
Tip: To specify that the "Personid" column should start at value
The following SQL statement defines the "Personid" column to 10 and increment by 5, change it to IDENTITY(10,5).
be an auto-increment primary key field in the "Persons" table:
To insert a new record into the "Persons" table, we will NOT
CREATE TABLE Persons ( have to specify a value for the "Personid" column (a unique
Personid int IDENTITY(1,1) PRIMARY KEY, value will be added automatically):
LastName varchar(255) NOT NULL,
FirstName varchar(255), INSERT INTO Persons (FirstName,LastName)
Age int VALUES ('Lars','Monsen’);
);
The SQL statement above would insert a new record into the
ONLY ONE IDENTITY COLUMN PER TABLE IS ALLOWED!
"Persons" table. The "Personid" column would be assigned a
unique value. The "FirstName" column would be set to "Lars"
and the "LastName" column would be set to "Monsen".

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 44


WINDOW FUNCTIONS

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Window Functions Introduction

Window functions operate on a set of rows and return a single value for each row from the underlying query. The term window describes the set of
rows on which the function operates. A window function uses values from the rows in a window to calculate the returned values.

When you use a window function in a query, define the window using the OVER() clause.
The OVER() clause (window definition) differentiates window functions from other analytical and reporting functions. A query can include multiple
window functions with the same or different window definitions.

The OVER() clause has the following capabilities:


• Defines window partitions to form groups of rows (PARTITION BY clause).
• Orders rows within a partition (ORDER BY clause).

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 46


Window Functions Syntax

window_function ( [ ALL ] expression )


OVER ( [ PARTITION BY partition_list ] [ ORDER BY order_list] )

Arguments:
window_function - specify the name of the window function
ALL - ALL is an optional keyword. When you will include ALL it will count all values including duplicate ones. DISTINCT is not supported in window functions
expression - the target column or expression that the functions operates on. In other words, the name of the column for which we need an aggregated
value. For example, a column containing order amount so that we can see total orders received.
OVER specifies the window clauses for aggregate functions.
PARTITION BY partition_list Defines the window (set of rows on which window function operates) for window functions. We need to provide a field or list
of fields for the partition after PARTITION BY clause. Multiple fields need be separated by a comma as usual. If PARTITION BY is not specified, grouping will
be done on entire table and values will be aggregated accordingly.
ORDER BY order_list sorts the rows within each partition. If ORDER BY is not specified, ORDER BY uses the entire table.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 47


Window Functions Syntax. OVER()
SELECT
Date
, Medium
, Conversions
, SUM(Conversions) OVER() AS 'Sum'
FROM Orders

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 48


Window Functions Syntax. PARTITION BY

SELECT

Date

, Medium

, Conversions

, SUM(Conversions) OVER(PARTITION BY Date) AS 'Sum'

FROM Orders

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 49


Window Functions Syntax. ORDER BY
SELECT
Date
, Medium
, Conversions
, SUM(Conversions) OVER(PARTITION BY Date ORDER BY Medium) AS
'Sum'
FROM Orders

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 50


Window Functions Syntax. ROWS/RANGE

The ROWS clause limits the rows within a partition by specifying a fixed SELECT
number of rows preceding or following the current row. Date
, Medium​
The RANGE clause logically limits the rows within a partition by specifying
, Conversions​
a range of values with respect to the value in the current row.
, SUM(Conversions) OVER(PARTITION BY Date
Preceding and following rows are defined based on the ordering in the ORDER BY Conversions
ORDER BY clause. ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) AS 'Sum'
The window frame "RANGE ... CURRENT ROW ..." includes all rows that FROM Orders
have the same values in the ORDER BY expression as the current row.

UNBOUNDED PRECEDING - Specifies that the window starts at the first


row of the partition.
CURRENT ROW - Specifies that the window starts or ends at the current
row when used with ROWS or the current value when used with RANGE.
CURRENT ROW can be specified as both a starting and ending point.
BETWEEN ... AND - Used with either ROWS or RANGE to specify the lower
(starting) and upper (ending) boundary points of the window.
UNBOUNDED FOLLOWING - Specifies that the window ends at the last row
of the partition. UNBOUNDED FOLLOWING can only be specified as a
window end point.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 51


Types of Window Functions

Aggregate Window Functions:​ Value Window Functions:​


• MAX();​ • LAG();​
• MIN();​ • LEAD();​
• SUM();​ • FIRST_VALUE();​
• AVG();​ • LAST_VALUE();​
• COUNT();​ • CUME_DIST().​
Ranking Window Functions:​
• RANK();​
• DENSE_RANK();​
• ROW_NUMBER();​
• NTILE();​

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 52


Aggregate Window Functions
Window Function Description Example

AVG() The AVG window function returns the average value for the input SELECT SalesOrderID, ProductID, OrderQty,
expression values. The AVG function works with numeric values AVG(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Avg“
and ignores NULL values. FROM Sales.SalesOrderDetail

COUNT() The COUNT() window function counts the number of input rows. SELECT SalesOrderID, ProductID, OrderQty,
COUNT(expression) computes the number of rows with non- COUNT(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Count“
NULL values in a specific column or expression. FROM Sales.SalesOrderDetail

MAX() The MAX() window function returns the maximum value of the SELECT SalesOrderID, ProductID, OrderQty,
expression across all input values. The MAX function works with MAX(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Max"
numeric values and ignores NULL values. FROM Sales.SalesOrderDetail

MIN() The MIN () window function returns the minimum value of the SELECT SalesOrderID, ProductID, OrderQty,
expression across all input values. The MIN function works with MIN(OrderQty) OVER(PARTITION BY SalesOrderID) AS "Min“
numeric values and ignores NULL values. FROM Sales.SalesOrderDetail

SUM() The SUM () window function returns the sum of specified field for SELECT SalesOrderID, ProductID, OrderQty,
specified or for the entire table if group is not specified. The SUM SUM(OrderQty) OVER(PARTITION BY SalesOrderID) AS Total
function works with numeric values and ignores NULL values. FROM Sales.SalesOrderDetail

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 53


Ranking Window Functions. ROW_NUMBER()

RANKING functions will rank the values of a specified field and categorize them according to their rank.

ROW_NUMBER() - assign a unique sequential integer to rows within a partition of a result set or a only result set, the first row starts from 1.
Syntax:
ROW_NUMBER ( )
OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )
Return types: BIGINT
NOTE:
THERE IS NO GUARANTEE THAT THE ROWS RETURNED BY A QUERY USING ROW_NUMBER() WILL BE ORDERED EXACTLY THE SAME WITH
EACH EXECUTION UNLESS THE FOLLOWING CONDITIONS ARE TRUE.
• VALUES OF THE PARTITIONED COLUMN ARE UNIQUE.
• VALUES OF THE ORDER BY COLUMNS ARE UNIQUE.
• COMBINATIONS OF VALUES OF THE PARTITION COLUMN AND ORDER BY COLUMNS ARE UNIQUE.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 54


ROW_NUMBER() examples
ROW_NUMBER() example: The following example uses the PARTITION BY argument to partition the query
result set by the column TerritoryName.
The following example calculates a row number for the salespeople in
Adventure Works Cycles based on their year-to-date sales ranking. SELECT FirstName, LastName, TerritoryName,
SELECT ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row, ROUND(SalesYTD,2,1) AS SalesYTD,
FirstName, LastName, ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY
ROUND(SalesYTD,2,1) AS "Sales YTD" SalesYTD DESC) AS Row
FROM Sales.vSalesPerson FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0

ORDER BY TerritoryName;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 55


Ranking Window Functions. RANK()

The RANK() function is used to give a unique rank to each record based on a specified value, for example salary, order amount etc.
If two or more rows tie for a rank, each tied row receives the same rank.
The sort order that is used for the whole query determines the order in which the rows appear in a result set.
ROW_NUMBER and RANK are similar. ROW_NUMBER numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK provides the same
numeric value for ties (for example 1, 2, 2, 4, 5).
Syntax:
RANK ( ) OVER ( [ partition_by_clause ] order_by_clause )
Return types: BIGINT

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 56


RANK() example

The following example ranks the products in inventory the


specified inventory locations according to their quantities. The
result set is partitioned by LocationID and logically ordered by
Quantity.
SELECT i.ProductID, p.Name, i.LocationID, i.Quantity,
RANK() OVER (PARTITION BY i.LocationID ORDER BY
i.Quantity DESC) AS Rank
FROM Production.ProductInventory AS i
INNER JOIN Production.Product AS p
ON i.ProductID = p.ProductID
WHERE i.LocationID BETWEEN 3 AND 4
ORDER BY i.LocationID;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 57


Ranking Window Functions. DENSE_RANK()

DENSE_RANK() function returns the rank of each row within a result set partition, with no gaps in the ranking values. The rank of a specific
row is one plus the number of distinct rank values that come before that specific row.
If two or more rows have the same rank value in the same partition, each of those rows will receive the same rank.
The sort order used for the whole query determines the order of the rows in the result set. This implies that a row ranked number one
does not have to be the first row in the partition.
Syntax:
DENSE_RANK ( ) OVER ( [ <partition_by_clause> ] < order_by_clause > )
Return types: BIGINT

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 58


DENSE_RANK() example

This example ranks the products in inventory, by the specified inventory


locations, according to their quantities.

DENSE_RANK partitions the result set by LocationID and logically orders


the result set by Quantity.
SELECT i.ProductID, p.Name, i.LocationID, i.Quantity

,DENSE_RANK() OVER

(PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS Rank


FROM Production.ProductInventory AS i

INNER JOIN Production.Product AS p

ON i.ProductID = p.ProductID
WHERE i.LocationID BETWEEN 3 AND 4

ORDER BY i.LocationID;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 59


Ranking Window Functions. NTILE()

NTILE() distributes the rows in an ordered partition into a specified number of groups. The groups are numbered, starting at one. For each
row, NTILE returns the number of the group to which the row belongs.
If the number of rows in a partition is not divisible by integer_expression, this will cause groups of two sizes that differ by one member.
Larger groups come before smaller groups in the order specified by the OVER clause.
Syntax:
NTILE (integer_expression) OVER ( [ <partition_by_clause> ]
< order_by_clause > )
Return types: BIGINT

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 60


NTILE() example

The following example divides rows into four groups of employees based
on their year-to-date sales. Because the total number of rows is not
divisible by the number of groups, the first two groups have four rows and
the remaining groups have three rows each.

SELECT p.FirstName, p.LastName

,NTILE(4) OVER(ORDER BY SalesYTD DESC) AS Quartile

,CONVERT(NVARCHAR(20),s.SalesYTD,1) AS SalesYTD

,a.PostalCode

FROM Sales.SalesPerson AS s

INNER JOIN Person.Person AS p

ON s.BusinessEntityID = p.BusinessEntityID

INNER JOIN Person.Address AS a

ON a.AddressID = p.BusinessEntityID

WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 61


Value Window Functions. FIRST_VALUE()

Value window functions are used to find first, last, previous and next The following example uses FIRST_VALUE to return the name of the
values. The functions that can be used are LAG(), LEAD(), FIRST_VALUE(), product that is the least expensive in a given product category.
LAST_VALUE()
SELECT Name, ListPrice,

FIRST_VALUE(Name) OVER (ORDER BY ListPrice ASC) AS


FIRST_VALUE() helps you to identify first record within a partition or LeastExpensive
entire table if PARTITION BY is not specified.
FROM Production.Product
Syntax:
WHERE ProductSubcategoryID = 37;
FIRST_VALUE ( [scalar_expression ] )
[ IGNORE NULLS | RESPECT NULLS ] OVER ( [ partition_by_clause ]
order_by_clause [ rows_range_clause ] )

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 62


Value Window Functions. LAST_VALUE()

LAST_VALUE() helps you to identify last record within a partition or entire The following example returns the hire date of the last employee in each
table if PARTITION BY is not specified. department for the given salary (Rate).

Syntax: SELECT Department, LastName, Rate, HireDate,


LAST_VALUE ( [ scalar_expression ] ) [ IGNORE NULLS | RESPECT NULLS ] LAST_VALUE(HireDate) OVER (PARTITION BY Department ORDER BY
OVER ( [ partition_by_clause ] order_by_clause rows_range_clause ) Rate) AS LastValue

FROM HumanResources.vEmployeeDepartmentHistory AS edh

INNER JOIN HumanResources.EmployeePayHistory AS eph


ON eph.BusinessEntityID = edh.BusinessEntityID

INNER JOIN HumanResources.Employee AS e

ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN (N'Information Services',N'Document Control');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 63


Value Window Functions. LAG()

The LAG() window function returns the value for the row before the The following example uses the LAG function to return the difference
current row in a partition. If no row exists, null is returned. in sales quotas for a specific employee over previous years.
The LAG function allows to access data from the previous row in the SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS
same result set without use of any SQL joins. CurrentQuota,
Syntax: LAG(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS
PreviousQuota
LAG (scalar_expression [,offset] [,default])
FROM Sales.SalesPersonQuotaHistory
OVER ( [ partition_by_clause ] order_by_clause )
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2011','2012');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 64


Value Window Functions. LEAD()

LEAD function allows to access data from the next row in the same The query uses the LEAD function to return the difference in sales quotas
result set without use of any SQL joins. for a specific employee over subsequent years.

Syntax: SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS


CurrentQuota,
LEAD ( scalar_expression [ ,offset ] , [ default ] )
LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS
OVER ( [ partition_by_clause ] order_by_clause )
NextQuota

FROM Sales.SalesPersonQuotaHistory

WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2011','2012');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 65


DATE AND TIME FUNCTIONS

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 66


GETDATE() Function

GETDATE() - returns the current date along with time.


Syntax:
GETDATE()
The following query will return the current date along with time in MS SQL Server:
SELECT GETDATE() AS CURRENTDATETIME

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 67


DATEPART() Function

datepart Abbreviations
DATEPART() - returns the part of date or time. year yy, yyyy
quarter qq, q
Syntax:
month mm, m
DATEPART(datepart, datecolumnname) dayofyear dy, y
The following query will return the part of current date in MS SQL Server: day dd, d
SELECT DATEPART(DAY, GETDATE()) AS CURRENTDATE week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns
tzoffset tz
iso_week isowk, isoww

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 68


DATEADD() Function

DATEADD() – displays the date and time by adding or subtracting date and time interval.
Syntax:
DATEADD(datepart, number, datecolumnname)
The following query will return the date and time 10 days from the current date and time in MS SQL Server.
Example:
SELECT DATEADD(DAY, 10, GETDATE()) AS TENDAYSLATER

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 69


DATEDIFF() Function

DATEDIFF() - displays the date and time between two dates.


Syntax:
DATEDIFF(datepart, startdate, enddate)
The following query will return the difference in hours between 2020-12-01 and 2020-12-07 dates in MS SQL Server.
Example:
SELECT DATEDIFF(HOUR, 2020-12-01, 2020-12-07) AS HOURSDIFF

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 70


CONVERT() Function

N O T E : C O N V E R T ( ) F U N C T I O N C O N V E R T S E X P R E S S I O N T O D A TA T Y P E A C C O R D I N G T O S T Y L E .
E X P R E S S I O N A N D D A TA T Y P E I N C L U D E B U T A R E N O T L I M I T E D T O D A T E A N D T I M E F O R M A T S !
CONVERT() - displays the date and time in different formats.

Syntax:
CONVERT(datatype, expression, style)

The following queries will return the date and time in different format in MS SQL Server:
SELECT CONVERT(VARCHAR(19),GETDATE())
SELECT CONVERT(VARCHAR(10),GETDATE(),10)
SELECT CONVERT(VARCHAR(10),GETDATE(),110)

SQL Server Data Type Conversion Chart

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 71


Date and Time Functions
Date and Time Functions (Transact-SQL)

• Functions That Return System Date and Time Values;


• Functions That Return Date and Time Parts;
• Functions That Return Date and Time Values from Their Parts;
• Functions That Return Date and Time Difference Values;
• Functions That Modify Date and Time Values;
• Functions That Set or Return Session Format;
• Functions That Validate Date and Time Values.

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 72


Functions That Return System Date and Time Values
Transact-SQL derives all system date and time values from the operating system of the computer on which the instance of SQL Server runs.

Function Syntax Return value Return data type


SYSDATETIME SYSDATETIME () Returns a datetime2(7) value containing the date datetime2(7)
and time of the computer on which the instance
of SQL Server runs. The returned value does not
include the time zone offset.

SYSDATETIMEOFFSET SYSDATETIMEOFFSET ( ) Returns a datetimeoffset(7) value containing the datetimeoffset(7)


date and time of the computer on which the
instance of SQL Server runs. The returned value
includes the time zone offset.

SYSUTCDATETIME SYSUTCDATETIME ( ) Returns a datetime2(7) value containing the date datetime2(7)


and time of the computer on which the instance
of SQL Server is running. The function returns the
date and time values as UTC time (Coordinated
Universal Time).

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 73


Functions That Return System Date and Time Values

Function Syntax Return value Return data type


CURRENT_TIMESTAMP CURRENT_TIMESTAMP Returns a datetime value containing the date and datetime
time of the computer on which the instance
of SQL Server runs. The returned value does not
include the time zone offset.

GETDATE GETDATE ( ) Returns a datetime value containing the date and datetime
time of the computer on which the instance
of SQL Server runs. The returned value does not
include the time zone offset.

GETUTCDATE GETUTCDATE ( ) Returns a datetime value containing the date and datetime
time of the computer on which the instance
of SQL Server runs. The function returns the date
and time values as UTC time (Coordinated
Universal Time).

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Functions That Return Date and Time Parts

Function Syntax Return value Return data type


DATENAME DATENAME ( datepart , date ) Returns a character string representing the nvarchar
specified datepart of the specified date.

DATEPART DATEPART ( datepart , date ) Returns an integer representing the int


specified datepart of the specified date.

DAY DAY ( date ) Returns an integer representing the day part of int
the specified date.

MONTH MONTH ( date ) Returns an integer representing the month part int
of a specified date.

YEAR YEAR ( date ) Returns an integer representing the year part int
of a specified date.

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Functions That Return Date and Time Values from Their Parts

Function Syntax Return value Return data type


DATEFROMPARTS DATEFROMPARTS Returns a date value for the specified date
( year, month, day ) year, month, and day.
DATETIME2FROMPARTS DATETIME2FROMPARTS Returns a datetime2 value for the datetime2(precision)
( year, month, day, hour, minut specified date and time, with the
e, seconds, fractions, precision) specified precision.
DATETIMEFROMPARTS DATETIMEFROMPARTS Returns a datetime value for the datetime
( year, month, day, hour, minut specified date and time.
e, seconds, milliseconds)
DATETIMEOFFSETFROMPARTS DATETIMEOFFSETFROMPARTS Returns a datetimeoffset value for the datetimeoffset(precision)
( year, month, day, hour, minut specified date and time, with the
e, seconds, fractions, hour_offs specified offsets and precision.
et, minute_offset, precision)
SMALLDATETIMEFROMPARTS SMALLDATETIMEFROMPARTS Returns a smalldatetime value for the smalldatetime
( year, month, day, hour, minut specified date and time.
e)
TIMEFROMPARTS TIMEFROMPARTS Returns a time value for the specified time(precision)
( hour, minute, seconds, fractio time, with the specified precision.
ns, precision )

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Functions That Return Date and Time Difference Values

Function Syntax Return value Return data type


DATEDIFF DATEDIFF Returns the number of int
( datepart , startdate , date or
enddate ) time datepart boundari
es, crossed between
two specified dates.

DATEDIFF_BIG DATEDIFF_BIG Returns the number of bigint


( datepart , startdate , date or
enddate ) time datepart boundari
es, crossed between
two specified dates.

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Functions That Modify Date and Time Values

Function Syntax Return value Return data type


DATEADD DATEADD Returns a new datetime value by adding The data type of
(datepart , number , date ) an interval to the specified datepart of the the date argument
specified date.

EOMONTH EOMONTH Returns the last day of the month Return type is the type of
( start_date [, month_to_add ] ) containing the specified date, with an the start_date argument, or
optional offset. alternately, the date data
type.
SWITCHOFFSET SWITCHOFFSET SWITCHOFFSET changes the time zone datetimeoffset with the
(DATETIMEOFFSET , time_zone) offset of a DATETIMEOFFSET value, and fractional precision of
preserves the UTC value. the DATETIMEOFFSET
TODATETIMEOFFSET TODATETIMEOFFSET TODATETIMEOFFSET transforms a datetimeoffset with the
(expression , time_zone) datetime2 value into a datetimeoffset fractional precision of
value. TODATETIMEOFFSET interprets the the datetime argument
datetime2 value in local time, for the
specified time_zone.

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Functions That Set or Return Session Format Functions

Function Syntax Return value Return data type


@@DATEFIRST @@DATEFIRST Returns the current value, for the session, of SET DATEFIRST. tinyint

SET DATEFIRST SET DATEFIRST Sets the first day of the week to a number from 1 through 7. Not applicable
{ number | @number_var }
SET DATEFORMAT SET DATEFORMAT Sets the order of the dateparts (month/day/year) for Not applicable
{ format | @format_var } entering datetime or smalldatetime data.
@@LANGUAGE @@LANGUAGE Returns the name of the language in current Not applicable
used. @@LANGUAGE is not a date or time
function. However, the language setting can affect the
output of date functions.
SET LANGUAGE SET LANGUAGE { [ N Sets the language environment for the session and system Not applicable
] 'language' | @language_var } messages. SET LANGUAGE is not a date or time
function. However, the language setting affects the output
of date functions.
sp_helplanguage sp_helplanguage [ Returns information about date formats of all supported Not applicable
[ @language = ] 'language' ] languages. sp_helplanguage is not a date or time stored
procedure. However, the language setting affects the output
of date functions.

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


Functions That Validate Date and Time Values

Function Syntax Return value Return data type Determinism

ISDATE ISDATE ( expression ) Determines whether int ISDATE is


a datetime or smallda deterministic only
tetime input used with the
expression has a valid CONVERT function,
date or time value. when the CONVERT
style parameter is
specified, and when
style is not equal to 0,
100, 9, or 109.

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


STRING FUNCTIONS

CONFIDENTIAL | © 2021 EPAM Systems, Inc.


CHAR() Function

The CHAR() function returns the character based on the ASCII code.

Syntax:
CHAR(code)
Parameter is required (it is the ASCII number code to return the character)

Example:
Return the character based on the number code 65:
SELECT CHAR(65) AS CodeToCharacter;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 82


CONCAT() Function

The CONCAT() function adds two or more strings together.

Syntax:
CONCAT(string1, string2, ...., string_n)
Parameter is required (Parameters are the strings which will be concatenated)

Example:
Add two strings together:
SELECT CONCAT('EPAM', '.com');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 83


LEFT()

The LEFT() function extracts a number of characters from a string (starting from left).

Syntax:
LEFT(string, number_of_chars)
Parameter and string is required (The string to extract from and the number of characters to extract)

Example:
Extract 3 characters from a string (starting from left):
SELECT LEFT('SQL Lesson', 3) AS ExtractString;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 84


LEN()

The LEN() function returns the length of a string.

Syntax:
LEN(string)
Parameter is required (The string to return the length for. If string is NULL, it returns NULL)

Example:
Return the length of a string:
SELECT LEN('EPAM.com');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 85


REPLACE()

The REPLACE() function replaces all occurrences of a substring within a string with a new substring.

Syntax:
REPLACE(string, old_string, new_string)
Parameters are required

Example:
Replace "T" with "M":
SELECT REPLACE('SQL Tutorial', 'T', 'M');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 86


REVERSE()

The REVERSE() function reverses a string and returns the result.

Syntax:
REVERSE(string)
Parameter is required (The string to reverse)

Example:
Reverse a string:
SELECT REVERSE('SQL Tutorial');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 87


TRIM()

The TRIM() function removes the space characters OR other specified characters from the start or end of a string.

Syntax:
TRIM([characters FROM ]string)

Examples:
Remove leading and trailing spaces from a string:
SELECT TRIM(' SQL Tutorial! ') AS TrimmedString;

Remove characters and spaces from a string:


SELECT TRIM('#! ' FROM ' #SQL Tutorial! ') AS TrimmedString;

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 88


UPPER()

The UPPER() function converts a string to upper-case.


Note: Also there is LOWER() function, which converts a string to lower-case!

Syntax:
UPPER(text)
Parameter is required (The string to convert)

Example:
Convert the text to upper-case:
SELECT UPPER('SQL lesson is FUN!');

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 89


STUFF()

The STUFF() function deletes a part of a string and then inserts another Parameter Description
part into the string, starting at a specified position.
Syntax: string Required. The string to be modified
STUFF(string, start, length, new_string)
start Required. The position in string to
start to delete some characters
Example:
Delete 1 character from a string, starting in position 13, and then insert
length Required. The number of characters
" is fun!" in position 13: to delete from string
SELECT STUFF('SQL Tutorial!', 13, 1, ' is fun!');
new_string Required. The new string to insert
into string at the start position

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 90


THANKS FOR ATTENDING!
QUESTIONS?

CONFIDENTIAL | © 2021 EPAM Systems, Inc. 91

You might also like