SQL1
SQL1
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
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
S of tw are Engineer
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
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.
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
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
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.
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.
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.
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.
candidate 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.
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.
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.
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.
surrogate 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.
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.
Recursive foreign key is a foreign key which refers back to the primary key in the same table.
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:
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)
);
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);
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)
);
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);
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 (
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:
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)
);
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');
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'
);
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;
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".
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.
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.
SELECT
Date
, Medium
, Conversions
FROM Orders
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.
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
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.
ORDER BY TerritoryName;
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
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
,DENSE_RANK() OVER
ON i.ProductID = p.ProductID
WHERE i.LocationID BETWEEN 3 AND 4
ORDER BY i.LocationID;
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
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.
,CONVERT(NVARCHAR(20),s.SalesYTD,1) AS SalesYTD
,a.PostalCode
FROM Sales.SalesPerson AS s
ON s.BusinessEntityID = p.BusinessEntityID
ON a.AddressID = p.BusinessEntityID
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,
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).
ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN (N'Information Services',N'Document Control');
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');
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.
FROM Sales.SalesPersonQuotaHistory
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
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
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)
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).
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.
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.
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.
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;
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');
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;
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');
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');
Syntax:
REVERSE(string)
Parameter is required (The string to reverse)
Example:
Reverse a string:
SELECT REVERSE('SQL Tutorial');
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;
Syntax:
UPPER(text)
Parameter is required (The string to convert)
Example:
Convert the text to upper-case:
SELECT UPPER('SQL lesson is FUN!');
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