0
0
MysqlHow-ToBeginner · 3 min read

How to Use CONV Function in MySQL: Syntax and Examples

In MySQL, the CONV() function converts a number from one base to another base. You provide the number as a string, the base it is currently in, and the base you want to convert it to, like CONV('a', 16, 10) to convert hexadecimal 'a' to decimal 10.
📐

Syntax

The CONV() function syntax is:

  • CONV(number, from_base, to_base)

where:

  • number: The number as a string to convert.
  • from_base: The base of the input number (between 2 and 36).
  • to_base: The base to convert the number to (between 2 and 36).

The function returns the converted number as a string.

sql
CONV(number, from_base, to_base)
💻

Example

This example converts the hexadecimal number '1a' to decimal, binary, and octal bases.

sql
SELECT 
  CONV('1a', 16, 10) AS decimal_value,
  CONV('1a', 16, 2) AS binary_value,
  CONV('1a', 16, 8) AS octal_value;
Output
decimal_value | binary_value | octal_value ------------- | ------------ | ----------- 26 | 11010 | 32
⚠️

Common Pitfalls

Common mistakes when using CONV() include:

  • Passing a number instead of a string for the number argument, which can cause unexpected results.
  • Using bases outside the allowed range (2 to 36), which returns NULL.
  • Confusing the input base and output base order.

Always provide the number as a string and verify base values.

sql
/* Wrong: number as integer */
SELECT CONV(10, 10, 2);

/* Right: number as string */
SELECT CONV('10', 10, 2);
Output
/* Wrong returns NULL or unexpected result depending on MySQL version */ /* Right returns '1010' */
📊

Quick Reference

ParameterDescriptionAllowed Values
numberNumber to convert (as string)Any valid number string in from_base
from_baseBase of the input number2 to 36
to_baseBase to convert the number to2 to 36

Key Takeaways

Use CONV() to convert numbers between bases by specifying the number as a string and the from/to bases.
Both from_base and to_base must be between 2 and 36, or CONV() returns NULL.
Always pass the number argument as a string to avoid unexpected results.
CONV() returns the converted number as a string, not a numeric type.