Answer the question
In order to leave comments, you need to log in
[PostgreSQL] How to cast strings to INT and other data types?
Good day dear!
There is a PostgreSQL database, mixed values are stored in one of the tables (that is, there can be both text and numbers, and anything else), the field format is VARCHAR.
At some points in time, it
is necessary to select all rows in which the field N, for example, is greater than 3, for example: SELECT * FROM table1 WHERE field1 > 3;
field1 is not always numeric. I know that PostgreSQL has casts, and the query should look something like this: SELECT * FROM table1 WHERE field1::INTEGER > 3;
But as soon as the cast reaches a non-numeric value, it crashes with an error, "syntax error".
Please tell me how to correctly compose a request in such a way that everything that could be brought to the desired type would be automatically given, and everything that could not be simply skipped, without comparison / casting?
Answer the question
In order to leave comments, you need to log in
Select only what is a number.
SELECT field1::integer FROM table1 WHERE field1 ~ E'^\\d+$' AND field1::integer > 3;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question