1

I want to find an entity name that could be in one of the six tables. For that I have written a function getEntityName(entityid). The code is working fine as I am using UNION for the tables. But the problem is, these tables contain a huge amount data so the function is taking a long time to return the output. I am not sure if by using JOIN I can optimize this function. I am sharing the function definition; please let me know if there is any way to optimize this function:

delimiter $$
drop function if exists getEntityName$$
create function getEntityName(entityid int) returns varchar(128)
    begin
return(
        select
            shortname as entityname 
        from partnerships
         where partnerships.pshipentid = entityid 
        union
        select
            concat(lastname, ', ', firstname) as entityname
        from individuals
        where individuals.indentid = entityid 
        union
        select
            shortname as entityname
        from firms
        where firms.firmentid = entityid 
        union
        select
            shortname as entityname
        from funds
        where funds.fundentid = entityid 
        union
        select 
            entityshortname as entityname
        from deletedentities
        where deletedentities.entityid = entityid
    );
    end$$
Mark Bell
  • 28,985
  • 26
  • 118
  • 145
Puneet Purohit
  • 1,243
  • 6
  • 23
  • 42

1 Answers1

1

There's nothing too much wrong with the queries in the function or the unions

However, it is critical to the performance that the following indexes exist:

  • partnerships(pshipentid)
  • individuals(indentid)
  • firms(firmentid)
  • funds(fundentid)
  • deletedentities(entityid)

The other probable issue is that if the function is evaluated over a large set of data, it will be evaluated one row at a time, e.g.

select getEntityName(firms.id)
from firms;

In this case, a set based approach would be preferable. MySql doesn't have Table Valued Parameters (i.e. you can't pass a bunch of entityid's into the function), but there are other workarounds.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285