pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Optimize query
14+ messages / 9 participants
[nested] [flat]

* Optimize query
@ 2004-04-05 13:48 Michal Hlavac <hlavki@medium13.sk>
  0 siblings, 0 replies; 14+ messages in thread

From: Michal Hlavac @ 2004-04-05 13:48 UTC (permalink / raw)
  To: pgsql-general

Hello,

I have one main table and 2 many-to-many relation tables and 2
one-to-many relation table. Main table has 150 000 rows and many-to-many
tables have about 300 000 rows.

I am creating web portal.
In my query I must call distinct with many-to-many relation. But this
query is too slow for web application. This query costs 8,5 seconds.
For example:

SELECT distinct(i_part_id), i_is_special, a.v_name, d.v_company,
f_price, t_description
FROM v_part a
	JOIN l_model_to_part b USING (i_part_id)
	JOIN l_part_to_cat c USING (i_part_id)
	JOIN k_seller d USING (i_seller_id)
	JOIN c_part_cat e USING (i_part_cat_id)
WHERE TRUE AND condition ORDER BY i_is_special DESC, v_name;

So, I created another way, how to grow up performace. I created 
temporary table with result of query, which has only one column (id of 
product). And finally I do a join of temporary table with main table. 
This query costs 0,5 seconds with everything.

It is 8,5 seconds versus 0,5 seconds...

Is this the right way, how to increase the performance of the queries??? 
I know, that every problem is specific. I mean this philosophical.

thanx, miso





^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* optimize query?
@ 2013-01-30 11:33 hamann.w@t-online.de
  0 siblings, 0 replies; 14+ messages in thread

From: hamann.w@t-online.de @ 2013-01-30 11:33 UTC (permalink / raw)
  To: pgsql-general

Hi,

I am trying to match items from 2 tables based on a common string.
One is a big table which has one column with entries like XY123, ABC44, etc
The table has an index on that column.
The second table is, typically, much smaller

select .... from tab1, tab2 where tab1.code = tab2.code;

This works fine and fast.
Now, as a variant, I have some entries like XY423A, XY423B, GF55A, GF55D in the
big table and want them to match XY423, GF55 in the second table

Variants I have tried

select  .... from tab1, tab2 where tab1.code ~ (tab2.code||'($|[A-Z])');
select  .... from tab1, tab2 where tab1.code ~ ('^'||tab2.code||'($|[A-Z])');

both take an enormous time. In the better case that I can subset (e.g. all candidates in table 2
share initial "AX") I get back to manageable times by adding
  and tab1.code ~ '^AX'
into the recipe. Actual runtime with about a million entries in tab1 and 800 entries in tab2
is about 40 seconds.

Regards
Wolfgang Hamann



-- 
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general



^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: optimize query?
@ 2013-01-30 13:32 hamann.w@t-online.de
  0 siblings, 0 replies; 14+ messages in thread

From: hamann.w@t-online.de @ 2013-01-30 13:32 UTC (permalink / raw)
  To: pgsql-general


Bob Futrelle wrote:

If looking for the variants with a single suffixed character is all you'll
ever need to do:
Do a single pass on the large table, after creating a field, 'trunc' that
contains a truncated version of the item, e.g., adding XY423 to trunc for
each entry of the form XY423A, or XY423B, etc.  This would be a one-time
operation.

Hi Bob,

unfortunately it is not because  the suffix pattern is not always the same.
On the other hand, I tried to split the query into

select substring (code from '^[A-Z]+[0-9]+') as code into tmp table t
select .... where tab2.code = t.code

which definitely was a big improvement. I believe that most of the time
passing in a pattern like that would work

So thank you for that tip

Regards
Wolfgang


-- 
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general



^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Optimize Query
@ 2016-02-11 01:25 drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
  0 siblings, 1 reply; 14+ messages in thread

From: drum.lucas@gmail.com @ 2016-02-11 01:25 UTC (permalink / raw)
  To: pgsql-general

Hi all,

