Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORA-00907 Missing right parenthesis issue - select with order by inside insert query

I am trying to do insert to a table and it uses one select statement for one column. Below is the illustration of my query.

INSERT INTO MY_TBL (MY_COL1, MY_COL2)
VALUES (
(SELECT DATA FROM FIR_TABL WHERE ID = 1 AND ROWNUM = 1 ORDER BY CREATED_ON DESC),
1
);

It throws ORA-00907 Missing right Parenthesis. If I remove ORDER BY from this, it works as expected. But I need order it. How can I fix it?

like image 285
Vaandu Avatar asked Feb 07 '12 11:02

Vaandu


People also ask

How do I fix Ora 00907 missing right parenthesis?

To correct this error, you must find the part of code that contains the missing right parenthesis, insert the missing symbol in the correct spot, and run the statement again.

How do I find missing parentheses in SQL?

Solution 1 – Check Your Pairs of Parentheses If you're using an IDE such as SQL Developer, you can put your cursor next to each parenthesis to see where the matching parenthesis is. If it's in the right spot, great. If the match is showing up somewhere unexpected, then you're missing a parenthesis.

What is missing right parenthesis in Oracle?

ORA-00907: missing right parenthesis error occurs when a left parenthesis is used without a right parenthesis to close it in SQL statements such as create table, insert, select, subquery, and IN clause. The right parenthesis is missing. All parentheses must be used in pairs.


1 Answers

Both the current answers ignore the fact that using order by and rownum in the same query is inherently dangerous. There is absolutely no guarantee that you will get the data you want. If you want the first row from an ordered query you must use a sub-query:

insert into my_tbl ( col1, col2 )
select data, 'more data'
  from ( select data
           from fir_tabl
          where id = 1
          order by created_on desc )
 where rownum = 1
       ;

You can also use a function like rank to order the data in the method you want, though if you had two created_on dates that were identical you would end up with 2 values with rnk = 1.

insert into my_tbl ( col1, col2 )
select data, 'more data'
  from ( select data
              , rank() over ( order by created_on desc ) as rnk
           from fir_tabl
          where id = 1)
 where rnk = 1
       ;
like image 129
Ben Avatar answered Oct 05 '22 16:10

Ben