-1

Exist a chance to speedup the below sql query?

select 
    max(xtrid) as xtrid
  , jid
from jpltab jl
  inner join rb_cust u 
    on jl.custid = u.custid
where jl.tpe = 'Y'
  and jl.jid in (51, 52, 53, 54, 55)
  and u.org = 'INVCE'
group by jid
order by xtrid desc;

thanks

SqlZim
  • 37,248
  • 6
  • 41
  • 59
Mark89
  • 9
  • 4
  • 1
    Adding indexes.... – juergen d May 24 '17 at 16:15
  • can you include the execution plan please? – VDK May 24 '17 at 16:19
  • Since your `jl.jid` in your `Where` clause has consecutive numbers, change that to `Between 51 and 55` instead of the `IN (51, 52, 53, 54, 55)`. This should give you better performance. See here... https://stackoverflow.com/questions/3308280/is-there-a-performance-difference-between-between-and-in-with-mysql-or-in-sql-in – SS_DBA May 24 '17 at 16:21
  • What database client? – SandPiper May 24 '17 at 16:31
  • I would also move "and u.org = 'INVCE'" to your JOIN statement. You only want rb_cust to match jpltab for custid, but ONLY for rb_cust.org='INVCE'. Logically, that will make that initial JOIN a lot smaller, instead of JOINing for every custid and then filtering out for the org. The SQL Optimizer _may_ already handle this for an INNER JOIN, but I don't think it does. – Shawn May 24 '17 at 16:36

2 Answers2

1

This is your query:

select jl.jid, max(xtrid) as xtrid
from jpltab jl inner join
     rb_cust u 
     on jl.custid = u.custid
where jl.tpe = 'Y' and
      jl.jid in (51, 52, 53, 54, 55) and
      u.org = 'INVCE'
group by jl.jid
order by xtrid desc;

I would start with indexes. What comes to mind is jpltab(tpe, jid, custid) and rb_cust(custid, org).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-3

You can take out 'order by xtrid desc' as you're already selecting the max

RBT
  • 24,161
  • 21
  • 159
  • 240
heyhey
  • 41
  • 4
  • Yes... you don't need to order the values by group in order to select the max for each group. – heyhey May 24 '17 at 16:46