Popular Searches
Popular Course Categories
Popular Courses

String Functions: CONCAT, UPPER, LOWER, and LENGTH

String Functions: CONCAT, UPPER, LOWER, and LENGTH

MySQL Functions and Data Transformation

String Functions: CONCAT, UPPER, LOWER, and LENGTH in MySQL – Detailed Notes

Course: MySQL Training

Topic: String Functions: CONCAT, UPPER, LOWER, and LENGTH

Course Link: MySQL Training Course

Demo Link: Register for a Free Course Demo


1. Introduction to String Functions in MySQL

String functions in MySQL are built-in functions used to manipulate, combine, transform, and analyze text data stored in database columns. They help developers retrieve meaningful information from strings without manually modifying the original table data.

String functions are commonly used with customer names, employee details, email addresses, product descriptions, addresses, usernames, and other text-based information.

In this topic, we will study four important MySQL string functions:

  • CONCAT(): Combines two or more strings into a single string.
  • UPPER(): Converts lowercase letters in a string to uppercase.
  • LOWER(): Converts uppercase letters in a string to lowercase.
  • LENGTH(): Returns the length of a string measured in bytes.

Example of String Functions

SELECT CONCAT('My', 'SQL') AS combined_text;
SELECT UPPER('mysql training') AS uppercase_text;
SELECT LOWER('MYSQL TRAINING') AS lowercase_text;
SELECT LENGTH('MySQL') AS string_length;

These queries demonstrate how MySQL can combine text, change letter case, and measure the byte length of a string.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand the purpose of string functions in MySQL.
  • Use CONCAT() to combine multiple strings.
  • Combine first names, last names, addresses, and other text fields.
  • Use UPPER() to convert text into uppercase.
  • Use LOWER() to convert text into lowercase.
  • Understand how LENGTH() measures string size in bytes.
  • Differentiate LENGTH() from CHAR_LENGTH().
  • Use string functions with SELECT statements and table columns.
  • Combine multiple string functions in a single query.
  • Handle NULL values when working with text.
  • Identify common errors and apply best practices.
  • Use string functions in practical database reporting tasks.

3. What Are String Functions?

String functions are SQL functions that perform operations on character strings. They can create a new text value, convert the case of letters, calculate string length, extract parts of text, remove spaces, or replace characters.

For example, a customers table may store a first name and last name in separate columns. CONCAT() can combine them into a full name. UPPER() can display names in uppercase, LOWER() can standardize email addresses, and LENGTH() can help identify the byte size of stored text.

3.1 Overview of the Four Functions

Function Purpose Example Result
CONCAT() Combines strings. CONCAT('Hello', ' World') Hello World
UPPER() Converts text to uppercase. UPPER('mysql') MYSQL
LOWER() Converts text to lowercase. LOWER('MYSQL') mysql
LENGTH() Returns the number of bytes. LENGTH('MySQL') 5

4. Understanding the CONCAT() Function

The CONCAT() function combines two or more string values into a single string. The resulting text contains the arguments joined together in the order in which they are provided.

CONCAT() is useful when information is stored across multiple columns but needs to be displayed as one value.

4.1 Syntax of CONCAT()

CONCAT(string1, string2, ..., stringN)

Parameters:

  • string1: The first string or value to combine.
  • string2: The second string or value to combine.
  • stringN: Additional strings or values to combine.

The function accepts one or more arguments. Numeric arguments are converted to their string representation as needed.

4.2 Basic Example

SELECT CONCAT('Hello', 'World') AS result;

Output:

result
HelloWorld

There is no automatic space between the two strings. MySQL joins the supplied values exactly as they are provided.

4.3 Combining Strings with a Space

SELECT CONCAT('Hello', ' ', 'World') AS result;

Output:

result
Hello World

The second argument is a single space, which separates the words in the result.

4.4 Combining Multiple Strings

SELECT CONCAT('Learn', ' ', 'MySQL', ' ', 'Today') AS message;

Output:

message
Learn MySQL Today

CONCAT() can combine several strings in a single expression, making it useful for generating complete labels, messages, and formatted text.

5. Using CONCAT() with Table Columns

In real database applications, CONCAT() is often used to combine values stored in different columns.

5.1 Example: Combining First Name and Last Name

Suppose a table named employees contains the columns first_name and last_name.

SELECT
    CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;

