Open In App

HEX() function in MySQL

Improve
Improve
Like Article
Like
Save
Share
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_ID PLAYER_NAME PLAYING_TEAM HIGHEST_RUN_SCORED
1 Virat Kohli RCB 60
2 Rohit Sharma MI 45
3 Dinesh Karthik KKR 26
4 Shreyash Iyer DC 40
5 David Warner SRH 65
6 Steve Smith RR 52
7 Andre Russell KKR 70
8 Jasprit Bumrah MI 10
9 Risabh Panth DC 34

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_ID PLAYER_NAME PLAYING_TEAM HighestRunInHexaDecimal
1 Virat Kohli RCB 3C
2 Rohit Sharma MI 2D
3 Dinesh Karthik KKR 1A
4 Shreyash Iyer DC 28
5 David Warner SRH 41
6 Steve Smith RR 34
7 Andre Russell KKR 46
8 Jasprit Bumrah MI A
9 Risabh Panth DC 22

Last Updated : 04 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads