Lesson

MySQL CONV() Function

10 min reading
Free Course

MySQL CONV() Function

The MySQL CONV() function converts a number from one numeral base (from_base) into another (to_base) and returns the result as a string. It supports any base between 2 and 36, covering binary, octal, decimal, and hexadecimal conversions.

Syntax

CONV(N, from_base, to_base)
  • N: The integer or string representation of the number to convert.
  • from_base: Source base as an integer from 2 to 36.
  • to_base: Target base as an integer from 2 to 36 (or -2 to -36 for signed output).

MySQL internally computes the conversion using 64-bit integer precision (BIGINT), and uses letters A through Z for digits above 9.

Practical Example

Suppose demo_products stores hardware color codes or device IDs in decimal, and you want hexadecimal and binary representations for an engineering export.

SELECT
    product_id,
    product_name,
    CONV(product_id, 10, 16) AS hex_id,
    CONV(product_id, 10, 2) AS binary_id
FROM demo_products
WHERE product_id IN (15, 255, 1024);
product_id product_name hex_id binary_id
15 Smart Sensor F 1111
255 LED Strip FF 11111111
1024 Network Switch 400 10000000000

Common Mistakes & NULL Behavior

  • NULL and out-of-range bases: CONV() returns NULL if any argument is NULL, or if abs(from_base) or abs(to_base) is outside 2..36.
  • Signed vs unsigned negative numbers: If to_base is positive (e.g., 16), CONV(-10, 10, 16) formats -10 as an unsigned 64-bit value (FFFFFFFFFFFFFFF6). Pass a negative to_base like CONV(-10, 10, -16) to get '-A'.
  • Leading invalid characters: CONV('1Z', 16, 10) stops parsing at 'Z' (not a valid base-16 digit) and converts only '1', returning '1' instead of an error.
  • 64-bit overflow: Values exceeding unsigned 64-bit BIGINT (18446744073709551615) clamp to the maximum 64-bit value rather than raising an error.

Frequently Asked Questions

How do I convert hex to decimal in MySQL?

Call CONV(hex_str, 16, 10). For example, CONV('FF', 16, 10) returns '255'.

Why does CONV(-1, 10, 16) return 16 F characters?

Because a positive to_base formats values as unsigned 64-bit integers. Pass -16 as to_base (CONV(-1, 10, -16)) to preserve the minus sign and return '-1'.

What data type does CONV() return?

CONV() always returns a string (VARCHAR), even when to_base is 10. Cast to UNSIGNED or SIGNED if you need arithmetic sorting.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum