AD JB Toolbox 01 EN

MariaDB Tutorial / Join, Extract, Replace, and Measure Strings

String functions join, extract, replace or measure text to produce query results. Choose CONCAT, SUBSTRING, REPLACE and CHAR_LENGTH according to the task, and distinguish NULL handling and character counts from byte counts before changing the meaning of the original data.

Choose a function for the transformation

Combining a name and category, extracting part of a code and removing telephone separators are different transformations. Calling a string function in SELECT calculates an output value; it does not automatically update a stored name. Decide what should remain original data and what belongs only in a display. Check the input column’s storage rules in Choose String Types: CHAR, VARCHAR, and TEXT and the missing-value semantics in Compare NULL Correctly with IS NULL and COALESCE when transforming text.

Function Purpose Important behavior
CONCAT Join strings In ordinary mode, a NULL argument makes the result NULL
CONCAT_WS Join with a separator Skips NULL arguments but keeps empty strings
SUBSTRING Extract by position and length The first character is at position 1
REPLACE Replace matching substrings Distinct from the data-changing REPLACE statement
CHAR_LENGTH / LENGTH Count characters / bytes Different for multibyte text

Check the MariaDB documentation for the syntax and conditions used here: mariadb string functions guide, substring.

Build display labels from the practice data

Connect to the learning server as course_user and select shopcourse. The command-line and UTF-8 SQL-file guide explains how to save the code as a UTF-8 file and execute it with SOURCE C:/mariadb-lab/lesson.sql;, replacing the path with the actual file. Run SQL inside the MariaDB client, rather than at the operating-system prompt.

Check SELECT VERSION(), DATABASE(); and SHOW TABLES; before creating products_19_lab. These names belong only to this exercise. If they exist, inspect their definitions and rows first; remove them only when you have established that they are disposable exercise objects. Do not replace existing application tables.

USE shopcourse;
CREATE TABLE products_19_lab (
  product_id INT NOT NULL AUTO_INCREMENT,
  product_name VARCHAR(100) NOT NULL,
  category VARCHAR(30) NOT NULL,
  price DECIMAL(10,2) NOT NULL,
  stock INT NOT NULL DEFAULT 0,
  note VARCHAR(100) NULL DEFAULT NULL,
  PRIMARY KEY (product_id),
  CONSTRAINT ck_p19_price CHECK (price >= 0),
  CONSTRAINT ck_p19_stock CHECK (stock >= 0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO products_19_lab (product_id,product_name,category,price,stock,note) VALUES (1, '노트', '문구', 3500.00, 20, NULL),
  (2, '볼펜', '문구', 1500.00, 0, ''),
  (3, '머그컵', '생활', 8000.00, 12, '선물 포장'),
  (4, '스탠드', '생활', 25000.00, 5, NULL),
  (5, '파일', '문구', 1500.00, 50, ''),
  (6, '케이블', '전자', 8000.00, 0, '호환 확인');

The SQL retains the original Korean sample strings to exercise UTF-8 consistently. Product identifiers 1–6 represent a notebook, pen, mug, lamp, folder and cable; their category strings mean stationery, household and electronics. Enter the string literals as shown, use the identifiers when comparing results, and save the file with UTF-8 encoding.

The notes contain both NULL and empty strings. Compare the NULL and empty-string examples when choosing a missing-value display policy.

SELECT product_id, CONCAT(product_name,' / ',category) AS label,
 CONCAT_WS(' / ',product_name,note) AS note_label
FROM products_19_lab ORDER BY product_id;

For product 1, label combines the notebook and stationery strings with a slash, while note_label contains only its name because CONCAT_WS skips the NULL note. Product 2 has an empty note, so its separator remains. Do not rewrite empty notes as NULL merely to remove an unwanted separator; first decide the intended display rule.

Extract by character position and replace separators

SELECT SUBSTRING('MariaDB',1,5), SUBSTRING('MariaDB',-2);
SELECT REPLACE('010-1234-5678','-','') AS normalized_phone;

The results are Maria, DB and 01012345678. SUBSTRING starts at position 1, not zero, and a negative position counts from the end. Its positions refer to characters, making it suitable for multibyte strings too. Establish that a business code really has a fixed positional structure before cutting it apart.

REPLACE calculates a substituted string here. Converting the resulting telephone string to a number could lose a leading zero, country-code information or extensions. Normalizing an identifier requires more than deleting punctuation.

Compare characters with UTF-8 bytes

SELECT CHAR_LENGTH('한글'), LENGTH('한글'),
 CHAR_LENGTH('🙂'), LENGTH('🙂');

With utf8mb4 input and connection handling, the Korean sample contains two characters and six bytes; the emoji is one character and four bytes. A visually single symbol can also consist of multiple code points, so CHAR_LENGTH does not universally count user-perceived glyph clusters.

A 100-character input rule and a 100-byte storage or network limit are different requirements. The string-type and length discussion explains the storage context. Arbitrarily cutting UTF-8 bytes can produce an invalid sequence.

Keep NULL, empty text and trimming policies separate

SELECT CONCAT('노트',NULL),
 CONCAT_WS(' / ','노트',NULL,'');
SELECT CONCAT('[',TRIM('  노트  '),']');

The first CONCAT result is NULL. CONCAT_WS retains the empty string and therefore a trailing separator. TRIM removes the ordinary surrounding spaces in this example, leaving the Korean notebook name inside brackets. It does not universally remove every Unicode whitespace character or interior space. Names and passwords may contain meaningful spaces.

Collation affects comparisons involving case, accents and trailing spaces. If those distinctions matter, inspect the type and collation together rather than assume a different string function fixes the comparison policy.

Compare original and transformed values before updating

Display the primary key, original value and calculated value side by side. For unexpectedly short output, check position and length; for NULL output, check each argument; for garbled Korean text, check file and connection encoding. Validate a transformation with SELECT and use a recoverable change procedure before applying it through UPDATE.

Before repeating the exercise, inspect the selected database, actual table definitions and stored rows, and back up anything that must be kept. Drop only this article’s disposable practice objects, with child tables before their referenced parents. DROP TABLE removes both definitions and rows and cannot be undone by an ordinary ROLLBACK; keep cleanup separate from transaction experiments.

DROP TABLE shopcourse.products_19_lab;
More in This Category
MariaDB Tutorial / Design Table Relationships with Keys and Foreign Keys

MariaDB Tutorial / Design Table Relationships with Keys and Foreign Keys

Build and inspect customer, product, order and item tables with foreign keys. Verify one-to-many links, reject missing parents and choose deliberate deletion and historical-price policies.

MariaDB Tutorial / What MariaDB Is: Databases, SQL, and Its Relationship to MySQL

MariaDB Tutorial / What MariaDB Is: Databases, SQL, and Its Relationship to MySQL

Understand the roles of the MariaDB server and client, the structure of relational data, and the purpose of SQL. Learn how MariaDB relates to MySQL and prepare for a small product-database exercise.

MariaDB Tutorial / Check Target Rows Before UPDATE and DELETE

MariaDB Tutorial / Check Target Rows Before UPDATE and DELETE

Inspect and lock precise target rows, verify UPDATE and DELETE results, and roll back independent InnoDB exercises. Understand affected-row counts, connection requirements and recovery boundaries.

MariaDB Tutorial / Create a Database with CREATE DATABASE, USE, and utf8mb4

MariaDB Tutorial / Create a Database with CREATE DATABASE, USE, and utf8mb4

Create a practice database with explicit utf8mb4 settings and verify its definition. Understand connection-local database selection, collation comparisons, and why IF NOT EXISTS preserves existing defaults.

MariaDB Tutorial / Combine Query Results with UNION and UNION ALL

MariaDB Tutorial / Combine Query Results with UNION and UNION ALL

Stack compatible customer-query results, compare UNION with UNION ALL and observe how source labels change duplicate detection. Check column meaning, result types and ordering scope.

MariaDB Tutorial / Filter Rows with WHERE, AND, OR, IN, BETWEEN, and LIKE

MariaDB Tutorial / Filter Rows with WHERE, AND, OR, IN, BETWEEN, and LIKE

Build clear MariaDB filters using comparisons, grouped AND/OR conditions, IN lists, inclusive ranges and escaped LIKE patterns. Check expected product IDs and investigate missing or extra rows.

MariaDB Tutorial / Build a Local MariaDB Lab with Docker Compose

MariaDB Tutorial / Build a Local MariaDB Lab with Docker Compose

Configure a local MariaDB container with Compose, file-based secrets, a healthcheck, and a named volume. Verify connections and distinguish container replacement from deleting persistent data.

MariaDB Tutorial / Select Columns, Aliases, Calculations, and DISTINCT

MariaDB Tutorial / Select Columns, Aliases, Calculations, and DISTINCT

Read explicit columns, label results with AS, calculate per-product stock values and understand how DISTINCT treats complete row combinations. Compare expected values and troubleshoot aliases and filters.

MariaDB Tutorial / Compare Isolation Levels, Locks, and Deadlocks with Two Connections

MariaDB Tutorial / Compare Isolation Levels, Locks, and Deadlocks with Two Connections

Follow explicit A/B steps to compare isolation, row-lock waits and deadlocks. Complete blocks cover resetting values, rereading, cleaning up failures and restoring each connection’s settings.

MariaDB Tutorial / Compare NULL Correctly with IS NULL and COALESCE

MariaDB Tutorial / Compare NULL Correctly with IS NULL and COALESCE

Distinguish NULL from empty strings and zero, filter missing notes with IS NULL, choose COALESCE fallbacks and avoid NULL-related NOT IN surprises using reproducible product queries.