Introduction to String Functions
Learn about pattern matching and comparison of strings in MySQL.
We'll cover the following...
MySQL provides data types with five categories of data: numeric, date and time, string, spatial, and JSON. Out of the eight distinct data types for strings, TEXT
is one that we already use in our running example for representing the names of parts for car models:
-- Generate a table for sample car model parts.DROP TABLE IF EXISTS CarPart;CREATE TABLE CarPart(model INT,name TEXT,built_at DATE DEFAULT NULL,PRIMARY KEY (model, name(256)),FOREIGN KEY (model) REFERENCES CarModel (id));-- Inspect the properties of the table for car parts.DESCRIBE CarPart;
As we can observe, CarPart
has three columns, model
, name
, and built_at
, of which the second represents the name of a car part using the data type TEXT
. If we filter for specific car parts, e.g., 'exterior'
, it might feel intuitive to use the comparison operator =
on the column name
:
-- Retrieve all exterior car parts.SELECT *FROM CarPartWHERE name = 'exterior';
While the comparison operator =
is sufficient in this case, matching strings based on criteria other than equality is not possible with this operator. Referring to other programming languages like JavaScript or Python, we know that the comparison operator =
evaluates its operands based on strict ...