0

I don't know how to name this syntax properly. I got a table (say T) with column A in which store the entries in format USER-YYYY-MMDD. I want to extract all rows whose A column's year part (YYYY part) is greater than 2010. E.g.

TABLE T
+----------------+
|        A       |
+----------------+
| USER-2011-1234*|
| USER-1992-1923 |
| USER-2014-1234*|
+----------------+

(*) are what I want: YYYY part is greater than 2010. SQL should looks like this, but I dont know how to say it in PostgreSQL.

 SELECT * FROM T WHERE A[5-8] > 2010

Thanks!

2 Answers 2

3
select *
from t
where to_number(substr(a, 6, 4)) > 2010;

Note that his will fail with an error if the string cannot be converted to a number

More details in the manual: http://www.postgresql.org/docs/current/static/functions-string.html

Btw: storing more than one information in a single column is a bad design. You should store the username and the date in two different columns. Additionally storing dates as varchar is also a very bad idea. The date should be stored as date not as varchar

Sign up to request clarification or add additional context in comments.

7 Comments

As a result of the problems mentioned in the post you have performance issue in your query as non-sargable predicate.
@HamletHakobyan: as a workaround one, could create an index on to_number(substr(a, 6, 4))
Is the analogue of this in the mssql? Can you provide the link to documentation of this type of index. How it named? Index on expression?
@HamletHakobyan What's MS SQL got to do with this? In PostgreSQL, these are referred to as "functional indexes" or "expression indexes".
@CraigRinger MS SQL just forces to have well designed databases :)
|
2

Try Like this

select *
from t
where  substring(a::text from 6 for 4)::integer > 2010;

1 Comment

It works. Thank you! Can you provide a link to the documentation for :: stuff?

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.