I have two tables, sprockets
and cogs
.
create table sprockets(
id NUMBER
);
INSERT into sprockets VALUES (4);
INSERT into sprockets VALUES (8);
INSERT into sprockets VALUES (15);
INSERT into sprockets VALUES (16);
INSERT into sprockets VALUES (23);
INSERT into sprockets VALUES (42);
create table cogs(
id NUMBER
);
I want to take some ids from sprockets
and put them into cogs
.
insert into cogs select id from sprockets s where s.id < 40 and MOD(s.id, 3) != 0;
This adds sprockets 4, 8, 16, 23 to cogs
as expected.
4 rows inserted
As my sprocket making business grows, the business logic for determining which sprockets require cogs will become much more complicated. So I would like to use a sequence of temporary tables that filter out non-candidate sprockets. I believe this is more maintainable than a one line statement with no comments.
--sprockets with ids greater than 40 are too big to frob,
--so it's impossible to weld a cog to them
with frobbableSprockets as(
select id from sprockets where sprockets.id < 40
),
--non-greppable sprockets have built-in harmonic oscillators,
--so cogs are not required
greppableFrobbableSprockets as(
select id from frobbableSprockets f where MOD(f.id,3) != 0
),
--not pictured: more filtering using arcane business logic,
--including but not limited to:
--whether it is raining on a tuesday,
--and if the moon is in the seventh house.
--sprockets with ids less than 3 are from the legacy system and already have cogs
sprocketsRequiringCogs as(
select id from greppableFrobbableSprockets f where f.id > 3
)
insert into cogs select id from sprocketsRequiringCogs
This code is relatively readable, but unfortunately it does not work!
insert into cogs select id from sprocketsRequiringCogs
Error at Command Line:18 Column:2
Error report:
SQL Error: ORA-00928: missing SELECT keyword
If I change the last line to select id from sprocketsRequiringCogs
, there is no error, so I know the problem must be in the insert statement and not in the declaration of the temporary tables.
The one-line insert statement works, and the multi-line insert statement does not work. The only difference I see is that the latter is getting its values from a temporary table.
Why can't I insert rows from a temporary table?