0

On my PostgreSQL DB I have a table that looks like below. The description column can store a string of any size.

What I'm looking for, is a way to select just the first X chars from the content of the description column, or the whole string if X > description.length

CREATE TABLE descriptions (
    id uuid NOT NULL,
    description text NULL,
);

E.g.: If X = 100 chars and if in the description column I store a string containing 150+ chars, when I run select <some method on description> from descriptions, I just want to get back the first 100 chars from the description column.

Bonus if the approach proposed is extremely fast!

Ken White
  • 123,280
  • 14
  • 225
  • 444
Yonoss
  • 1,242
  • 5
  • 25
  • 41
  • I can create a second column to store the short version, but I don't feel like duplicating data – Yonoss Nov 12 '22 at 23:43

1 Answers1

0

Use a type cast or use substring():

SELECT CAST(description AS varchar(100)), substring(description for 100)
FROM descriptions;

Or if you want to do it the "PostgreSQL way":

SELECT description::varchar(100), substr(description, 1, 100)
FROM descriptions;
xehpuk
  • 7,814
  • 3
  • 30
  • 54