简体   繁体   中英

Best practices of Oracle LEFT OUTER JOIN

I am new to sql, i use Sql Developer (Oracle db). When I need to select some data with null values I write one of these selects:

1)

SELECT i.number
      ,i.amount
      ,(SELECT value FROM ATTRIBUTES a
        WHERE a.parameter = 'aaa' AND a.item_nr = i.number) AS atr_value
FROM ITEMS i

2)

SELECT i.number
      ,i.amount
      ,a.value as atr_value
FROM ITEMS i
left outer join ATTRIBUTES a
    on a.parameter = 'aaa'
   and a.item_nr = i.number

Questions:

  1. What is difference?
  2. How first approach is called (how can I google it)? Where can I read about it?
  3. Which one should I use further (what is best practices), maybe there is better way to select same data?

Axample of tables:

在此处输入图片说明

In case there is never more than one matching row in table attributes, the queries do the same. It's just two ways to query the same data. Both querys are fine and straight-forward.

In case there can be more than one match, query one (which is using a correlated subquery) would fail. It would be inappropriate for the given task then.

The query with the outer join is easier to extend, when you want a second column from the attributes table.

The first query makes it crystal-clear that you expect zero or one matches in table attributes for each item. In case of data inconsistency or if you have an error in your query such as a forgotten criteria, it will fail, which is good.

The second query would simply retrieve more rows in case of such error, which may not be desired.

So it's a matter of personal preference and of your choice how the query is to deal with inconsistencies which query to choose.

Your two queries are not exactly the same. If you have multiple matches in the second table, then the first generates an error and the second generates multiple rows.

Which is better? As a general rule, the LEFT JOIN method (the second method) is considered the better practice than the correlated subquery (the first method). Oracle has a pretty good optimizer and it offers many ways of optimizing joins. I also think Oracle can use JOIN algorithms for the correlated subqueries (not all databases are so smart). And, with the right indexes, the two forms probably have very similar performance.

There are situations where correlated subqueries have better performance than the equivalent JOIN construct. For this example, though, I would expect the performance to be similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM