Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql: reverse function of Char()

in SQL, char() converts an integer to a character (e.g., char(101) returns 'e'). What's the reverse function of char() (e.g., convert 'e' to 101)?

like image 586
Paul Avatar asked Dec 10 '22 00:12

Paul


2 Answers

ORD() or ASCII(), though they're not strictly a reverse since they will only handle the first character of the string passed in whereas CHAR() can build a string from a list of digits.

As per Michael Buen's answer it's worth noting that ORD() is MySql-only, whereas ASCII() is more widely supported but doesn't handle multi-byte characters.

mysql> SELECT CHAR(104), ASCII('h'), ORD('h');
+-----------+------------+----------+
| CHAR(104) | ASCII('h') | ORD('h') |
+-----------+------------+----------+
| h         |        104 |      104 |
+-----------+------------+----------+
like image 164
John Carter Avatar answered Dec 31 '22 03:12

John Carter


I was about to upvote BluesRockAddict's answer, but he deleted his answer, but it's the best answer, ASCII works on many platforms, e.g. SQL Server, Oracle, Postgresql, and of course MySQL

SELECT ASCII('e')

ORD works on MySQL only

http://www.sqlfiddle.com/

like image 27
Michael Buen Avatar answered Dec 31 '22 02:12

Michael Buen