This query combines the first and last names and displays the result as full_name.

5.2 Example: Creating a Complete Address

SELECT
    CONCAT(
        house_number, ', ',
        street, ', ',
        city, ', ',
        postal_code
    ) AS full_address
FROM customers;

This query combines several address fields into a single formatted address. The actual column names must match those defined in the customers table.

5.3 Example: Generating a Product Label

SELECT
    CONCAT(product_name, ' - ', category) AS product_label
FROM products;

If product_name is 'Laptop' and category is 'Electronics', the resulting label is 'Laptop - Electronics'.

5.4 Example: Creating a Custom Message

SELECT
    CONCAT(
        'Welcome ',
        customer_name,
        '! Your customer ID is ',
        customer_id
    ) AS welcome_message
FROM customers;

This query generates a welcome message for each customer. MySQL converts the numeric customer_id to a string representation when combining it with text.

6. Handling Spaces and Separators with CONCAT()

CONCAT() does not automatically add spaces, commas, hyphens, or other separators. You must include these characters explicitly in the arguments.

Query Result Explanation
CONCAT('John','Smith') JohnSmith No separator is included.
CONCAT('John',' ','Smith') John Smith A space is inserted.
CONCAT('John','-','Smith') John-Smith A hyphen is inserted.
CONCAT('John',', ','Smith') John, Smith A comma followed by a space is inserted.

6.1 Using CONCAT_WS() as an Alternative

MySQL also provides CONCAT_WS(), which means concatenate with separator. It inserts a specified separator between the remaining arguments.

SELECT CONCAT_WS(' ', 'John', 'Michael', 'Smith') AS full_name;

Output:

John Michael Smith

Unlike CONCAT(), CONCAT_WS() skips NULL values among the strings being joined. However, if the separator itself is NULL, the result is NULL.

7. Handling NULL Values with CONCAT()

NULL represents a missing or unknown value in a database. An important behavior of CONCAT() is that if any argument is NULL, the entire result is NULL.

7.1 Example with NULL

SELECT CONCAT('MySQL', NULL, ' Training') AS result;

Output:

result
NULL

Even though two arguments contain text, the NULL argument causes the CONCAT() result to be NULL.

7.2 Handling NULL with COALESCE()

COALESCE() returns the first non-NULL value from its arguments. It can be used to provide a replacement when a text column is missing.

SELECT
    CONCAT(
        COALESCE(first_name, ''),
        ' ',
        COALESCE(last_name, '')
    ) AS full_name
FROM employees;

This query replaces NULL name components with empty strings before combining them. If both name fields are missing, the result may contain a space, so further cleanup may be needed.

7.3 A More Flexible Example with CONCAT_WS()

SELECT
    CONCAT_WS(' ', first_name, middle_name, last_name) AS full_name
FROM employees;

CONCAT_WS() skips NULL name components. It does not skip empty strings, so empty values may still produce extra separators.

8. Understanding the UPPER() Function

The UPPER() function converts lowercase letters in a string to uppercase according to the character set mapping. It is also known as UCASE(), which is a synonym in MySQL.

UPPER() is useful when displaying text in uppercase, generating standardized labels, and preparing text for comparisons or reports.

8.1 Syntax of UPPER()

UPPER(string_value)

Parameter: string_value is the string or expression whose letters should be converted to uppercase.

8.2 Basic Example

SELECT UPPER('mysql training') AS uppercase_text;

Output:

uppercase_text
MYSQL TRAINING

8.3 Converting Mixed-Case Text

SELECT UPPER('MySqL DaTaBaSe') AS result;

Output:

MYSQL DATABASE

UPPER() changes lowercase letters to uppercase. Existing uppercase letters remain uppercase, and spaces and punctuation are preserved.

9. Using UPPER() with Table Columns

UPPER() can be applied to database columns to display their values in uppercase without permanently changing the stored data.

9.1 Example: Employee Names

SELECT
    employee_name,
    UPPER(employee_name) AS uppercase_name
FROM employees;

This query displays the original employee name alongside its uppercase version.

9.2 Example: Product Categories

SELECT
    product_name,
    UPPER(category) AS category_code
FROM products;

If the category is 'electronics', the query displays 'ELECTRONICS' in the calculated column.

9.3 Example: Formatting Email Addresses

SELECT
    email,
    UPPER(email) AS uppercase_email
FROM customers;

This query displays email addresses in uppercase. It does not change the values stored in the customers table.

9.4 Example: Generating an Uppercase Label

SELECT
    UPPER(CONCAT(first_name, ' ', last_name)) AS display_name
FROM employees;

In this example, CONCAT() first joins the names, and UPPER() converts the resulting text to uppercase.

10. Practical Uses of UPPER()

  • Displaying department names in uppercase.
  • Formatting product category labels.
  • Creating uppercase report headings and identifiers.
  • Standardizing text for selected comparisons.
  • Generating consistent display values for dashboards.
  • Preparing text for a data-cleaning workflow.

Important: UPPER() does not permanently update a column. To change stored values, an UPDATE statement would be required. Such changes should be made only when they are intended and appropriate for the data.

11. Understanding the LOWER() Function

The LOWER() function converts uppercase letters in a string to lowercase according to the current character set mapping. LCASE() is a synonym for LOWER() in MySQL.

LOWER() is commonly used to standardize text display, normalize email addresses, and prepare text for comparisons when case differences should not matter.

11.1 Syntax of LOWER()

LOWER(string_value)

Parameter: string_value is the string or expression whose letters should be converted to lowercase.

11.2 Basic Example

SELECT LOWER('MYSQL TRAINING') AS lowercase_text;

Output:

lowercase_text
mysql training

11.3 Converting Mixed-Case Text

SELECT LOWER('MySqL DaTaBaSe') AS result;

Output:

mysql database

LOWER() changes uppercase letters to lowercase while preserving spaces, punctuation, and other characters that do not have a case conversion.

12. Using LOWER() with Table Columns

12.1 Example: Standardizing Email Display

SELECT
    customer_name,
    LOWER(email) AS normalized_email
FROM customers;

This query displays email addresses in lowercase. Lowercase normalization is often useful for consistent display and comparisons, but the actual matching behavior also depends on the column's collation and application requirements.

12.2 Example: Converting Usernames

SELECT
    username,
    LOWER(username) AS lowercase_username
FROM users;

The query displays each username in lowercase while leaving the original stored value unchanged.

12.3 Example: Converting Department Names

SELECT
    department,
    LOWER(department) AS department_name
FROM employees;

If a department is stored as 'HUMAN RESOURCES', the result is 'human resources'.

12.4 Example: Combining LOWER() and CONCAT()

SELECT
    LOWER(CONCAT(first_name, '.', last_name)) AS username
FROM employees;

If first_name is 'Rahul' and last_name is 'Sharma', the resulting username is 'rahul.sharma'. This is an example of generating a username-like value; real applications should also handle duplicates and their own username rules.

13. Difference Between UPPER() and LOWER()

Feature UPPER() LOWER()
Purpose Converts letters to uppercase. Converts letters to lowercase.
Example UPPER('Hello') LOWER('Hello')
Result HELLO hello
Synonym UCASE() LCASE()
Common use Uppercase labels and display formatting. Lowercase normalization and display formatting.

13.1 Example Using Both Functions

SELECT
    UPPER('MySQL Functions') AS uppercase_result,
    LOWER('MySQL Functions') AS lowercase_result;

Output:

uppercase_result lowercase_result
MYSQL FUNCTIONS mysql functions

14. Understanding the LENGTH() Function

The LENGTH() function returns the length of a string measured in bytes. A byte is a unit used to represent encoded data. Depending on the character set, a single character may require one or more bytes.

LENGTH() is useful when checking the storage size of text values, inspecting encoded strings, and performing byte-length validation.

14.1 Syntax of LENGTH()

LENGTH(string_value)

Parameter: string_value is the string or expression whose length in bytes should be calculated.

14.2 Basic Example

SELECT LENGTH('MySQL') AS string_length;

Output:

string_length
5

The string 'MySQL' contains five single-byte characters in its usual encoding, so its byte length is 5.

14.3 Measuring a String with Spaces

SELECT LENGTH('My SQL') AS string_length;

Output:

6

The space between 'My' and 'SQL' also occupies a byte in this example. LENGTH() counts the bytes used by the entire string, including spaces and punctuation.

14.4 Measuring an Empty String

SELECT LENGTH('') AS string_length;

Output:

0

An empty string contains no bytes, so LENGTH() returns 0.

15. Difference Between LENGTH() and CHAR_LENGTH()

One of the most important concepts in MySQL string functions is the difference between byte length and character length.

  • LENGTH(): Returns the number of bytes used to represent the string.
  • CHAR_LENGTH(): Returns the number of characters, measured as code points.

For ordinary English letters encoded as single-byte characters in UTF-8, both functions often return the same value. For multibyte characters, the results can be different.

15.1 Comparison Example

SELECT
    LENGTH('Hello') AS byte_length,
    CHAR_LENGTH('Hello') AS character_length;

Output:

byte_length character_length
5 5

15.2 Example with Multibyte Characters

SELECT
    LENGTH('海豚') AS byte_length,
    CHAR_LENGTH('海豚') AS character_length;

When the string uses UTF-8 encoding in which each of these Chinese characters takes three bytes, the result is:

byte_length character_length
6 2

The string contains two characters but uses six bytes in this encoding.

15.3 Which Function Should You Use?

Requirement Recommended Function Reason
Count the characters in a name. CHAR_LENGTH() Measures characters rather than bytes.
Check the byte length of encoded text. LENGTH() Measures the number of bytes.
Validate a character-count rule for a username. CHAR_LENGTH() Usually matches character-based requirements more closely.
Inspect the encoded size of a string. LENGTH() Returns the byte count.

16. Using LENGTH() with Table Columns

LENGTH() can be applied to columns to calculate the byte length of stored text values.

16.1 Example: Measuring Customer Names

SELECT
    customer_name,
    LENGTH(customer_name) AS name_byte_length
FROM customers;

This query displays each customer's name along with its length in bytes.

16.2 Example: Checking Email Length

SELECT
    email,
    LENGTH(email) AS email_byte_length
FROM customers;

This query can help inspect the byte length of email values. If the business requirement concerns the number of characters, use CHAR_LENGTH() instead.

16.3 Example: Finding Long Product Names

SELECT
    product_name,
    LENGTH(product_name) AS name_byte_length
FROM products
WHERE LENGTH(product_name) > 20;

This query returns products whose product_name values exceed 20 bytes. It does not necessarily return every name with more than 20 characters, because characters can use different numbers of bytes.

16.4 Example: Sorting by String Length

SELECT
    product_name,
    LENGTH(product_name) AS name_byte_length
FROM products
ORDER BY LENGTH(product_name) DESC;

This query sorts products from the largest byte length to the smallest.

17. Combining CONCAT(), UPPER(), LOWER(), and LENGTH()

MySQL allows string functions to be nested inside other string functions. The output of one function can become the input of another.

17.1 Combining a Full Name and Converting It to Uppercase

SELECT
    UPPER(CONCAT(first_name, ' ', last_name)) AS full_name
FROM employees;

First, CONCAT() combines the first and last names. Then UPPER() converts the resulting string to uppercase.

17.2 Combining a Full Name and Converting It to Lowercase

SELECT
    LOWER(CONCAT(first_name, '.', last_name)) AS username
FROM employees;

This query combines two name columns with a period and converts the resulting value to lowercase.

17.3 Calculating the Length of a Combined Name

SELECT
    CONCAT(first_name, ' ', last_name) AS full_name,
    LENGTH(CONCAT(first_name, ' ', last_name)) AS full_name_byte_length
FROM employees;

The query generates a full name and calculates the byte length of the combined value, including the space between the names.

17.4 Applying Multiple Functions in One Query

SELECT
    CONCAT(first_name, ' ', last_name) AS full_name,
    UPPER(first_name) AS uppercase_first_name,
    LOWER(last_name) AS lowercase_last_name,
    LENGTH(CONCAT(first_name, ' ', last_name)) AS full_name_byte_length
FROM employees;

This query displays four calculated values for each employee. The original table data remains unchanged.

18. Creating a Sample Database for Practice

Use the following table to practise CONCAT(), UPPER(), LOWER(), and LENGTH(). Run the CREATE TABLE statement before inserting the sample records.

18.1 Create the Employees Table

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    department VARCHAR(50),
    email VARCHAR(100)
);

18.2 Insert Sample Records

INSERT INTO employees
(employee_id, first_name, last_name, department, email)
VALUES
(1, 'Rahul', 'Sharma', 'IT', '[email protected]'),
(2, 'Priya', 'Patel', 'HR', '[email protected]'),
(3, 'Amit', 'Verma', 'Finance', '[email protected]'),
(4, 'Neha', 'Singh', 'Marketing', '[email protected]'),
(5, 'Karan', 'Mehta', 'Sales', '[email protected]');

18.3 Display All Records

SELECT * FROM employees;

This query displays all records inserted into the employees table. You can now use the string functions to transform and inspect the stored text values.

19. Practical Examples Using the Employees Table

Example 1: Displaying Full Names

SELECT
    employee_id,
    CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;

This query creates a full_name result column by joining the first and last names with a space.

Example 2: Displaying Names in Uppercase

SELECT
    employee_id,
    UPPER(CONCAT(first_name, ' ', last_name)) AS uppercase_full_name
FROM employees;

This query combines the names and converts the complete result to uppercase.

Example 3: Displaying Emails in Lowercase

SELECT
    employee_id,
    LOWER(email) AS normalized_email
FROM employees;

This query displays email addresses in lowercase, which can support consistent formatting in reports.

Example 4: Measuring First Name Length

SELECT
    first_name,
    LENGTH(first_name) AS first_name_byte_length
FROM employees;

This query returns the byte length of each first name.

Example 5: Measuring Character Count

SELECT
    first_name,
    CHAR_LENGTH(first_name) AS first_name_character_count
FROM employees;

This query returns the number of characters in each first name, making it useful for character-based validation.

Example 6: Creating a Standardized Employee Label

SELECT
    CONCAT(
        UPPER(department),
        ' - ',
        LOWER(CONCAT(first_name, '.', last_name))
    ) AS employee_label
FROM employees;

This query creates a label with the department in uppercase and a lowercase name-based identifier.

Example 7: Finding Names Longer Than Five Characters

SELECT
    first_name,
    CHAR_LENGTH(first_name) AS character_count
FROM employees
WHERE CHAR_LENGTH(first_name) > 5;

CHAR_LENGTH() is used here because the requirement is based on the number of characters rather than bytes.

20. Common Errors and Troubleshooting

Problem Possible Cause Solution
CONCAT() returns NULL. At least one argument is NULL. Check for NULL values and consider COALESCE() or CONCAT_WS().
Words appear joined together. No spaces or separators were supplied. Add a space, comma, or other separator as an argument.
UPPER() does not change a binary string as expected. The input uses a binary string type. Convert the data to an appropriate nonbinary character string before case conversion.
LOWER() does not change a binary string as expected. The input uses a binary string type. Use an appropriate character-set conversion when suitable for the stored data.
LENGTH() returns a larger number than expected. Multibyte characters use multiple bytes. Use CHAR_LENGTH() when the requirement is character count.
Unexpected spaces appear in concatenated names. Source values may contain leading or trailing spaces or empty strings. Inspect the source data and consider TRIM() where appropriate.
Calculated output is mistaken for updated table data. A SELECT expression changes only the result, not the stored value. Use UPDATE only when a permanent data change is required.
Case-based comparisons behave unexpectedly. Comparison behavior may depend on collation. Check the column's character set and collation and define the intended comparison behavior.

21. Best Practices for Using String Functions

  • Choose the correct function: Use CONCAT() to combine text, UPPER() for uppercase, LOWER() for lowercase, and LENGTH() for byte length.
  • Include separators explicitly: CONCAT() does not automatically add spaces or punctuation.
  • Handle NULL values: Remember that CONCAT() returns NULL if any argument is NULL.
  • Use CONCAT_WS() when suitable: It can simplify joining values with a separator while skipping NULL arguments.
  • Distinguish bytes from characters: Use LENGTH() for bytes and CHAR_LENGTH() for character counts.
  • Preserve original values when appropriate: Use string functions in SELECT to format output without modifying stored data.
  • Check data quality: Leading spaces, trailing spaces, empty strings, and NULL values can affect the results.
  • Use meaningful aliases: Names such as full_name, normalized_email, and byte_length make query results easier to understand.
  • Be careful with email normalization: Lowercase formatting is common, but identity and comparison rules should follow the application's requirements.
  • Consider performance: Applying functions to columns in WHERE conditions may limit the use of ordinary indexes for those expressions. Review query execution plans for large tables.
  • Test with multilingual text: Character length and byte length can differ depending on the character set.
  • Avoid unnecessary updates: Do not permanently change stored text merely to format a report.

