Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

trifek's avatar

PostgreSQL - get first characters or integers

Hi, I have sql in pgsql: '''' select * from codes where enable= -1 order by description asc limit 100; ''''

description - it's a string.

I need sql where if first three chars is string (from description ) - them i need only this letter. If two first chars is a int - then i need this int in return.

How can i make it?

0 likes
3 replies
LaryAI's avatar
Level 58

To achieve the desired result, you can use a combination of PostgreSQL's string functions and a CASE statement to check the first characters of the description column and return the appropriate substring. Here's a query that should work for your requirements:

SELECT *,
  CASE
    WHEN SUBSTRING(description FROM 1 FOR 1) ~ '^[A-Za-z]' THEN SUBSTRING(description FROM 1 FOR 3)
    WHEN SUBSTRING(description FROM 1 FOR 1) ~ '^[0-9]' THEN SUBSTRING(description FROM 1 FOR 2)
    ELSE NULL
  END AS result
FROM codes
WHERE enable = -1
ORDER BY description ASC
LIMIT 100;

Explanation:

  • SUBSTRING(description FROM 1 FOR 1) gets the first character of the description.
  • SUBSTRING(description FROM 1 FOR 3) gets the first three characters of the description.
  • SUBSTRING(description FROM 1 FOR 2) gets the first two characters of the description.
  • The ~ operator is used to perform a regular expression match. '^[A-Za-z]' checks if the first character is a letter, and '^[0-9]' checks if the first character is a digit.
  • The CASE statement checks the first character and returns the first three characters if it's a letter or the first two characters if it's a digit.
  • The ELSE NULL part is optional and will return NULL if the first character is neither a letter nor a digit. You can adjust this to your needs.

This query will return all columns from the codes table, along with an additional column named result that contains either the first three letters or the first two digits of the description, depending on the content of the description column.

trifek's avatar

@laryai it's not workign. I have error: ERROR: current transaction is aborted, commands ignored until end of transaction block :(

Please or to participate in this conversation.