In an application, I intend on truncating and inserting on an Oracle 12c database, but have found this issue with an IDENTITY
column. Even though the INSERT... SELECT
statement works on most SELECT
uses I have tried, when this statement also has a GROUP BY
clause, it fails to work, issuing a "ORA-00979: not a GROUP BY
expression" complaint. Below is some example code:
create table aux (
owner_name varchar2(20),
pet varchar2(20) );
insert into aux values ('Scott', 'dog');
insert into aux values ('Mike', 'dog');
insert into aux values ('Mike', 'cat');
insert into aux values ('John', 'turtle');
create table T1 (
id number generated always as identity,
owner_name varchar2(20),
pet_count number
);
insert into T1 (owner_name, pet_count)
select owner_name, count(*) as pet_count from aux group by owner_name;
select owner_name, count(*) as pet_count from aux group by owner_name;
It works on the first insert, but fails on the next.
EDIT: I've changed the code so the issue is easier to understand while still reproducible.
Appreciate the help!
In this page, we have discussed how to insert values into a table using MySQL INSERT INTO statement, when the column names and values are collected from another identical table using MySQL SELECT and GROUP BY. This way you can insert the rows of one table into another identical table for a specific group.
Group functions cannot be used in WHERE clause. The can appear in SELECT, HAVING and ORDER BY clause.
Using Group By and Order By TogetherThe GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.
You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
In the Oracle Community, this question has been answered. https://community.oracle.com/message/13227544#13227544
insert into T1 (owner_name, pet_count)
with t as (select /*+ materialize */ owner_name, count(*) as pet_count from aux group by owner_name)
select owner_name, pet_count from t
Quoting the original answer, keep in mind the materialize hint is not documented. Thanks to all for your help!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With