I've got a slow query and I'm trying to make it faster.

*New Query:*

SELECT concat(client.company, ' ', client.name_first, ' ',
> client.name_last) AS customer,
>        sum(COALESCE(bill_item.unit_price, billable.unit_price, 0) *
> bill_item.quantity) AS revenue,
>        sum(bill_item.quantity) AS quantity,
>        sum(COALESCE(bill_item.unit_cost, billable.unit_cost, 0) *
> bill_item.quantity) AS cost
>    FROM ja_clients AS account
>    JOIN ja_customers AS client ON client.clientid = account.id
>    JOIN ja_jobs AS job ON client.id=job.customerid
>    JOIN ja_notes AS note ON note.jobid = job.id
>    JOIN dm.bill_items AS bill_item ON
> bill_item.bill_item_id=note.bill_item_id
>    LEFT JOIN dm.bills AS bill ON bill.bill_id=bill_item.bill_id
>    LEFT JOIN dm.invoices AS invoice ON invoice.invoice_id=bill.invoice_id
>      OR invoice.invoice_id=bill_item.invoice_id
>    LEFT JOIN dm.billables AS billable ON
> billable.billable_id=note.billable_id
>    LEFT JOIN dm.labors AS labs ON labs.billable_id = billable.billable_id
>    JOIN ja_mobiusers AS "user" ON "user".id = note.mobiuserid
>    JOIN ja_status AS status ON status.id = job.status_label_id
>    JOIN ja_role AS ROLE ON ROLE.id="user".user_type
>    WHERE note.note_type::text = ANY (ARRAY[ ('time'::CHARACTER
> VARYING)::text,
>                                             ('part'::CHARACTER
> VARYING)::text ])
>      AND NOT job.templated
>      AND NOT job.deleted
>      AND job.clientid = 6239
>      AND job.time_job >= 1438351200
>      AND job.time_job <= 1448888340
>      AND bill_item.for_invoicing = TRUE
> GROUP BY customer
> ORDER BY revenue DESC;


*The original query has:*


SELECT $cols $ec , sum(revenue) as revenue, $cost_cols
> FROM (".note_detail_report_view(). ") AS i
> LEFT JOIN (
>     SELECT $join_col , SUM(cost) AS cost, SUM(quantity) AS quantity
>     FROM (".note_detail_report_view(). ") AS note_detail_report_view
>     $whereClause AND *n_quote_status = 0*
>     GROUP BY $join_col
> ) AS a
> ON $joiner
> $whereClause AND invoice = true $limit_inv
> GROUP BY $group_by $ec, a.cost , a.quantity
> ORDER BY $order_by


I just need the a-case. i and a look very similar, except A with an
additional filter: *n_quote_status = 0*


How can I re-write that using the A case?

Thanks

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
@ 2016-02-11 02:22 ` Melvin Davidson <melvin6925@gmail.com>
  2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  0 siblings, 1 reply; 14+ messages in thread

From: Melvin Davidson @ 2016-02-11 02:22 UTC (permalink / raw)
  To: drum.lucas@gmail.com <drum.lucas@gmail.com>; +Cc: pgsql-general

On Wed, Feb 10, 2016 at 8:25 PM, drum.lucas@gmail.com <drum.lucas@gmail.com>
wrote:

> Hi all,
>
> I've got a slow query and I'm trying to make it faster.
>
> *New Query:*
>
> SELECT concat(client.company, ' ', client.name_first, ' ',
>> client.name_last) AS customer,
>>        sum(COALESCE(bill_item.unit_price, billable.unit_price, 0) *
>> bill_item.quantity) AS revenue,
>>        sum(bill_item.quantity) AS quantity,
>>        sum(COALESCE(bill_item.unit_cost, billable.unit_cost, 0) *
>> bill_item.quantity) AS cost
>>    FROM ja_clients AS account
>>    JOIN ja_customers AS client ON client.clientid = account.id
>>    JOIN ja_jobs AS job ON client.id=job.customerid
>>    JOIN ja_notes AS note ON note.jobid = job.id
>>    JOIN dm.bill_items AS bill_item ON
>> bill_item.bill_item_id=note.bill_item_id
>>    LEFT JOIN dm.bills AS bill ON bill.bill_id=bill_item.bill_id
>>    LEFT JOIN dm.invoices AS invoice ON invoice.invoice_id=bill.invoice_id
>>      OR invoice.invoice_id=bill_item.invoice_id
>>    LEFT JOIN dm.billables AS billable ON
>> billable.billable_id=note.billable_id
>>    LEFT JOIN dm.labors AS labs ON labs.billable_id = billable.billable_id
>>    JOIN ja_mobiusers AS "user" ON "user".id = note.mobiuserid
>>    JOIN ja_status AS status ON status.id = job.status_label_id
>>    JOIN ja_role AS ROLE ON ROLE.id="user".user_type
>>    WHERE note.note_type::text = ANY (ARRAY[ ('time'::CHARACTER
>> VARYING)::text,
>>                                             ('part'::CHARACTER
>> VARYING)::text ])
>>      AND NOT job.templated
>>      AND NOT job.deleted
>>      AND job.clientid = 6239
>>      AND job.time_job >= 1438351200
>>      AND job.time_job <= 1448888340
>>      AND bill_item.for_invoicing = TRUE
>> GROUP BY customer
>> ORDER BY revenue DESC;
>
>
> *The original query has:*
>
> SELECT $cols $ec , sum(revenue) as revenue, $cost_cols
>> FROM (".note_detail_report_view(). ") AS i
>> LEFT JOIN (
>>     SELECT $join_col , SUM(cost) AS cost, SUM(quantity) AS quantity
>>     FROM (".note_detail_report_view(). ") AS note_detail_report_view
>>     $whereClause AND *n_quote_status = 0*
>>     GROUP BY $join_col
>> ) AS a
>> ON $joiner
>> $whereClause AND invoice = true $limit_inv
>> GROUP BY $group_by $ec, a.cost , a.quantity
>> ORDER BY $order_by
>
>
> I just need the a-case. i and a look very similar, except A with an
> additional filter: *n_quote_status = 0*
>
> How can I re-write that using the A case?
>
> Thanks
>

FYI, it is always helpful (and polite) to state the PostgreSQL VERSION and
O/S for archive documentation purposes!

Note that various postgresql.conf options, system memory & hardware also
play a factor here, in addition to current table statistics.

That being said, try the following:

WITH jobs AS
(
 SELECT id,
        customerid,
        status_label_id
  FROM ja_jobs
 WHERE NOT templated
   AND NOT deleted
   AND clientid = 6239
   AND time_job >= 1438351200
   AND time_job <= 1448888340
)
SELECT concat(client.company,
       ' ',
       client.name_first,
       ' ', client.name_last) AS customer,
       sum(COALESCE(bill_item.unit_price, billable.unit_price, 0) *
bill_item.quantity) AS revenue,
       sum(bill_item.quantity) AS quantity,
       sum(COALESCE(bill_item.unit_cost, billable.unit_cost, 0) *
bill_item.quantity) AS cost
  FROM ja_clients    AS account
  JOIN ja_customers  AS client ON client.clientid = account.id
  JOIN jobs          AS job    ON job.customerid = client.id
  JOIN ja_notes      AS note   ON note.jobid = job.id
  JOIN dm.bill_items AS bill_item ON
bill_item.bill_item_id=note.bill_item_id
  LEFT JOIN dm.bills AS bill ON bill.bill_id=bill_item.bill_id
  LEFT JOIN dm.invoices AS invoice ON invoice.invoice_id=bill.invoice_id
                                   OR
invoice.invoice_id=bill_item.invoice_id
  LEFT JOIN dm.billables AS billable ON
billable.billable_id=note.billable_id
  LEFT JOIN dm.labors AS labs ON labs.billable_id = billable.billable_id
  JOIN ja_mobiusers AS "user" ON "user".id = note.mobiuserid
  JOIN ja_status AS status ON status.id = job.status_label_id
  JOIN ja_role AS ROLE ON ROLE.id="user".user_type
 WHERE note.note_type::text = ANY (ARRAY[ ('time'::CHARACTER
VARYING)::text, ('part'::CHARACTER VARYING)::text ])
   AND bill_item.for_invoicing = TRUE
 GROUP BY customer
 ORDER BY revenue DESC;

-- 
*Melvin Davidson*
I reserve the right to fantasize.  Whether or not you
wish to share my fantasy is entirely up to you.

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
@ 2016-02-11 02:38   ` drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 04:09     ` Re: Optimize Query John R Pierce <pierce@hogranch.com>
  2016-02-13 10:21     ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  0 siblings, 2 replies; 14+ messages in thread

From: drum.lucas@gmail.com @ 2016-02-11 02:38 UTC (permalink / raw)
  To: Melvin Davidson <melvin6925@gmail.com>; +Cc: pgsql-general

>
>
> FYI, it is always helpful (and polite) to state the PostgreSQL VERSION and
> O/S for archive documentation purposes!
>

That's right. My mistake... I'm using PostgreSQL 9.2.


>
> Note that various postgresql.conf options, system memory & hardware also
> play a factor here, in addition to current table statistics.
>
> That being said, try the following:
>
> WITH jobs AS
> (
>  SELECT id,
>         customerid,
>         status_label_id
>   FROM ja_jobs
>  WHERE NOT templated
>    AND NOT deleted
>    AND clientid = 6239
>    AND time_job >= 1438351200
>    AND time_job <= 1448888340
> )
> SELECT concat(client.company,
>        ' ',
>        client.name_first,
>        ' ', client.name_last) AS customer,
>        sum(COALESCE(bill_item.unit_price, billable.unit_price, 0) *
> bill_item.quantity) AS revenue,
>        sum(bill_item.quantity) AS quantity,
>        sum(COALESCE(bill_item.unit_cost, billable.unit_cost, 0) *
> bill_item.quantity) AS cost
>   FROM ja_clients    AS account
>   JOIN ja_customers  AS client ON client.clientid = account.id
>   JOIN jobs          AS job    ON job.customerid = client.id
>   JOIN ja_notes      AS note   ON note.jobid = job.id
>   JOIN dm.bill_items AS bill_item ON
> bill_item.bill_item_id=note.bill_item_id
>   LEFT JOIN dm.bills AS bill ON bill.bill_id=bill_item.bill_id
>   LEFT JOIN dm.invoices AS invoice ON invoice.invoice_id=bill.invoice_id
>                                    OR
> invoice.invoice_id=bill_item.invoice_id
>   LEFT JOIN dm.billables AS billable ON
> billable.billable_id=note.billable_id
>   LEFT JOIN dm.labors AS labs ON labs.billable_id = billable.billable_id
>   JOIN ja_mobiusers AS "user" ON "user".id = note.mobiuserid
>   JOIN ja_status AS status ON status.id = job.status_label_id
>   JOIN ja_role AS ROLE ON ROLE.id="user".user_type
>  WHERE note.note_type::text = ANY (ARRAY[ ('time'::CHARACTER
> VARYING)::text, ('part'::CHARACTER VARYING)::text ])
>    AND bill_item.for_invoicing = TRUE
>  GROUP BY customer
>  ORDER BY revenue DESC;
>

Thank you Melvin.
Sorry but I was unable to see the *n_quote_status = 0*

Did you use it?

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
  2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
@ 2016-02-11 04:09     ` John R Pierce <pierce@hogranch.com>
  1 sibling, 0 replies; 14+ messages in thread

From: John R Pierce @ 2016-02-11 04:09 UTC (permalink / raw)
  To: pgsql-general

On 2/10/2016 6:38 PM, drum.lucas@gmail.com wrote:
> Sorry but I was unable to see the *n_quote_status = 0*

I'm unable to see this variable anywhere in your two original queries, 
the SQL one, and the other ?? abbreviated thing, nor did you give any 
table definitions, so I'm not even sure what you mean by n_quote_status




-- 
john r pierce, recycling bits in santa cruz

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
  2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
@ 2016-02-13 10:21     ` drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-14 09:56       ` Re: Optimize Query Alban Hertroys <haramrae@gmail.com>
  1 sibling, 1 reply; 14+ messages in thread

From: drum.lucas@gmail.com @ 2016-02-13 10:21 UTC (permalink / raw)
  To: pgsql-general

Anyone can help with that please?

Cheers

On Thursday, 11 February 2016, drum.lucas@gmail.com <drum.lucas@gmail.com>
wrote:

> oh ok!
>
> thanks
>
>
>
> Lucas Possamai
>
> - kinghost.co.nz
> <http://forum.kinghost.co.nz/memberlist.php?mode=viewprofile&u=2&sid=e999f8370385657a65d41d5f...;
> - DigitalOcean <https://m.do.co/c/a0d31c597a03;
>
> On 11 February 2016 at 15:41, Melvin Davidson <melvin6925@gmail.com
> <javascript:_e(%7B%7D,'cvml','melvin6925@gmail.com');>> wrote:
>
>>
>>
>>
>>> Thank you Melvin.
>>> Sorry but I was unable to see the *n_quote_status = 0*
>>>
>>> Did you use it?
>>>
>>>
>> No, I just revised you "new" query to be more efficient.
>>
>>
>> --
>> *Melvin Davidson*
>> I reserve the right to fantasize.  Whether or not you
>> wish to share my fantasy is entirely up to you.
>>
>
>

