Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better Sub-Query or JOIN in SQl query?

Can any one suggest which one is better in this case:

1:

SELECT
    COLUMN1, 
        (SELECT 
            COLUMN2 
        FROM
            TABLE2
        WHERE 
            <some condition>) AS COLUMN2
FROM TABLE 1 

2:

SELECT
    T1.COLUMN1,
    T2.COLUMN2
FROM
    TABLE1 T1
INNER JOIN 
    TABLE2 T2 ON <some condition>
like image 838
Smruti Ranjan Sahoo Avatar asked Dec 05 '25 10:12

Smruti Ranjan Sahoo


2 Answers

There are several axis of "better"...

  • Better performance
  • Better readability
  • Better maintainability
  • Better flexibility ....

    So,

    1. Test and find out (examine plans they may be identical)
    2. In the eye of the beholder, where the queries are equvalent I prefer joins
    3. Depends on your staff
    4. Doesn't seem applicable in this case ...

Better is frequently just a trade off...

like image 100
jmoreno Avatar answered Dec 08 '25 01:12

jmoreno


Use JOIN.

Subqueries vs joins

like image 20
Spencer Ruport Avatar answered Dec 08 '25 01:12

Spencer Ruport



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!