LAB 05 Common Functions in Mysql: Main Contents
LAB 05 Common Functions in Mysql: Main Contents
❖ Main contents
Substring function allows you to extract a substring from another string, starting at a specific
position and with a certain length. The following illustrates the different uses of this function.
SUBSTRING(str, pos);
SUBSTRING(str FROM pos);
The result of the above statement returns a substring from a string str starting at position pos
The above two statements return a substring from a string str, starting at position pos and the
substring returning only len characters. Note that FROM is a standard SQL syntax keyword.
Let's consider some of the following examples:
MySQL allows using negative values for pos parameters. If negative values are used for the
pos parameter, the start of the substring is counted from the end of the string.
SELECT substring('MySQL Substring',-9);
Result: Substring
Sometimes the code snippet uses substr () instead of substring () function. Substr is a synonym
for substring, so it has the same effect.
2. CONCAT function
CONCAT function is used to concatenate two or more strings. If the arguments are numbers, they
will be converted to strings before concatenating. If any of the arguments in the argument list
are NULL, the concat function will return NULL.
CONCAT(str1,str2,...);
Example: To display the first full name of a customer's contact we can use the concat function
to concatenate the first and last names and the separator between them. Here is the query:
MySQL also supports the CONCAT_WS function, which allows us to concatenate two or more
strings with a predefined delimiter. The syntax of the CONCAT_WS function:
CONCAT_WS(seperator, str1, str2,...)
The first parameter is the defined delimiter and then the strings you want to concatenate. The
result is a concatenated string, with a separator between each paired component. For example,
the same result can be achieved in the above example using CONCAT_WS instead of CONCAT.
SELECT CONCAT_WS(char(10),
CONCAT_WS(' ',contactLastname,contactFirstname),
addressLine1, addressLine2,
CONCAT_WS(' ',postalCode,city), country,
CONCAT_WS(char(10),'')) AS Customer_Address
FROM customers;
3. REPLACE function
MySQL provides a useful string handling function: REPLACE, that allows replacing a string
in the original string with a new string. The syntax of the function is as follows:
Example:
Besides, we can use REPLACE to replace a string in a column of a table with a new string.
UPDATE products
SET productDescription =
REPLACE(productDescription,'abuot','about');
The query will look at the productDescription column and find all occurrences of the 'abuot'
spelling and replace it with the exact word 'about'.
It is very important to note that in the REPLACE function, the first parameter is the field name
not enclosed in quotation marks ‘’. If the field name is set as 'field_name', the query will update
the content of the 'field_name' column, causing data loss.
4. IF function
IF is a control function, which returns a string or number based on a given condition. The syntax
of the IF function is as follows:
• The first parameter is expr to be checked for true or false. Actual value means that expr
is not equal to 0 and expr is not equal to NULL. Note that NULL is a special value, not
equal to anything else, even by itself.
• If expr is evaluated to be true, the IF function will return if_true_expr, otherwise it will
return if_false_expr.
Example:
Example: In the table Customer, not all customers have state information. Therefore, when
we select the customer, the state information will display NULL values, which are not
significant for reporting purposes.
SELECT customerNumber,
customerName,
state,
country
FROM customers;
SELECT customerNumber,
customerName,
IF(state IS NULL,'N/A',state) state,
country
FROM customers;
Example: the IF function is also very useful with aggregate functions. Suppose if we want to
know how many orders were Shipped and Canceled at the same time, we can use IF to count as
follows:
In the above query, if the status of the order is SHIPPED or CANCELLED, IF will return the
value 1, otherwise it returns 0. And then the SUM function will calculate the total to ship and
be canceled based on on the return value of the IF function.
5. LAST_INSERT_ID function
LAST_INSERT_ID function returns the ID of the last record inserted into the table, provided
that the ID of the column has the attribute AUTO_INCREMENT. In database design, we usually
use an auto-increment column AUTO_INCREMENT. When inserting a new record into a table
with column AUTO_INCREMENT, MySQL generates the ID for automatically based on its
settings. This ID can be obtained by using the LAST_INSERT_ID function.
Example: Create a new table for testing called TBL. In the TBL table, we use the ID as the
column AUTO_INCREMENT.
Then we use the LAST_INSERT_ID() function to get the newly inserted ID.
SELECT LAST_INSERT_ID();
It is important to note that if you insert multiple records into the table using the unique INSERT
statement, the LAST_INSERT_ID function will return the value generated for the first inserted
records. Try these steps:
SELECT LAST_INSERT_ID();
We have inserted 3 records using the INSERT statement and LAST_INSERT_ID function
returns the ID of the first record as desired. MySQL LAST_INSERT_ID operates on a client-
independent principle. It means that the value returned by LAST_INSERT_ID for a particular
client is the value that client generates. This ensures that each client can receive its own ID
without having to take care of the activities of other clients and without using a lock or
transaction mechanism (will be learned later).
6. DATEDIFF function
In some cases, it is necessary to calculate the number of days between two time points, for
example the number of days from the shipping date to the required date in an order. In these
cases, it is necessary to use the DATEDIFF function.
DATEDIFF syntax:
DATEDIFF(expr1,expr2)
SELECT DATEDIFF('2011-08-17','2011-08-17');
Result: 0 day
SELECT DATEDIFF('2011-08-17','2011-08-08');
Result: 9 days
SELECT DATEDIFF('2011-08-08','2011-08-17');
Result: -9 days
Example: To calculate the number of days left between the shipping date and the required
date to place an order, we use DATEDIFF as follows:
SELECT orderNumber,
DATEDIFF(requiredDate,shippedDate) AS daysLeft
FROM orders
ORDER BY daysLeft DESC;
7. ADDDATE, EXTRACT function
MySQL also supports a number of other date processing functions like: ADDDATE,
EXTRACT
ADDDATE function: returns a time value as a result of the operation on a different time
value.
Example: Get the date 30 days after the current date and time:
Use the keyword DAY to indicate that the value will be added as a date. Similarly we can use
some of the following keywords:
SELECT *
FROM orders
WHERE orderDate>= '2005-5-1' AND orderDate < ADDDATE('2005-5-
1', INTERVAL 30 DAY);
Result:
Example: Get the orders from May 1, 2005 30 days before to May 1, 2005
SELECT *
FROM orders
WHERE orderDate<= '2005-5-1' AND orderDate > ADDDATE('2005-5-
1', INTERVAL -30 DAY);
If the time added is month, year, the corresponding keywords used are MONTH, YEAR.
SELECT *
FROM orders
WHERE orderDate<= '2005-5-1' AND orderDate > ADDDATE('2005-5-
1', INTERVAL -1 MONTH);
EXTRACT function: separates values like day, month, year from a value of time type. (Note
that MONTH or YEAR may be used instead.)
SELECT *
FROM orders
SELECT *
FROM orders
WHERE EXTRACT(YEAR FROM orderDate) = 2005 and EXTRACT(MONTH
FROM orderDate) = 5;
❖ Practical exercises:
1. Get the first 50 characters of the product description, naming it ‘Title of products’.