Received: from sss2.sss.pgh.pa.us (sss.pgh.pa.us [209.114.166.2]) by hub.org (8.9.3/8.9.3) with ESMTP id RAA64219 for ; Sat, 18 Dec 1999 17:28:50 -0500 (EST) (envelope-from tgl@sss.pgh.pa.us) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss2.sss.pgh.pa.us (8.9.3/8.9.3) with ESMTP id RAA01563; Sat, 18 Dec 1999 17:27:41 -0500 (EST) To: "tjk@tksoft.com" cc: admin@wtbwts.com (admin), peter_e@gmx.net, pgsql-sql@postgreSQL.org Subject: Re: [SQL] making 'like' queries quicker In-reply-to: Your message of Sat, 18 Dec 1999 13:53:51 -0800 (PST) <199912182153.NAA11586@uno.tksoft.com> Date: Sat, 18 Dec 1999 17:27:41 -0500 Message-ID: <1560.945556061@sss.pgh.pa.us> From: Tom Lane "tjk@tksoft.com" writes: > A general rule of thumb is that indexes > only work on exact matches. Troy's rule of thumb is correct, but there's an important additional property of some types of indexes: you can scan them in order (for whatever kind of "order" is imposed by the index comparison operator). Postgres' btree indexes work that way, but hash indexes don't. An ordered index can be used to process inequalities and range queries as well as exact-match queries. For example, with a btree index you can do something like WHERE lastname >= 'Smith' AND lastname <= 'Szekely' fairly efficiently: you scan the portion of the index falling between the given limits, and then extract the main-table records pointed to by those index entries. Therefore, it's practical to use a btree index to speed up match queries that require a match at the start of the string. For example, given WHERE lastname LIKE 'Smith%' Postgres will generate additional clauses lastname >= 'Smith' AND lastname <= 'Smith\377' which can be used with a btree index to restrict the number of records that have to be looked at. You still have to do the LIKE comparison, in general (consider LIKE 'Smith%Jr') but you don't have to do it for every record in the table. There isn't any obvious way to apply this trick for an unanchored match, though (as in LIKE '%Smith%'). However, if you are actually interested in searching for whole words, you could consider making an index that lists all of the whole words in your target field, and doing an exact match with that index. See contrib/fulltextindex in the Postgres distribution for an example. regards, tom lane