Open In App

HEX() function in MySQL

Last Updated : 04 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

HEX() :

This function in MySQL is used to return an equivalent hexadecimal string value of a string or numeric Input. If the input is a string then each byte of each character in the string is converted to two hexadecimal digits. This function also returns a hexadecimal string representation of the numeric argument N treated as a longlong (BIGINT) number.  

Syntax :

HEX(string)
OR
HEX(N)

Parameter : 

This method accepts only one parameter.

  • string - Input string who's each character is to be converted to two hexadecimal digits.
  • N - Input number which is to be converted to hexadecimal.

Returns : 

It returns an equivalent hexadecimal string representation of a string or numeric Input.

Example-1 :

Hexadecimal representation of the decimal number 0 using HEX Function as follows.

SELECT HEX(0) AS Hex_number ;

Output :

HEX_NUMBER
0

Example-2 :

Hexadecimal representation of the decimal number 2020 using HEX Function as follows.

SELECT HEX( 2020 ) AS Hex_number ;

Output :

HEX_NUMBER
7E4

Example -3 :

Hexadecimal representation of the string 'geeksforgeeks' using HEX Function as follows.

SELECT HEX( 'geeksforgeeks') AS Hex_string ;

Output :

HEX_STRING
 6765656B73666F726765656B73

Example-4 :

Using HEX Function to find a hexadecimal representation of all decimal numbers present in a column as follows. 

Creating a Player table :

CREATE TABLE Player(

Player_id INT AUTO_INCREMENT,  
Player_name VARCHAR(100) NOT NULL,
Playing_team VARCHAR(20) NOT NULL,
Highest_Run_Scored INT NOT NULL,
PRIMARY KEY(Player_id )

);

Inserting data into the Table :

INSERT INTO  
Player(Player_name, Playing_team, Highest_Run_Scored)
VALUES
('Virat Kohli', 'RCB', 60 ),
('Rohit Sharma', 'MI', 45),
('Dinesh Karthik', 'KKR', 26 ),
('Shreyash Iyer', 'DC', 40 ),
('David Warner', 'SRH', 65),
('Steve Smith', 'RR', 52 ),
('Andre Russell', 'KKR', 70),
('Jasprit Bumrah', 'MI', 10),
('Risabh Panth', 'DC', 34 ) ;

To verify use the following command as follows.

SELECT * FROM Player;

Output :

PLAYER_IDPLAYER_NAMEPLAYING_TEAMHIGHEST_RUN_SCORED
1Virat KohliRCB60
2Rohit SharmaMI45
3Dinesh KarthikKKR26
4Shreyash IyerDC40
5David WarnerSRH65
6Steve SmithRR52
7Andre RussellKKR70
8Jasprit BumrahMI10
9Risabh PanthDC34

Now, we will find the highest run scored by each player in hexadecimal using the HEX Function.

SELECT  
Player_id, Player_name,
Playing_team, HEX(HIGHEST_RUN_SCORED) AS HighestRunInHexaDecimal
FROM Player ;

Output :

PLAYER_IDPLAYER_NAMEPLAYING_TEAMHighestRunInHexaDecimal
1Virat KohliRCB3C
2Rohit SharmaMI2D
3Dinesh KarthikKKR1A
4Shreyash IyerDC28
5David WarnerSRH41
6Steve SmithRR34
7Andre RussellKKR46
8Jasprit BumrahMIA
9Risabh PanthDC22

Next Article
Article Tags :

Similar Reads