-- 


Lucas Possamai

- kinghost.co.nz
<http://forum.kinghost.co.nz/memberlist.php?mode=viewprofile&u=2&sid=e999f8370385657a65d41d5f...;
- DigitalOcean <https://m.do.co/c/a0d31c597a03;

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
  2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-13 10:21     ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
@ 2016-02-14 09:56       ` Alban Hertroys <haramrae@gmail.com>
  2016-02-14 19:40         ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  0 siblings, 1 reply; 14+ messages in thread

From: Alban Hertroys @ 2016-02-14 09:56 UTC (permalink / raw)
  To: drum.lucas@gmail.com; +Cc: pgsql-general


> On 13 Feb 2016, at 11:21, drum.lucas@gmail.com wrote:
> 
> Anyone can help with that please?
> 
> Cheers

What would help is:
1. to post an actual query that you need optimised and
2. an explain analyze of that query.

What you posted in your original message was some kind of query-template with enough placeholders and views that there is no way to predict how that's going to perform without at least knowing what goes into the placeholders and how the views are built up.

Alban Hertroys
--
If you can't see the forest for the trees,
cut the trees and you'll find there is no forest.



-- 
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general



^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
  2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-13 10:21     ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-14 09:56       ` Re: Optimize Query Alban Hertroys <haramrae@gmail.com>
@ 2016-02-14 19:40         ` drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-14 23:43           ` Re: Optimize Query Alban Hertroys <haramrae@gmail.com>
  0 siblings, 1 reply; 14+ messages in thread

From: drum.lucas@gmail.com @ 2016-02-14 19:40 UTC (permalink / raw)
  To: Alban Hertroys <haramrae@gmail.com>; +Cc: pgsql-general

Hi Alban! Sorry.. that was my mistake


Original Query:

SELECT concat(company, ' ', customer_name_first, ' ',
customer_name_last) AS customer,
       sum(revenue) AS revenue,
       sum(i.quantity) AS quantity,
       sum(i.cost) AS costFROM
  ( SELECT account.id,
           job.customerid,
           job.title,
           job.gps_lat,
           job.gps_long,
           status.label AS status,
           status.status_type_id,
           job.status_label_id,
           client."position",
           bill_item.quantity,
           client.businesstype,
           account.id AS clientid,
           client.name_first AS customer_name_first,
           client.name_last AS customer_name_last,
           job.id AS jobid,
           note.mobiuserid,
           bill_item.for_invoicing AS invoice,
           COALESCE(bill_item.unit_price, billable.unit_price, 0) AS unit_price,
           note.n_quote_status,
           COALESCE(bill_item.unit_cost, billable.unit_cost, 0) AS unit_cost,
           job.time_job,
           "user".name_first,
           "user".name_last,
           role.id AS roleid,
           role.name AS role_name,
           billable.billable_id AS taskid,
           COALESCE(labs.tag, billable.code) AS task_name,
           note.time_start,
           client.company,
           job.refnum,
           (COALESCE(bill_item.unit_cost, billable.unit_cost, 0) *
bill_item.quantity) AS cost,
           (COALESCE(bill_item.unit_price, billable.unit_price, 0) *
bill_item.quantity) AS revenue,
           bill_item.for_invoicing AS invoiceable,
           COALESCE(extract('epoch'
                            FROM bill.ts_creation AT TIME ZONE 'UTC'),
bill_item.invoice_id, NULL) IS NOT NULL AS invoiced
   FROM ja_clients AS account
   JOIN ja_customers AS client ON client.clientid = account.id
   JOIN ja_jobs AS job ON client.id=job.customerid
   JOIN ja_notes AS note ON note.jobid = job.id
   JOIN dm.bill_items AS bill_item ON bill_item.bill_item_id=note.bill_item_id
   LEFT JOIN dm.bills AS bill ON bill.bill_id=bill_item.bill_id
   LEFT JOIN dm.invoices AS invoice ON invoice.invoice_id=bill.invoice_id
   OR invoice.invoice_id=bill_item.invoice_id
   LEFT JOIN dm.billables AS billable ON billable.billable_id=note.billable_id
   LEFT JOIN dm.labors AS labs ON labs.billable_id = billable.billable_id
   JOIN ja_mobiusers AS "user" ON "user".id = note.mobiuserid
   JOIN ja_status AS status ON status.id = job.status_label_id
   JOIN ja_role AS ROLE ON ROLE.id="user".user_type
   WHERE note.note_type::text = ANY (ARRAY[ ('time'::CHARACTER VARYING)::text,
                                            ('part'::CHARACTER VARYING)::text ])
     AND NOT job.templated
     AND NOT job.deleted
     AND job.clientid = 6239
     AND time_job >= 1438351200
     AND time_job <= 1448888340
     AND bill_item.for_invoicing = TRUE) AS iLEFT JOIN
  (SELECT customerid,
          SUM(cost) AS cost,
          SUM(quantity) AS quantity
   FROM
     (SELECT account.id,
             job.customerid,
             job.title,
             job.gps_lat,
             job.gps_long,
             status.label AS status,
             status.status_type_id,
             job.status_label_id,
             client."position",
             bill_item.quantity,
             client.businesstype,
             account.id AS clientid,
             client.name_first AS customer_name_first,
             client.name_last AS customer_name_last,
             job.id AS jobid,
             note.mobiuserid,
             bill_item.for_invoicing AS invoice,
             COALESCE(bill_item.unit_price, billable.unit_price, 0) AS
unit_price,
             note.n_quote_status,
             COALESCE(bill_item.unit_cost, billable.unit_cost, 0) AS unit_cost,
             job.time_job,
             "user".name_first,
             "user".name_last,
             ROLE.id AS roleid,
                  ROLE.name AS role_name,
                       billable.billable_id AS taskid,
                       COALESCE(labs.tag, billable.code) AS task_name,
                       note.time_start,
                       client.company,
                       job.refnum,
                       (COALESCE(bill_item.unit_cost,
billable.unit_cost, 0) * bill_item.quantity) AS cost,
                       (COALESCE(bill_item.unit_price,
billable.unit_price, 0) * bill_item.quantity) AS revenue,
                       bill_item.for_invoicing AS invoiceable,
                       COALESCE(extract('epoch'
                                        FROM bill.ts_creation AT TIME
ZONE 'UTC'), bill_item.invoice_id, NULL) IS NOT NULL AS invoiced
      FROM ja_clients AS account
      JOIN ja_customers AS client ON client.clientid = account.id
      JOIN ja_jobs AS job ON client.id=job.customerid
      JOIN ja_notes AS note ON note.jobid = job.id
      JOIN dm.bill_items AS bill_item ON
bill_item.bill_item_id=note.bill_item_id
      LEFT JOIN dm.bills AS bill ON bill.bill_id=bill_item.bill_id
      LEFT JOIN dm.invoices AS invoice ON invoice.invoice_id=bill.invoice_id
      OR invoice.invoice_id=bill_item.invoice_id
      LEFT JOIN dm.billables AS billable ON
billable.billable_id=note.billable_id
      LEFT JOIN dm.labors AS labs ON labs.billable_id = billable.billable_id
      JOIN ja_mobiusers AS "user" ON "user".id = note.mobiuserid
      JOIN ja_status AS status ON status.id = job.status_label_id
      JOIN ja_role AS ROLE ON ROLE.id="user".user_type
      WHERE note.note_type::text = ANY (ARRAY[ ('time'::CHARACTER
VARYING)::text,
                                               ('part'::CHARACTER
VARYING)::text ])
        AND NOT job.templated
        AND NOT job.deleted
        AND job.clientid = 6239
        AND time_job >= 1438351200
        AND time_job <= 1448888340
        AND n_quote_status = 0 ) AS note_detail_report_view
   WHERE 1=1
     AND clientid = 6239
     AND time_job >= 1438351200
     AND time_job <= 1448888340
     AND n_quote_status = 0
   GROUP BY customerid) AS a ON a.customerid = i.customeridWHERE 1=1
  AND clientid = 6239
  AND time_job >= 1438351200
  AND time_job <= 1448888340
  AND invoice = TRUEGROUP BY customer,
         a.cost,
         a.quantityORDER BY revenue DESC


