Understanding MySQL String Functions

Setting Up the Sample Database

To illustrate MySQL string functions, we will create a table named indian_users containing sample data with Indian names. This table will serve as the foundation for our examples.

Step 1: Create the Table

We define a table with columns for id, first_name, last_name, and email.

CREATE TABLE indian_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100)
);

Step 2: Insert Sample Data

We populate the table with sample records containing Indian names.

INSERT INTO indian_users (first_name, last_name, email) VALUES
('Aarav', 'Sharma', 'aarav.sharma@email.com'),
('Priya', 'Verma', 'priya.verma@email.com'),
('Rohan', 'Patel', 'rohan.patel@email.com'),
('Ananya', 'Singh', 'ananya.singh@email.com'),
('Vikram', 'Gupta', 'vikram.gupta@email.com');

The table now contains five records, which we will use to demonstrate various MySQL string functions.

Exploring MySQL String Functions

Below, we cover key MySQL string functions, including their syntax, purpose, and examples using the indian_users table. Each example includes the SQL query and its output for clarity.

1. CONCAT: Combining Strings

Purpose: Combines two or more strings into a single string.
Syntax: CONCAT(string1, string2, ...)

Example: Create a full name by combining first_name and last_name with a space between them.

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

Output:

+-----------------+
| full_name       |
+-----------------+
| Aarav Sharma    |
| Priya Verma     |
| Rohan Patel     |
| Ananya Singh    |
| Vikram Gupta    |
+-----------------+

Explanation: The CONCAT function merges the first_name and last_name columns, adding a space (‘ ‘) between them to form a readable full name.

2. UPPER: Converting to Uppercase

Purpose: Converts all characters in a string to uppercase.
Syntax: UPPER(string)

Example: Display the first_name in uppercase.

SELECT first_name, UPPER(first_name) AS uppercase_name
FROM indian_users;

Output:

+------------+---------------+
| first_name | uppercase_name |
+------------+---------------+
| Aarav      | AARAV         |
| Priya      | PRIYA         |
| Rohan      | ROHAN         |
| Ananya     | ANANYA        |
| Vikram     | VIKRAM        |
+------------+---------------+

Explanation: The UPPER function transforms each first_name to uppercase, which can be useful for standardizing data or creating case-insensitive searches.

3. LOWER: Converting to Lowercase

Purpose: Converts all characters in a string to lowercase.
Syntax: LOWER(string)

Example: Display the email in lowercase.

SELECT email, LOWER(email) AS lowercase_email
FROM indian_users;

Output:

+---------------------+---------------------+
| email               | lowercase_email     |
+---------------------+---------------------+
| aarav.sharma@email.com | aarav.sharma@email.com |
| priya.verma@email.com  | priya.verma@email.com  |
| rohan.patel@email.com  | rohan.patel@email.com  |
| ananya.singh@email.com | ananya.singh@email.com |
| vikram.gupta@email.com | vikram.gupta@email.com |
+---------------------+---------------------+

Explanation: The LOWER function ensures all characters in the email column are lowercase, which is often used to normalize email addresses for consistency.

4. LENGTH: Measuring String Length

Purpose: Returns the length of a string in bytes.
Syntax: LENGTH(string)

Example: Calculate the length of each first_name.

SELECT first_name, LENGTH(first_name) AS name_length
FROM indian_users;

Output:

+------------+-------------+
| first_name | name_length |
+------------+-------------+
| Aarav      |           5 |
| Priya      |           5 |
| Rohan      |           5 |
| Ananya     |           6 |
| Vikram     |           6 |
+------------+-------------+

Explanation: The LENGTH function counts the number of bytes in each first_name. For ASCII characters, this corresponds to the number of characters.

5. SUBSTRING: Extracting a Substring

Purpose: Extracts a portion of a string based on a starting position and length.
Syntax: SUBSTRING(string, start, length)

Example: Extract the first three characters of each first_name.

SELECT first_name, SUBSTRING(first_name, 1, 3) AS short_name
FROM indian_users;

Output:

+------------+------------+
| first_name | short_name |
+------------+------------+
| Aarav      | Aar        |
| Priya      | Pri        |
| Rohan      | Roh        |
| Ananya     | Ana        |
| Vikram     | Vik        |
+------------+------------+

Explanation: The SUBSTRING function starts at position 1 and extracts 3 characters from each first_name, creating a shortened version of the name.

6. REPLACE: Replacing Substrings

Purpose: Replaces all occurrences of a substring with another substring.
Syntax: REPLACE(string, old_string, new_string)

Example: Replace ‘Sharma’ with ‘Kumar’ in the last_name column.

SELECT last_name, REPLACE(last_name, 'Sharma', 'Kumar') AS updated_last_name
FROM indian_users;

Output:

+----------+------------------+
| last_name | updated_last_name |
+----------+------------------+
| Sharma   | Kumar            |
| Verma    | Verma            |
| Patel    | Patel            |
| Singh    | Singh            |
| Gupta    | Lahaina    |
| Gupta    | Gupta            |
+----------+------------------+

Explanation: The REPLACE function changes ‘Sharma’ to ‘Kumar’ in the last_name column, leaving other names unchanged.

7. TRIM: Removing Leading and Trailing Spaces

Purpose: Removes leading and trailing spaces from a string.
Syntax: TRIM(string)

Example: Assume some first_name values have extra spaces (we’ll simulate this by adding spaces).

SELECT TRIM(CONCAT(' ', first_name, ' ')) AS trimmed_name
FROM indian_users;

Output:

+--------------+
| trimmed_name |
+--------------+
| Aarav        |
| Priya        |
| Rohan        |
| Ananya       |
| Vikram       |
+--------------+

Explanation: The TRIM function removes spaces added around first_name, ensuring clean data without unnecessary whitespace.

8. LOCATE: Finding a Substring’s Position

Purpose: Returns the position of the first occurrence of a substring in a string.
Syntax: LOCATE(substring, string)

Example: Find the position of ‘@’ in the email column.

SELECT email, LOCATE('@', email) AS at_position
FROM indian_users;

Output:

+---------------------+-------------+
| email               | at_position |
+---------------------+-------------+
| aarav.sharma@email.com |          12 |
| priya.verma@email.com  |          11 |
| rohan.patel@email.com  |          11 |
| ananya.singh@email.com |          13 |
| vikram.gupta@email.com |          13 |
+---------------------+-------------+

Explanation: The LOCATE function identifies the position of the ‘@’ symbol in each email, which can help parse email addresses.

Practical Application: Combining Functions

In real-world scenarios, you may combine multiple string functions to achieve complex tasks. For example, let’s create a standardized username by combining the first three letters of first_name (in lowercase) with the last_name (in uppercase).

SELECT first_name, last_name,
       CONCAT(LOWER(SUBSTRING(first_name, 1, 3)), UPPER(last_name)) AS username
FROM indian_users;

Output:

+------------+----------+-------------+
| first_name | last_name | username    |
+------------+----------+-------------+
| Aarav      | Sharma   | aarSHARMA   |
| Priya      | Verma    | priVERMA    |
| Rohan      | Patel    | rohPATEL    |
| Ananya     | Singh    | anaSINGH    |
| Vikram     | Gupta    | vikGUPTA    |
+------------+----------+-------------+

Explanation: This query uses SUBSTRING to extract the first three letters of first_name, LOWER to convert them to lowercase, UPPER to convert last_name to uppercase, and CONCAT to combine the results into a username.

Conclusion

MySQL string functions are powerful tools for manipulating and formatting text data in databases. By using Indian names in our examples, we’ve demonstrated how these functions can be applied to culturally relevant datasets. Functions like CONCAT, UPPER, LOWER, LENGTH, SUBSTRING, REPLACE, TRIM, and LOCATE enable precise control over string data, making them essential for tasks like data cleaning, formatting, and analysis.

Scroll to Top