Oracle SQL: Using subquery factoring in an INSERT statement
I use subquery factoring a lot, to make my SQL queries easier to write. This basically means that most of my queries these days start with WITH rather than SELECT. (this feature was introduced in the 9i release of the Oracle Database).
Today I was wondering whether I can also use subquery factoring in INSERT statements. You probably are familiar with INSERT statements that go like:
INSERT INTO <tablename>
FROM … [rest of the query]
Such statements allow us to quickly and in a focused way load a table with records read from other tables (or PL/SQL Table Functions).
The question I had was: can I use WITH <subquery> as <alias>[, <subquery> as <alias>] SELECT value1,value2 from subquery,…. [rest of the query] inside an INSERT statement.
Best way to find it out – try and do it.
I have create a simple table (required for some other demo scenario) with seats in airplane:
I would like to create rows for this table. Let’s assume a plane with 46 rows and 6 seats in each row. Would it be possible to create these SEAT records using this statement:
Copy and paste the statement into SQL*Plus and execute. Low and behold:
The conclusion can be: WITH and subquery factoring can in fact be used in INSERT statement, allowing even greater control over which rows will be generated and/or selected to be inserted.
- Subquery Factoring in Oracle 11g
- Oracle RDBMS 11gR2 – new style hierarchical querying using Recursive Subquery Factoring
- Oracle RDBMS 11gR2 – Solving a Sudoku using Recursive Subquery Factoring
- Oracle 11gR2 – alternative for CONNECT_BY_ISLEAF function for Recursive Subquery Factoring (dedicated to Anton)
- Factorial in Oracle SQL – using both new Recursive Subquery and classic Connect By approach
- The AMIS Summary of Oracle OpenWorld 2013 is available for download – 60-page white paper
- On the integrity of data in Java applications – presentation from JFall 2013
- Enriching XMLType data using relational data – XQuery and fn:collection in action
- Java 8 – Collection enhancements leveraging Lambda Expressions – or: How Java emulates SQL
- Oracle Database SQL – Recursive Subquery to inspect events in football matches – find the MVP
- Oracle Database 12c: Find most valuable player using MATCH_RECOGNIZE in SQL
- Oracle Database 12c: Pattern Matching through MATCH_RECOGNIZE in SQL
- Oracle Database 12c: joining and outer joining with collections
- Oracle Database 12c: PL/SQL package UTL_CALL_STACK for programmatically inspecting the PL/SQL Call Stack
- Oracle Database 12c: In Line PL/SQL Functions in SQL queries