简体   繁体   中英

Oracle SQL - Understanding how the Dual table works its magic

In the process of making a small test table I stumbled across the following article online: ( http://www.techonthenet.com/sql/insert.php ) which gives the following solution on how to insert multiple rows of fixed values in Oracle:

Insert All
Into testTable (key, field1, field2) Values (1, 10, 'a')
Into testTable (key, field1, field2) Values (2, 20, 'b')
Into testTable (key, field1, field2) Values (3, 30, 'c')
Into testTable (key, field1, field2) Values (4, 40, 'd')
Select * from dual;

The use of dual was something I hadn't seen before and so I started doing a little research to understand how it works. I understand that this table is a workaround for certain oracle syntax but how it accomplishes theses tasks still isn't clicking for me. I'm aware that others have asked a similar question ( How does Oracle SELECT FROM dual work with multiple fields ) but I've yet to see anyone explain what's actually going on underneath the hood.

  • Is this a referential trick that they are able to pull off with a single valued table or are certain functions in Oracle just hardcoded to act differently when they see the dual table?

  • More specifically how does referencing it allow the code above to essentially loop through multiple Into ... Values ... statements?

Could somebody explain this to me?

Functionally, dual is merely a single-row table that you happen to be able to count on always existing and always having exactly 1 row. You could just as easily create your own single-row table and use that instead of dual . Or you could use a query that you know will always return 1 row (ie select * from all_objects where rownum < 2 ).

Behind the scenes, Oracle is able to optimize queries against dual a bit more than against a single-row table that you create. The optimizer knows that the table always has exactly 1 row so it can optimize things based on that. And Oracle can potentially eliminate the need to even hit the table using a "fast dual" operation to avoid doing any logical I/O. These optimizations aren't the sort of thing that you'll notice in a query like this, they are potentially useful when you're doing something like hitting dual in a tight loop to compute a variety of expressions.

In this case the select * from dual only exists because a multi-table INSERT statement needs a query as the source. Normally, when you're creating a multi-table INSERT , you would select the data from a source and insert some or all of it to multiple tables. In this case, though, you're not actually using the data that comes from the SELECT statement at all so it doesn't matter what you select or what you select the data from.

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