Skip site navigation (1) Skip section navigation (2)

FAQ -- Index usage/speed

From: Thomas F(dot)O'Connell <tfo(at)sitening(dot)com>
To: pgman(at)candle(dot)pha(dot)pa(dot)us
Cc: pgsql-docs(at)postgresql(dot)org
Subject: FAQ -- Index usage/speed
Date: 2004-08-31 16:30:45
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-docs

Considering the activity on the lists (at least recently and, I think, 
historically) about postgres not casting (usually integer) constant 
values across types, could there be a mention of this made in the FAQ? 
It seems like a logical case for inclusion under 4.8:

I was thinking something like the following:

Also note that 7.x versions of postgres will not automatically cast 
constant data in certain queries such that an index would be used. For 
example, if you have the following:

CREATE TABLE index_breaker (
	bigintcol		int8 primary key
	some_data 	text

The following query is liikely to perform a sequential scan:

SELECT some_data FROM index_breaker WHERE bigintcol = 42;

postgres will interpret the constant value as a basic int and will thus 
not use the index (implicitly created by the primary key) on the 
bigintcol column.

There are some workarounds for this issue [per Tom Lane]:

1. Always quote your constants:

	... WHERE bigintcol = '42';

Similarly, constants can be explicitly cast:

	... WHERE bigintcol = int8( 42 )

2. Use a prepared statement:

	PREPARE foo(bigint) AS ... WHERE bigintcol = $1;
	EXECUTE foo(42);

3. Use parameterized statements in extended-query mode (essentially the 
same idea as #2, but at the protocol level).  This doesn't help for 
pure SQL scripts, but is very workable when coding against libpq or 
JDBC.  Among other things it gets you out of worrying about SQL 
injection attacks when your parameter values come from untrusted 

Technical improvements to wording are welcome. But I think this is 
worth adding to the docs somewhere.




pgsql-docs by date

Next:From: Bruce MomjianDate: 2004-08-31 19:05:54
Subject: Re: FAQ -- Index usage/speed
Previous:From: Tom LaneDate: 2004-08-30 16:31:56
Subject: Re: Possible error in 8 beta documentation "basics.sql" > "basics.source"

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group