Afnan Bashir
Afnan Bashir

Reputation: 7419

Which approach is better to retrieve data from a database

I am confused about selecting two approaches.

Scenario
there are two tables Table 1 and Table 2 respectively. Table 1 contains user's data for example first name, last name etc

Table 2 contains cars each user has with its description. i.e Color, Registration No etc

Now if I want to have all the information of all users then what approach is best to be completed in minimum time?

Approach 1.

Query for all rows in Table 1 and store them all in a list for ex.

then Loop through the list and query it and get data from Table 2 according to user saved in in first step.

Approach 2

Query for all rows and while saving that row get its all values from table 2 and save them too.

If I think of system processes then I think it might be the same because there are same no of records to be processed in both approaches.

If there is any other better idea please let me know

Upvotes: 3

Views: 228

Answers (1)

usr
usr

Reputation: 171178

Your two approaches will have about the same performance (slow because of N+1 queries). It would be faster to do a single query like this:

select *
from T1
left join T2 on ...
order by T1.PrimaryKey

Your client app can them interpret the results and have all data in a single query. An alternative would be:

select *, 1 as Tag
from T1
union all
select *, 2 as Tag
from T2
order by T1.PrimaryKey, Tag

This is just pseudo code but you could make it work.

The union-all query will have surprisingly good performance because sql server will do a "merge union" which works like a merge-join. This pattern also works for multi-level parent-child relationships, although not as well.

Upvotes: 6

Related Questions