What are MariaDB Miscellaneous & Network Functions?
MariaDB miscellaneous functions cover a range of utility operations that do not fit into other categories. UUID() generates a UUID v1 value (time-based, unlike PostgreSQL's gen_random_uuid() which is v4). INET_ATON() and INET_NTOA() convert between IPv4 address strings and their integer representation. GET_LOCK() and RELEASE_LOCK() implement named application-level locks similar to PostgreSQL's advisory locks. SLEEP() introduces a delay in seconds and is useful for testing lock timeouts.
UUID
MariaDB 5.5+→ VARCHAR(36)
Generates a universally unique identifier (UUID) based on RFC 4122 version 1 (time-based).
UUID() generates a v1 UUID derived from timestamp and MAC address; output is non-random but globally unique.
⇄ vs PostgreSQL: PostgreSQL uses gen_random_uuid() (pgcrypto or built-in in 13+) for UUID v4 (random); uuid-ossp extension provides uuid_generate_v1() for v1.
Alias for MASTER_POS_WAIT() introduced for naming consistency; blocks until the replica has applied events up to the specified binlog file and position.
Returns the given value while assigning a specific column name to it in the result set; primarily used internally by stored procedures for replication.
Signature
NAME_CONST(name, value)
Parameters
Parameter
Type
Description
name
VARCHAR
Column name to assign in the result set
value
any literal
Constant literal value to return (must be a literal, not an expression or column reference)
Examples
Integer with custom name
sql
SELECTNAME_CONST('my_col', 42);
→-- Column named 'my_col' with value 42
String value
sql
SELECTNAME_CONST('greeting', 'Hello');
→-- Column 'greeting' = 'Hello'
Decimal value
sql
SELECTNAME_CONST('pi_approx', 3.14159);
→-- Column 'pi_approx' = 3.14159
Boolean value
sql
SELECTNAME_CONST('flag', TRUE);
→-- Column 'flag' = 1
NULL value
sql
SELECTNAME_CONST('empty', NULL);
→-- NULL
⚠Anti-Pattern— Using NAME_CONST with non-literal expressions
NAME_CONST requires its second argument to be a constant literal; passing a function call or column reference causes an error.
✓ Instead: Use a subquery with AS alias syntax: SELECT expr AS col_name FROM ...
example
SELECTNAME_CONST('greeting', 'Hello');
→'Hello' — alias as 'greeting' in result column
◆MariaDB Note
Mainly used in CREATE PROCEDURE binlog events to preserve parameter names for replication; not intended for general query use.
⇄ vs PostgreSQL: No equivalent in PostgreSQL; use AS alias in SELECT.
CONVERT
MariaDB 5.5+→ Varies (depends on target type)
Converts a value to a specified data type, or converts a string's character set using the USING clause.
Signatures
CONVERT(expr, type)
CONVERT(expr USING charset_name)
Parameters
Parameter
Type
Description
expr
any
Value or expression to convert
type
type keyword
Target data type (e.g., CHAR, SIGNED, UNSIGNED, DECIMAL, DATE, DATETIME, BINARY)
charset_name
VARCHAR
Target character set name when using USING clause (e.g., utf8mb4, latin1)
Examples
String to integer
sql
SELECTCONVERT('42', SIGNED);
→-- 42
Float to unsigned int (rounds)
sql
SELECTCONVERT(3.7, UNSIGNED);
→-- 4
String to DATE
sql
SELECTCONVERT('2024-01-15', DATE);
→-- 2024-01-15
Character set conversion
sql
SELECTCONVERT('hello'USINGutf8mb4);
→-- 'hello' in utf8mb4
NULL handling
sql
SELECTCONVERT(NULL, CHAR);
→-- NULL
⚠Anti-Pattern— Using CONVERT for locale-sensitive formatting
CONVERT does not apply locale-specific number or date formatting; it performs type casting only.
✓ Instead: Use FORMAT() for locale-aware number formatting or DATE_FORMAT() for date string formatting.
example
SELECTCONVERT('café'USINGutf8mb4);
→'café' in utf8mb4 encoding
◆MariaDB Note
CONVERT(expr, type) and CAST(expr AS type) are equivalent for type conversion; CONVERT USING is unique to CONVERT.
⇄ vs PostgreSQL: PostgreSQL uses expr::type syntax or CAST(expr AS type); character set conversion uses convert(bytea, name, name) or client_encoding settings.
In an INSERT ... ON DUPLICATE KEY UPDATE statement, returns the value that would have been inserted into the specified column (the new value, not the existing one).
Signature
VALUES(col_name)
Parameters
Parameter
Type
Description
col_name
column reference
Name of the column whose prospective INSERT value you want to reference in the ON DUPLICATE KEY UPDATE clause
The VALUES() function approach works in all MariaDB versions supporting ON DUPLICATE KEY UPDATE; the new_row alias (MariaDB 10.3.3+) is preferred for readability.
⇄ vs PostgreSQL: PostgreSQL uses INSERT ... ON CONFLICT DO UPDATE SET col = EXCLUDED.col (EXCLUDED pseudo-table alias, not VALUES()).
Adds two vectors element-wise. Both vectors must have the same number of dimensions. Returns a new vector where each element is the sum of the corresponding elements of the input vectors. Core building block for AI/ML vector arithmetic in the database.
Signature
VEC_ADD(vec1, vec2) → VECTOR
Parameters
Parameter
Type
Description
vec1
VECTOR / JSON array string
First input vector; must match vec2 in dimension count
vec2
VECTOR / JSON array string
Second input vector; must match vec1 in dimension count
⚠Anti-Pattern— Adding vectors of mismatched dimensions
VEC_ADD requires both operands to have the same number of dimensions. Passing vectors of different lengths raises an error at runtime and there is no automatic padding.
✓ Instead: Always validate that vectors stored in the same column share a consistent dimension count — use a CHECK constraint or application-layer validation when inserting embeddings.
To compute the centroid of a cluster of vectors, accumulate VEC_ADD across all rows and then divide each element by the count. This lets you keep centroid arithmetic inside SQL without exporting data to Python.
example
SELECTVEC_ADD(v1, VEC_ADD(v2, v3)) FROM (SELECT'[1,0]'v1, '[0,1]'v2, '[1,1]'v3) t;
→-- [2,2]
◆MariaDB Note
Part of the native VECTOR data type system introduced in MariaDB 11.7. Vectors are stored as fixed-length binary blobs of 32-bit floats internally.
⇄ vs MySQL: MySQL has no native vector arithmetic functions; this is a MariaDB 11.7+ feature.
⇄ vs PostgreSQL: PostgreSQL (with pgvector extension) supports the + operator for vector addition: embedding1 + embedding2.
Computes the cosine distance between two vectors. Cosine distance = 1 − cosine similarity. Range is [0, 2]: 0 means identical direction (most similar), 1 means orthogonal (unrelated), 2 means exactly opposite direction. Widely used in semantic search, recommendation systems, and NLP embedding comparisons.
Signature
VEC_COSINE_DISTANCE(vec1, vec2) → DOUBLE
Parameters
Parameter
Type
Description
vec1
VECTOR / JSON array string
First input vector
vec2
VECTOR / JSON array string
Second input vector; must match vec1 in dimension count
Parallel vectors (same direction, different magnitude) → distance 0
sql
SELECTVEC_COSINE_DISTANCE('[1,2,3]', '[2,4,6]');
→-- 0
⚠Anti-Pattern— Using cosine distance on zero vectors
A zero vector [0,0,...,0] has no direction; cosine distance is mathematically undefined (division by zero in the denominator). MariaDB may return NULL or raise an error.
✓ Instead: Filter out zero vectors before computing cosine distance, or use VEC_EUCLIDEAN_DISTANCE as a fallback for degenerate cases.
When all stored vectors are pre-normalized to unit length (via VEC_NORMALIZE at insert time), cosine distance reduces to 1 − dot product. This means VEC_DOT_PRODUCT on unit vectors is equivalent and may use SIMD optimizations more effectively.
Computes the dot product (inner product) of two vectors. The dot product is the sum of the element-wise products: Σ(vec1[i] × vec2[i]). A higher positive value indicates vectors pointing in the same direction with large magnitudes; 0 indicates orthogonality. When both vectors are unit-normalized, the dot product equals cosine similarity.
Signature
VEC_DOT_PRODUCT(vec1, vec2) → DOUBLE
Parameters
Parameter
Type
Description
vec1
VECTOR / JSON array string
First input vector
vec2
VECTOR / JSON array string
Second input vector; must match vec1 in dimension count
Examples
1×4 + 2×5 + 3×6 = 4+10+18 = 32
sql
SELECTVEC_DOT_PRODUCT('[1,2,3]', '[4,5,6]');
→-- 32
Orthogonal unit vectors → 0
sql
SELECTVEC_DOT_PRODUCT('[1,0,0]', '[0,1,0]');
→-- 0
Unit vector dot itself = 1 (its squared magnitude)
⚠Anti-Pattern— Using dot product without normalization for similarity ranking
Raw dot product favors high-magnitude vectors regardless of direction. A vector [100,100] will outscore [1,1] even if both point in the same direction relative to the query.
✓ Instead: Normalize vectors with VEC_NORMALIZE before storing, or use VEC_COSINE_DISTANCE which accounts for magnitude internally.
If you normalize all embeddings to unit length when inserting (using VEC_NORMALIZE), then VEC_DOT_PRODUCT gives you cosine similarity directly — without the overhead of computing magnitudes at query time. This is the standard trick used by vector databases for fast similarity ranking.
Computes the Euclidean (L2) distance between two vectors. This is the straight-line distance in high-dimensional space: √(Σ(vec1[i] − vec2[i])²). Lower values indicate higher similarity. Standard metric for image similarity, clustering (k-means), and anomaly detection.
Signature
VEC_EUCLIDEAN_DISTANCE(vec1, vec2) → DOUBLE
Parameters
Parameter
Type
Description
vec1
VECTOR / JSON array string
First input vector
vec2
VECTOR / JSON array string
Second input vector; must match vec1 in dimension count
⚠Anti-Pattern— Using Euclidean distance for text embeddings from language models
Language model embeddings (BERT, OpenAI, etc.) are designed for cosine similarity, not Euclidean distance. High-dimensional text embeddings have nearly equal L2 norms, but the direction (angle) carries the semantic meaning.
✓ Instead: Use VEC_COSINE_DISTANCE for text/NLP embeddings; reserve VEC_EUCLIDEAN_DISTANCE for image features, tabular numeric embeddings, or models explicitly trained with L2 distance.
Euclidean distance ranking is equivalent to squared-distance ranking because √ is monotone. If your DB optimizer does not inline the SQRT, computing (a-b)² per element and summing (done outside MariaDB) avoids the square root entirely. For MariaDB's VEC_EUCLIDEAN_DISTANCE the computation is already vectorized internally, so just use the function directly.
A VECTOR INDEX on the embedding column will use approximate nearest-neighbor (ANN) algorithms to accelerate ORDER BY VEC_EUCLIDEAN_DISTANCE(...) LIMIT N queries.
⇄ vs MySQL: MySQL 9.0+ uses DISTANCE(v1, v2, 'EUCLIDEAN'); MariaDB uses VEC_EUCLIDEAN_DISTANCE().
⇄ vs PostgreSQL: pgvector uses the <-> operator for L2 distance: embedding1 <-> embedding2.
Normalizes a vector to unit length (L2 norm = 1) by dividing each element by the vector's magnitude. The result lies on the unit hypersphere. Useful as a preprocessing step before cosine similarity comparisons, since normalized dot products equal cosine similarity.
A zero vector [0,0,...,0] has magnitude 0; dividing by zero is undefined. VEC_NORMALIZE will return NULL or raise an error for a zero vector.
✓ Instead: Guard against zero vectors: WHERE VEC_EUCLIDEAN_DISTANCE(embedding, '[0,0,0]') > 0, or handle the NULL result downstream with COALESCE.
If you normalize embeddings when inserting rows, every query-time similarity computation becomes a cheap dot product on pre-normalized vectors. Normalizing at query time means repeating the same division for every row scanned — normalize once, query many times.
The result is a VECTOR of the same dimension with L2 norm = 1. Useful as a DEFAULT expression or GENERATED COLUMN: embedding_norm VECTOR(768) AS (VEC_NORMALIZE(embedding)) STORED.
⇄ vs MySQL: MySQL 9.0+ has no VEC_NORMALIZE equivalent; normalize externally before inserting.
⇄ vs PostgreSQL: pgvector does not have a normalize function; normalize in application code (e.g., numpy) before inserting, or use the l2_normalize() function added in pgvector 0.5.0.
Full-text search operator. MATCH(col1, col2, ...) specifies the columns to search (which must have a FULLTEXT index); AGAINST(expr [mode]) specifies the search expression and optional search mode. Returns a floating-point relevance score — higher means a stronger match. Three modes are supported: NATURAL LANGUAGE MODE (default, rank by relevance), BOOLEAN MODE (supports +, -, *, " operators), and WITH QUERY EXPANSION (two-pass: find matches, expand with related terms, re-rank).
Signatures
MATCH(col1 [, col2, ...]) AGAINST (expr) → DOUBLE
MATCH(col1 [, col2, ...]) AGAINST (expr IN NATURAL LANGUAGE MODE) → DOUBLE
MATCH(col1 [, col2, ...]) AGAINST (expr IN BOOLEAN MODE) → DOUBLE
MATCH(col1 [, col2, ...]) AGAINST (expr WITH QUERY EXPANSION) → DOUBLE
Parameters
Parameter
Type
Description
col1, col2, ...
TEXT / VARCHAR columns
Columns to search; must be covered by a FULLTEXT index, listed in the same order as in the index definition
expr
VARCHAR / string literal
The search string or Boolean expression
mode
keyword
Optional: IN NATURAL LANGUAGE MODE (default), IN BOOLEAN MODE, or WITH QUERY EXPANSION
⚠Anti-Pattern— Running MATCH...AGAINST without a FULLTEXT index
Without a FULLTEXT index on the searched columns, MariaDB falls back to a full table scan and may even return an error in strict mode. Performance degrades catastrophically on large tables.
✓ Instead: Always create a FULLTEXT index first: ALTER TABLE articles ADD FULLTEXT INDEX ft_idx (title, body); — and list the columns in MATCH() in the same order as in the index.
When you use an identical MATCH...AGAINST expression in both the WHERE clause and the SELECT list, MariaDB's optimizer evaluates the full-text index only once and reuses the score — there is no double computation penalty. Always put the filtering condition in WHERE to activate the FULLTEXT index.
Works with MyISAM and InnoDB FULLTEXT indexes. MariaDB also supports the Mroonga storage engine for Japanese/CJK full-text search. The minimum word length is controlled by ft_min_word_len (MyISAM) or innodb_ft_min_token_size (InnoDB), defaulting to 4.
⇄ vs MySQL: Identical syntax and behavior in MySQL 5.6+. MySQL's InnoDB FULLTEXT index behavior matches MariaDB's in most respects; MariaDB adds Mroonga storage engine as an alternative full-text backend.
⇄ vs PostgreSQL: PostgreSQL uses tsvector / tsquery types with the @@ operator: to_tsvector('english', body) @@ plainto_tsquery('english', 'search term'). The ts_rank() function provides relevance scoring. No MATCH...AGAINST syntax.