0

I have a query below, which retrieves data from 3 tables.

select *
from vendor_allocation as va, district as d, vendor as v 
where va.district_id = d.id and va.vendor_id = v.id

In the result there are many null columns and it takes about 315 msec to execute. I would need to omit the null columns and execute the query faster. I tried using COALESCE but dint get expected results. Please help.

8
  • 4
    Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Jul 3, 2017 at 12:22
  • 1
    Also, what is your expected result? List of all Vendors, with district attached?
    – Daniel
    Jul 3, 2017 at 12:25
  • 3
    To "omit" columns, don't put them in the select list. Another good example on why select * should never be used in production queries. Jul 3, 2017 at 12:26
  • 1
    select * returns all columns. Define the columns you want to return by listing them (eg select somecolumn, someothercolumn, jcwashere from somekindatable
    – JohnHC
    Jul 3, 2017 at 12:27
  • I have to add a sentence to the comment of @GordonLinoff : Using commas you performa a cross join i.e. Cartesian Product. Each row from vendot_allocation is combined with each row of district which is then combined with vendor. This results in a huge amount of meaningless data Jul 3, 2017 at 12:28

2 Answers 2

0

The following query will return only those values that are present across all the tables. Use a left join if you want to consider the rows in vendor_allocation that might not have corresponding rows present in district / vendor. Those rows will be returned with null as values in the joined table.

select *
from vendor_allocation as va
  join district as d using ON va.district_id = d.id
  join vendor as v using ON va.vendor_id = v.id;

Using LEFT JOIN

select *
from vendor_allocation as va
  left join district as d ON va.district_id = d.id
  left join vendor as v ON va.vendor_id = v.id;
0

This would give you a list of Vendors, with attached district. If you don´t want the ones without district, use an inner join:

select v.VendorName, d.DistrictName 
from vendor as v 
left join vendor_allocation as va
on v.id=va.vendor_id 
left join district as d
on va.district_id =d.id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.