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

LAB 05 Common Functions in Mysql: Main Contents

The document discusses common string processing, conditional, and time functions in MySQL including: 1. The SUBSTRING function extracts a substring from a string starting at a given position with an optional length. 2. The CONCAT and CONCAT_WS functions concatenate multiple strings together with or without a separator. 3. The REPLACE function finds and replaces a substring within a string. 4. The IF function conditionally returns one value if an expression is true and another if it is false. 5. The LAST_INSERT_ID function returns the auto-incremented ID of the last inserted record. 6. Functions like DATEDIFF calculate the time difference between two dates while

Uploaded by

Thiệp Lê
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

LAB 05 Common Functions in Mysql: Main Contents

The document discusses common string processing, conditional, and time functions in MySQL including: 1. The SUBSTRING function extracts a substring from a string starting at a given position with an optional length. 2. The CONCAT and CONCAT_WS functions concatenate multiple strings together with or without a separator. 3. The REPLACE function finds and replaces a substring within a string. 4. The IF function conditionally returns one value if an expression is true and another if it is false. 5. The LAST_INSERT_ID function returns the auto-incremented ID of the last inserted record. 6. Functions like DATEDIFF calculate the time difference between two dates while

Uploaded by

Thiệp Lê
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

LAB 05

COMMON FUNCTIONS IN MYSQL

❖ Main contents

- String processing function: Substring, Concat, Replace


- Conditional function IF
- LAST_INSERT_ID function
- Time processing function: DATEDIFF, ADDDATE, EXTRACT

1. SUBSTRING processing function

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

SUBSTRING(str, pos, len);


SUBSTRING(str FROM pos FOR len);

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:

SELECT substring('MySQL Substring',7);


Result: Substring
SELECT substring('MySQL Substring' FROM 7);
Result: Substring
SELECT substring('MySQL Substring',7,3);
Result: Sub
SELECT substring('MySQL Substring' FROM 7 FOR 3);
Result: Sub

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:

SELECT CONCAT(contactLastname,', ',contactFirstname)


fullname
FROM customers;

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('; ', contactLastname, contactFirstname)


fullname
FROM customers;

Here is another example of using CONCAT_WS to get customer address format.

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:

REPLACE(origin string, search string, replacement string);

Example:

SELECT REPLACE('MySQL Replace', 'MySQL', 'MariaDB');

Result: MariaDB Replace

Besides, we can use REPLACE to replace a string in a column of a table with a new string.

The syntax of the function is as follows:

UPDATE <table name>


SET column name = REPLACE(column name, search string
replacement string)
WHERE <conditions>;

Note: When searching for alternatives, MySQL is case-sensitive.


For example, if you want to correct the spelling errors in the table Product in a sample
database, use the REPLACE function as follows:

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:

IF(expr, if_true_expr, if_false_expr)

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

SELECT IF(1 = 2,'true','false');


Result: false
SELECT IF(1 = 1,' true','false');
Result: true

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;

We can use IF to display the client's status as N/A if it is NULL as follows:

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:

SELECT SUM(IF(status = 'Shipped',1,0)) AS Shipped,


SUM(IF(status = 'Cancelled',1,0)) AS Cancelled
FROM orders;

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.

CREATE TABLE tbl(


id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
description varchar(250) NOT NULL
);

Then we use the LAST_INSERT_ID() function to get the newly inserted ID.

INSERT INTO tbl(description)


VALUES('MySQL last_insert_id');

Execute the query:

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:

INSERT INTO tbl(description)


VALUES('record 1'),
('record 2'),
('record 3');

Execute the query:

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)

expr1 and expr2 are two milestones.


Example:

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:

SELECT ADDDATE(NOW(), INTERVAL 30 DAY);

Use the keyword DAY to indicate that the value will be added as a date. Similarly we can use
some of the following keywords:

Value Input format


MICROSECOND MICROSECONDS
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
WEEK WEEKS
MONTH MONTHS
QUARTER QUARTERS
YEAR YEARS
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
Value Input format
MINUTE_MICROSECOND 'MINUTES:SECONDS.MICROSECONDS'
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MICROSECOND 'HOURS:MINUTES:SECONDS.MICROSECONDS'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
'DAYS
DAY_MICROSECOND HOURS:MINUTES:SECONDS.MICROSECONDS'
DAY_SECOND 'DAYS HOURS:MINUTES:SECONDS'
DAY_MINUTE 'DAYS HOURS:MINUTES'
DAY_HOUR 'DAYS HOURS'
YEAR_MONTH 'YEARS-MONTHS'

Example: Get the orders within 30 days from May 1, 2005

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.

The example above can be rewritten as follows:

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

Example: Get the month of a time value:

SELECT EXTRACT(MONTH FROM '2004-12-31 23:59:59');


Example: Get the year of a time value:

SELECT EXTRACT(YEAR FROM '2004-12-31 23:59:59');

Example: Get the orders placed in 2005:

SELECT *

FROM orders

WHERE EXTRACT(YEAR FROM orderDate) = 2005;

Example: Get the orders placed in May 2005:

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

2. Get the descriptions of employees in the format ‘Fullname, jobTitle’.

3. Update the employees’ information whose jobTitle is ‘Sales Rep’ to ‘Sales


Representative’.

4. Get 5 orders shipped sooner than the required date.

5. Get the orders in May 2005 with an unspecified shipped date.

You might also like