Explain analyze link:
http://explain.depesz.com/s/5WJy

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize Query
  2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
  2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-13 10:21     ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
  2016-02-14 09:56       ` Re: Optimize Query Alban Hertroys <haramrae@gmail.com>
  2016-02-14 19:40         ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
@ 2016-02-14 23:43           ` Alban Hertroys <haramrae@gmail.com>
  0 siblings, 0 replies; 14+ messages in thread

From: Alban Hertroys @ 2016-02-14 23:43 UTC (permalink / raw)
  To: drum.lucas@gmail.com; +Cc: pgsql-general


> On 14 Feb 2016, at 20:40, drum.lucas@gmail.com wrote:
> 
> Hi Alban! Sorry.. that was my mistake

Okay, first advice on that query: Trim it down to something that people can wrap their minds around.

You have a silly amount of code repetition in there, much of which doesn't even seem to serve a purpose. This is some kind of generated query, I gather?
For example, you don't use most of the fields from your first subquery.

Another example is the nested subquery in your left join, which can be reduced to a single subquery with just the fields summed that you actually need (and the customer_id, obviously).

The same goes for most of the joins inside that left join, definitely the left joins - but that depends a bit on your table definitions and contents.
For example, the fields you're summing come from account (but you can use customer instead, since you only use the account_id, which equals client_id anyway) and bill_item. Some fields in your where-clause come from job, some others I can't tell where they're from.

Trim, trim, trim, until you're left with a more readable query that gives you the same results and then put it through explain analyze again. It wouldn't surprise me if that query is already significantly faster.

If you're still having problems at that point, post that query and the analysis again.

> Explain analyze link:
> http://explain.depesz.com/s/5WJy

Alban Hertroys
--
If you can't see the forest for the trees,
cut the trees and you'll find there is no forest.



-- 
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general



^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Optimize query
@ 2020-12-15 14:17 Yambu <hyambu@gmail.com>
  2020-12-15 14:27 ` Re: Optimize query Raul Giucich <raul.giucich@gmail.com>
  2020-12-15 15:37 ` Re: Optimize query Ron <ronljohnsonjr@gmail.com>
  0 siblings, 2 replies; 14+ messages in thread

From: Yambu @ 2020-12-15 14:17 UTC (permalink / raw)
  To: pgsql-general@lists.postgresql.org

Hi

How would you optimize a query with greater than in where clause eg

select * from table1 where id > 1000

and there is an index on id column

regards

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize query
  2020-12-15 14:17 Optimize query Yambu <hyambu@gmail.com>
@ 2020-12-15 14:27 ` Raul Giucich <raul.giucich@gmail.com>
  1 sibling, 0 replies; 14+ messages in thread

From: Raul Giucich @ 2020-12-15 14:27 UTC (permalink / raw)
  To: Yambu <hyambu@gmail.com>; +Cc: pgsql-general@lists.postgresql.org

Hi Yambu, the btree index type is optimized for this kind of operators (>,
>=, <, <=, =).
For deep understanding on how to plan an query optimization I would
recommend https://classroom.google.com/c/MTQ4MzczNDExMjM4 and
https://use-the-index-luke.com.
Another tip is use in the select clause only the columns that are
significant to answer the question you user is making executing this query.
Sorry for my foreign english.
Best regards.
Raúl.


El mar, 15 dic 2020 a las 11:18, Yambu (<hyambu@gmail.com>) escribió:

> Hi
>
> How would you optimize a query with greater than in where clause eg
>
> select * from table1 where id > 1000
>
> and there is an index on id column
>
> regards
>

^ permalink  raw  reply  [nested|flat] 14+ messages in thread

* Re: Optimize query
  2020-12-15 14:17 Optimize query Yambu <hyambu@gmail.com>
@ 2020-12-15 15:37 ` Ron <ronljohnsonjr@gmail.com>
  1 sibling, 0 replies; 14+ messages in thread

From: Ron @ 2020-12-15 15:37 UTC (permalink / raw)
  To: pgsql-general@lists.postgresql.org

On 12/15/20 8:17 AM, Yambu wrote:
> Hi
>
> How would you optimize a query with greater than in where clause eg
>
> select * from table1 where id > 1000
>
> and there is an index on id column

The question as written is unanswerable.

- Why do you think it needs to be optimized?
- What is the table cardinality, and the query cardinality?
- What does EXPLAIN say?
- Have you run ANALYZE on table1?

Bottom line: Postgres *might* think that it is more efficient to scan the 
whole table.

-- 
Angular momentum makes the world go 'round.

^ permalink  raw  reply  [nested|flat] 14+ messages in thread


end of thread, other threads:[~2020-12-15 15:37 UTC | newest]

Thread overview: 14+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2004-04-05 13:48 Optimize query Michal Hlavac <hlavki@medium13.sk>
2013-01-30 11:33 optimize query? hamann.w@t-online.de
2013-01-30 13:32 Re: optimize query? hamann.w@t-online.de
2016-02-11 01:25 Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
2016-02-11 02:22 ` Re: Optimize Query Melvin Davidson <melvin6925@gmail.com>
2016-02-11 02:38   ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
2016-02-11 04:09     ` Re: Optimize Query John R Pierce <pierce@hogranch.com>
2016-02-13 10:21     ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
2016-02-14 09:56       ` Re: Optimize Query Alban Hertroys <haramrae@gmail.com>
2016-02-14 19:40         ` Re: Optimize Query drum.lucas@gmail.com <drum.lucas@gmail.com>
2016-02-14 23:43           ` Re: Optimize Query Alban Hertroys <haramrae@gmail.com>
2020-12-15 14:17 Optimize query Yambu <hyambu@gmail.com>
2020-12-15 14:27 ` Raul Giucich <raul.giucich@gmail.com>
2020-12-15 15:37 ` Ron <ronljohnsonjr@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox