8

How do I get the ASCII value of a string as an int in PostgreSQL?

For example: the string S06.6X9A

Currently, I am using an ASCII function, but it returns only the first character of a given string.

5
  • S06.6X9A is not a single integer. Do you want it as the int array [83, 48, 54, 46, 54, 88, 57, 65]? Could you provide an example of the output you want? Commented Jun 1, 2020 at 17:34
  • Yup, I want it as the int array. For example: after converting, the expected result as: 8348544654885765 Commented Jun 1, 2020 at 19:02
  • You can use the technique in my answer and turning the table back into an array, but you're probably better off writing a function and using foreach to do it more directly. postgresql.org/docs/current/… Commented Jun 1, 2020 at 19:59
  • thanks a lot! It's really helpful for a beginner like me! Commented Jun 1, 2020 at 20:41
  • You're welcome. SQL is mind bending, but it's worth it. Good luck! Commented Jun 1, 2020 at 22:32

2 Answers 2

4

Use string_to_array('S06.6X9A', null) to split the string into a text[] of individual characters. Then unnest to turn that text[] into a table. Then use that in a from clause and run ascii() over each row.

select ascii(char)
from (
  select unnest( string_to_array('S06.6X9A', null) )
) as chars(char);

 ascii 
-------
    83
    48
    54
    46
    54
    88
    57
    65
Sign up to request clarification or add additional context in comments.

Comments

4

Simpler than Schwern's answer is:

SELECT ascii( unnest( string_to_array('S06.6X9A', NULL) ) )

1 Comment

Technically this is identical to Schwern's answer and using set returning functions in the SELECT list is discouraged though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.