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 Single and Composite Indexes for Real Queries

MariaDB Tutorial / Design Single and Composite Indexes for Real Queries

Inspect existing keys, create a customer–time composite index and review leading columns, covering access and foreign-key dependencies. Preserve query results while evaluating read, write and storage costs.

MariaDB Tutorial / Choose String Types: CHAR, VARCHAR, and TEXT

MariaDB Tutorial / Choose String Types: CHAR, VARCHAR, and TEXT

Compare CHAR, VARCHAR, and TEXT with runnable Unicode and trailing-space examples. Check character counts versus byte counts, length errors, comparison rules, and the optional TEXT(M) syntax.

MariaDB Tutorial / Summarize Rows with COUNT, SUM, AVG, MIN, and MAX

MariaDB Tutorial / Summarize Rows with COUNT, SUM, AVG, MIN, and MAX

Calculate and reconcile product counts, known-value counts, stock totals, averages and price bounds. Understand empty-input results and why the order of row calculations and aggregation matters.

MariaDB Tutorial / Build and Reconcile Monthly Sales, Customer Totals, and Unsold Products

MariaDB Tutorial / Build and Reconcile Monthly Sales, Customer Totals, and Unsold Products

Create three related MariaDB reports from one order fixture, retain nonbuyers and find products without paid sales. Reconcile monthly and customer amounts and inspect join, status and date boundaries.

MariaDB Tutorial / Connect with the Command-Line Client and Run SQL Files

MariaDB Tutorial / Connect with the Command-Line Client and Run SQL Files

Connect to MariaDB with explicit TCP and UTF-8 settings, check account and query results, and execute a complete SQL file with SOURCE. Learn how to diagnose path, encoding, and partial-execution errors.

MariaDB Tutorial / Compare ROW_NUMBER, RANK, and DENSE_RANK

MariaDB Tutorial / Compare ROW_NUMBER, RANK, and DENSE_RANK

Compare ROW_NUMBER, RANK and DENSE_RANK on customer totals, then run regional rankings and an outer top-N filter. Check how a row limit differs from retaining tied ranks.

MariaDB Tutorial / Improve Date Filters, Sorting, and Pagination Without Changing Results

MariaDB Tutorial / Improve Date Filters, Sorting, and Pagination Without Changing Results

Compare equivalent date predicates and deterministic keyset pagination in MariaDB. Preserve exact results, account for version-specific DATE/YEAR optimization and review projection and search semantics.

MariaDB Tutorial / Change Table Structure Safely with ALTER TABLE

MariaDB Tutorial / Change Table Structure Safely with ALTER TABLE

Practice an add-fill-constrain migration with a product SKU column, verify counts and rejected duplicates, and review metadata locks, online-change limits and recovery boundaries.

MariaDB Tutorial / Restore a Backup into a Separate Database and Verify It

MariaDB Tutorial / Restore a Backup into a Separate Database and Verify It

Review a SQL dump, restore it into a verified empty database and compare object definitions, rows and goods totals. Handle source-file errors, compatibility and partial-restoration states explicitly.

MariaDB Tutorial / Store Dates and Times with DATE, DATETIME, and TIMESTAMP

MariaDB Tutorial / Store Dates and Times with DATE, DATETIME, and TIMESTAMP

Choose DATE, DATETIME, or TIMESTAMP by the meaning of a time value. Run a controlled time-zone comparison, check version-dependent limits and invalid dates, and restore the original session settings.