Home >Database >Mysql Tutorial >How Can I Efficiently Query PostgreSQL for Values Starting with '00' and a Non-Zero Third Character?

How Can I Efficiently Query PostgreSQL for Values Starting with '00' and a Non-Zero Third Character?

DDD
DDDOriginal
2024-12-26 17:58:09463browse

How Can I Efficiently Query PostgreSQL for Values Starting with

Regular Expression in PostgreSQL LIKE Clause

This query seeks to match values starting with '00' and having a third character different from '0', as in '0090D0DF143A'. However, the following query fails to match:

SELECT * FROM table WHERE value LIKE '00[1-9]%'

To address this issue, consider using the regular expression operator '~' along with a bracket expression outside the LIKE clause. However, for optimal performance, a combination of LIKE and NOT LIKE clauses is recommended:

SELECT *
FROM   tbl
WHERE  value LIKE '00%'
AND    value NOT LIKE '000%'

The LIKE clause efficiently narrows down the potential matches with a left-anchored expression, while the NOT LIKE clause further refines the results. Postgres can utilize indexes for such expressions, resulting in faster query execution.

Additionally, it's crucial to anchor the pattern to the start of the string using '^' in regular expressions and to use bracket expressions '1' to match any character other than '0'.


    The above is the detailed content of How Can I Efficiently Query PostgreSQL for Values Starting with '00' and a Non-Zero Third Character?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn