Select where first letter in a range ( PostgreSQL )

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

I am trying to select from a table where word's first letter is in a range (a-f for example)

I tried with a where clause like this:

WHERE lower(substring(title from 1 for 1)) IN ARRAY['a', 'k', 't']

hoping that I will find a way to generate the range ARRAY dynamically later.

The above is not working. Any idea what I'm doing wrong?

回答1:

You can use the SIMILAR TO keyword. The following will match all titles that start with either 'a', 'k', or 't'.

... WHERE lower(title) SIMILAR TO '(a|k|t)%'

If you want to use a range, you could use the [] notation:

... WHERE lower(title) SIMILAR TO '[a-f]%'

NOTES

  1. The % character matches any number of characters following the pattern. For instance, the second pattern example would match: 'abc', 'ab', 'a', 'far', 'fear' etc.

  2. Also, it is important to note that the SIMILAR TO keyword is only available to PostgreSQL and it is not ANSI SQL.

  3. Finally, the lower(title) is not necessary when using the character class. You could simply search for something like

    WHERE title SIMILAR TO '[a-fA-F]%'



回答2:

IN doesn't understand an array on the right side, you want = ANY:

WHERE lower(substring(title from 1 for 1)) = ANY (ARRAY['a', 'k', 't'])

Or you could use LIKE, SIMILAR TO, or ~ (POSIX regex).

Extra references:



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!