Re: Need help optimizing this query - Mailing list pgsql-general

From Michael Glaesemann
Subject Re: Need help optimizing this query
Date
Msg-id CB5B0172-691F-4B3F-AE24-5BF39EA7FA65@seespotcode.net
Whole thread Raw
In response to Re: Need help optimizing this query  ("Pat Maddox" <pergesu@gmail.com>)
Responses Re: Need help optimizing this query
List pgsql-general
On Jul 18, 2007, at 16:48 , Pat Maddox wrote:

> For some reason the functions you wrote are giving me trouble (there's
> a BIGINT involved, I tried changing the functions around but kept
> having issues).

You might try these, if you're interested.

CREATE OR REPLACE FUNCTION ternary(BOOLEAN, BIGINT, BIGINT)
RETURNS BIGINT
LANGUAGE SQL AS $_$SELECT CASE WHEN $1 THEN $2 ELSE $3 END$_$;

CREATE OR REPLACE FUNCTION value_when(BOOLEAN, BIGINT)
RETURNS BIGINT
LANGUAGE SQL AS $_$SELECT ternary($1,$2,0)$_$;

CREATE OR REPLACE FUNCTION one_when(BOOLEAN)
RETURNS BIGINT
LANGUAGE SQL as $_$SELECT value_when($1,1)$_$;

> So here's the full query, hopefully formatted better:

I'm still curious about why the planner is choosing a hash join over
using the indexes on the foreign keys, but that might be because the
tables are relatively small.

> That one runs reasonably fine, because there are only 20 videos being
> returned and a handful of video views associated with them.  In the
> real query there are about 1k videos and a couple million views.  That
> took about 80 minutes to run, according to logs.

The planner will choose different plans based on, among other things,
what it estimates the size of the result to be, so while looking at a
small example query might seem like a way to go about looking at
what's going on, it's most likely not going to give you an accurate
representation of the situation. Are you looking at two different
systems (e.g., a development system versus a production system) or
just choosing a smaller query on the same system? If you can't run
the query on your production system, you may want to take a dump of
the production system and set it up on another box. Even with a
couple million rows in the video_views table, PostgreSQL shouldn't
really blink too much, as long as the server is tuned properly, the
hardware is adequate, and the database statistics are up to date.

Michael Glaesemann
grzm seespotcode net




pgsql-general by date:

Previous
From: "Pat Maddox"
Date:
Subject: Re: Need help optimizing this query
Next
From: Tom Lane
Date:
Subject: Re: Feature request: Per database search_path