Lab 15: String Functions

Time: 30 minutes | Level: Foundations | DB: MySQL 8 / PostgreSQL 15

Overview

Master string manipulation: CONCAT, UPPER/LOWER, TRIM, SUBSTRING, LENGTH, REPLACE, pattern matching with LIKE/ILIKE, regex, and LPAD/RPAD for formatting.


Step 1: Setup

docker run -d --name mysql-lab -e MYSQL_ROOT_PASSWORD=rootpass mysql:8.0
for i in $(seq 1 30); do docker exec mysql-lab mysql -uroot -prootpass -e "SELECT 1" 2>/dev/null && break || sleep 2; done

docker run -d --name pg-lab -e POSTGRES_PASSWORD=rootpass postgres:15
sleep 10

docker exec mysql-lab mysql -uroot -prootpass << 'EOF'
CREATE DATABASE strlab;
USE strlab;

CREATE TABLE contacts (
    id         INT NOT NULL AUTO_INCREMENT,
    first_name VARCHAR(50),
    last_name  VARCHAR(50),
    email      VARCHAR(100),
    phone      VARCHAR(30),
    city       VARCHAR(50),
    country    VARCHAR(50) DEFAULT 'US',
    notes      TEXT,
    PRIMARY KEY (id)
);

INSERT INTO contacts (first_name, last_name, email, phone, city, notes) VALUES
('  Alice  ',  'JOHNSON',  '[email protected]',  '(555) 123-4567',  'new york',    'Prefers email contact'),
('bob',        'Smith',    '[email protected]',     '555.234.5678',    'LOS ANGELES', NULL),
('Carol',      'Davis',    '[email protected]',   '555-345-6789',    'Chicago',     'VIP customer since 2020'),
('DAVID',      'WILSON',   '[email protected]',   '(555)456-7890',   'HOUSTON',     'Do not call before 9am'),
('Eve',        'MARTINEZ', '[email protected]',     '5556789012',      'Phoenix',     NULL);
EOF

Step 2: CONCAT and String Concatenation

MySQL:

PostgreSQL — || operator:

📸 Verified Output (MySQL CONCAT):


Step 3: UPPER, LOWER, and Case Normalization

📸 Verified Output:


Step 4: TRIM, LTRIM, RTRIM

📸 Verified Output:


Step 5: SUBSTRING and LENGTH

📸 Verified Output:

PostgreSQL equivalents:


Step 6: REPLACE

📸 Verified Output:


Step 7: REGEXP / Pattern Matching

MySQL — REGEXP_LIKE:

PostgreSQL — ~ operator:

📸 Verified Output (digits-only phones):


Step 8: Capstone — LPAD, RPAD, and Data Formatting

📸 Verified Output:

Cleanup:


Summary

Function
MySQL
PostgreSQL
Notes

Concatenate

CONCAT(a, b)

a || b

PG: NULL → NULL

Concatenate with sep

CONCAT_WS(sep, ...)

concat_ws(sep, ...)

Skips NULLs

Uppercase

UPPER(s)

UPPER(s)

Lowercase

LOWER(s)

LOWER(s)

Trim whitespace

TRIM(s)

TRIM(s)

Left trim

LTRIM(s)

LTRIM(s)

Right trim

RTRIM(s)

RTRIM(s)

Substring

SUBSTRING(s, pos, len)

SUBSTRING(s FROM pos FOR len)

1-indexed

Length (bytes)

LENGTH(s)

LENGTH(s)

Length (chars)

CHAR_LENGTH(s)

CHAR_LENGTH(s)

Replace

REPLACE(s, old, new)

REPLACE(s, old, new)

Case-sensitive

Regex match

REGEXP_LIKE(s, pattern)

s ~ pattern

Case-insensitive regex

REGEXP_LIKE(s, pattern, 'i')

s ~* pattern

Left pad

LPAD(s, len, char)

LPAD(s, len, char)

Right pad

RPAD(s, len, char)

RPAD(s, len, char)

Find position

LOCATE(needle, haystack)

POSITION(needle IN haystack)

Next: Lab 16 — Date and Time Functions

Last updated