Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL: How to INSERT a SELECT statement with a GROUP BY clause on a table with IDENTITY column?

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!

like image 867
Hector Terceros Avatar asked Jul 30 '15 18:07

Hector Terceros


People also ask

Can we use GROUP BY in insert query?

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.

Can we use group function in where clause in Oracle?

Group functions cannot be used in WHERE clause. The can appear in SELECT, HAVING and ORDER BY clause.

Can we use order by and GROUP BY Together in Oracle?

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.

Can we use insert and select together?

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.


1 Answers

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!

like image 113
Hector Terceros Avatar answered Oct 11 '22 14:10

Hector Terceros