22. Real-World Applications

Function Real-World Application Example
CONCAT() Combining customer names. First name + last name
CONCAT() Building readable addresses. Street + city + postal code
CONCAT() Generating product labels. Product name + category
UPPER() Formatting department labels. it becomes IT
UPPER() Displaying standardized headings. monthly sales becomes MONTHLY SALES
LOWER() Formatting email addresses. [email protected] becomes [email protected]
LOWER() Creating lowercase identifiers. Rahul.Sharma becomes rahul.sharma
LENGTH() Checking byte length. Measuring encoded text size
CHAR_LENGTH() Validating character counts. Checking the length of a username

23. Practice Exercises

Complete the following exercises using the employees table or create suitable tables of your own.

  1. Write a query to combine first_name and last_name into a column named full_name.
  2. Write a query to display all employee names in uppercase.
  3. Write a query to display all employee email addresses in lowercase.
  4. Write a query to calculate the byte length of each employee's email address.
  5. Write a query to display the first name and its character count using CHAR_LENGTH().
  6. Combine department and employee name into a single employee_label column.
  7. Create a welcome message by combining the words 'Welcome', the employee's first name, and an exclamation mark.
  8. Write a query that displays both the original name and its uppercase version.
  9. Write a query to find employees whose first names contain more than five characters.
  10. Write a query that combines first_name and last_name while handling NULL values.
  11. Write a query that displays a lowercase username generated from first_name and last_name.
  12. Write a query to compare LENGTH() and CHAR_LENGTH() for a multilingual text value supported by your database character set.

24. Mini Project: Employee Text Formatting and Validation

Project Objective

Create a report that standardizes employee names, formats email addresses, generates employee labels, and measures text lengths using MySQL string functions.

Project Requirements

  • Display employee ID and the original first and last names.
  • Combine first and last names into a full_name column.
  • Display the full name in uppercase.
  • Display the full name in lowercase.
  • Generate a lowercase email value for consistent display.
  • Calculate the byte length of the full name and email address.
  • Calculate the character count of the full name.
  • Identify names whose character count exceeds a chosen limit.
  • Handle NULL values where necessary.

Sample Solution

SELECT
    employee_id,
    first_name,
    last_name,
    CONCAT(
        COALESCE(first_name, ''),
        ' ',
        COALESCE(last_name, '')
    ) AS full_name,
    UPPER(
        CONCAT(
            COALESCE(first_name, ''),
            ' ',
            COALESCE(last_name, '')
        )
    ) AS uppercase_full_name,
    LOWER(
        CONCAT(
            COALESCE(first_name, ''),
            '.',
            COALESCE(last_name, '')
        )
    ) AS lowercase_username,
    LOWER(email) AS normalized_email,
    LENGTH(
        CONCAT(
            COALESCE(first_name, ''),
            ' ',
            COALESCE(last_name, '')
        )
    ) AS full_name_byte_length,
    CHAR_LENGTH(
        CONCAT(
            COALESCE(first_name, ''),
            ' ',
            COALESCE(last_name, '')
        )
    ) AS full_name_character_count
FROM employees;

This query demonstrates the combined use of CONCAT(), UPPER(), LOWER(), LENGTH(), and CHAR_LENGTH(). COALESCE() replaces NULL name components with empty strings before concatenation. Depending on the data, extra spaces or punctuation may still need to be cleaned up.

Expected Learning Outcomes

  • Combine data from multiple text columns.
  • Format text consistently for reports.
  • Understand byte length versus character count.
  • Recognize the impact of NULL values on concatenation.
  • Apply multiple string functions within a single query.

25. MySQL String Functions Interview Questions and Answers

Q1. What are string functions in MySQL?

Answer: String functions are built-in SQL functions used to manipulate, format, combine, and analyze text values.

Q2. What is CONCAT() used for?

Answer: CONCAT() combines two or more strings or values into one string.

Q3. Does CONCAT() automatically add spaces?

Answer: No. Spaces and separators must be provided explicitly as arguments.

Q4. What happens when one CONCAT() argument is NULL?

Answer: CONCAT() returns NULL if any argument is NULL.

Q5. What is CONCAT_WS()?

Answer: CONCAT_WS() combines values using a specified separator and skips NULL values among the strings being joined.

Q6. What is UPPER() used for?

Answer: UPPER() converts lowercase letters in a string to uppercase according to the character set mapping.

Q7. What is LOWER() used for?

Answer: LOWER() converts uppercase letters in a string to lowercase according to the character set mapping.

Q8. What are the synonyms for UPPER() and LOWER()?

Answer: UCASE() is a synonym for UPPER(), and LCASE() is a synonym for LOWER().

Q9. What does LENGTH() return?

Answer: LENGTH() returns the length of a string measured in bytes.

Q10. What is the difference between LENGTH() and CHAR_LENGTH()?

Answer: LENGTH() counts bytes, whereas CHAR_LENGTH() counts characters measured as code points.

Q11. Can string functions be used with table columns?

Answer: Yes. String functions can operate on columns to create calculated values in query results.

Q12. Do string functions permanently modify stored data?

Answer: No. When used in a SELECT query, they calculate output values without changing the stored records.

Q13. Can multiple string functions be combined in one query?

Answer: Yes. Functions can be nested, such as using UPPER(CONCAT(first_name, ' ', last_name)).

Q14. Why can LENGTH() return a value larger than the character count?

Answer: Some characters require multiple bytes in the chosen character encoding. LENGTH() counts those bytes, while CHAR_LENGTH() counts characters.

Q15. How can NULL values be handled when combining names?

Answer: COALESCE() can replace NULL values with a suitable fallback, or CONCAT_WS() can skip NULL arguments when joining values.

Q16. Can UPPER() and LOWER() be used with email addresses?

Answer: Yes. They can format email addresses for consistent display or normalization, but actual identity and matching rules should follow the application's requirements.

Q17. How can you find text values longer than a specific number of characters?

Answer: Use CHAR_LENGTH() in a condition, such as WHERE CHAR_LENGTH(first_name) > 5.

Q18. Does LENGTH() count spaces?

Answer: Yes. Spaces are included in the byte length of the string.

Q19. What is the purpose of an alias in a string-function query?

Answer: An alias gives a calculated column a readable name, such as full_name, uppercase_name, or email_byte_length.

Q20. Which function should be used to count characters in multilingual text?

Answer: CHAR_LENGTH() is generally appropriate for counting characters, while LENGTH() is used when the byte length is required.

26. Quick Revision Notes

  • String functions manipulate and analyze text values in MySQL.
  • CONCAT() joins multiple strings into a single result.
  • CONCAT() does not automatically insert spaces or separators.
  • CONCAT() returns NULL if any argument is NULL.
  • CONCAT_WS() joins values with a separator and skips NULL string arguments.
  • UPPER() converts letters to uppercase.
  • LOWER() converts letters to lowercase.
  • UCASE() and LCASE() are synonyms for UPPER() and LOWER().
  • LENGTH() returns the number of bytes in a string.
  • CHAR_LENGTH() returns the number of characters.
  • Spaces and punctuation contribute to string length.
  • Multibyte characters can make LENGTH() larger than CHAR_LENGTH().
  • String functions in SELECT queries do not permanently modify stored data.
  • Multiple string functions can be nested in a single expression.
  • COALESCE() can help handle NULL values during concatenation.

27. Final Checklist

  • Understand the role of MySQL string functions.
  • Write CONCAT() expressions to combine text.
  • Insert spaces and separators correctly.
  • Handle NULL values when concatenating columns.
  • Use UPPER() and LOWER() for text formatting.
  • Calculate byte length using LENGTH().
  • Calculate character count using CHAR_LENGTH().
  • Combine several string functions in one query.
  • Test the functions with table columns and sample records.
  • Complete the practice exercises and mini project.

28. Conclusion

CONCAT(), UPPER(), LOWER(), and LENGTH() are important MySQL string functions that help developers combine, format, and analyze text data. CONCAT() joins multiple values, UPPER() converts letters to uppercase, LOWER() converts letters to lowercase, and LENGTH() measures the byte length of a string.

Understanding the difference between LENGTH() and CHAR_LENGTH() is especially important when working with multilingual text or character-based validation. Correct handling of NULL values, separators, and character sets also helps produce accurate query results.

By practising these functions with employee, customer, and product tables, learners can build useful SQL queries for data formatting, reporting, and validation.

To learn more database concepts and practical SQL skills, visit the MySQL Training Course at JustAcademy. You can also register for a course demo to explore the training.

whatsapp