Ошибка oracle ora 00933 sql command not properly ended

I have the following code:

begin
for i in 1..2 loop
insert into dba_xy.despatch
select desp_id_seq.nextval,
      dbms_random.string('U',5),
      trunc(dbms_random.value(0000,9999)),
      prod_id from dba_xy.product 
              prod_name from dba_xy.product;        
end loop;

end;

When I run it, oracle gives me the following error message:

prod_name from dba_xy.product;
                        *

ERROR at line 8:
ORA-06550: line 8, column 29:
PL/SQL: ORA-00933: SQL command not properly ended
ORA-06550: line 3, column 2:
PL/SQL: SQL Statement ignored

What I’m trying to do is link the existing prod_id and prod_name with new data inserted into the despatch table. I have set prod_name as a unique key in the product table and prod_id as the primary key and have set both as foreign key constraints in the despatch table. I need to include the prod_name into the despatch table to allow readers of the table to have more understanding of what prod_name needs to be found etc, rather than just giving the prod_id which will make no sense to them at all. But maybe I was thinking that I don’t need prod_id in the despatch table.
Please help.

After dropping the prod_id column from the despatch table, i altered my code:

begin
for i in 1..2 loop
insert into dba_xy.despatch
select desp_id_seq.nextval,
      dbms_random.string('U',5),
      trunc(dbms_random.value(0000,9999)),
              prod_name from dba_xy.product;        
end loop;

end;
/

and the following error message came up about the unique constraint:
begin
*
ERROR at line 1:
ORA-00001: unique constraint (DBA_XY.PROD_NAME_UC) violated
ORA-06512: at line 3

First, separate you queries with a semicolon and fix your SET conditions:

CREATE VIEW cambiodatos AS 
SELECT 
    a.last_name||','||a.first_name AS "Nombre", 
    a.salary AS "Salario", 
    b.name AS "Nombre Departamento", 
    c.name AS "Nombre de Region"
FROM 
    s_emp a, s_dept b, s_region c
WHERE 
    a.dept_id = b.id AND b.region_id = c.id;

UPDATE 
     cambiodatos 
SET 
     name = 'North America'
WHERE 
     last_name = 'Biri'
     AND first_name = 'Ben'

That’s the reason of your error ORA-00933

Second, your UPDATE statement will fail, as the view you created does not contain field name.

This query will compile:

UPDATE 
     cambiodatos 
SET 
     "Nombre de Region" = 'North America'
WHERE 
     "Nombre" = 'Biri, Ben'

, but most probably will fail as s_region is not key-preserved in this view.

To update, use this instead:

MERGE
INTO    s_region c
USING   (
        SELECT  b.region_id
        FROM    s_emp a, s_dept b
        WHERE   a.last_name || ',' || a.first_name = 'Biri, Ben'
                AND b.id = a.dept_id
        ) q
ON      c.id = q.region_id
WHEN MATCHED THEN
UPDATE
SET     c.name = 'North America'

Are you getting the ORA-00933: SQL command not properly ended error? Learn what causes it and how to resolve it in this article.

This error is caused by an SQL statement with a clause that is not allowed for that statement. Some examples that might cause this error are:

  • An INSERT statement with an ORDER BY clause or an INNER JOIN
  • A DELETE statement with an INNER JOIN or ORDER BY clause
  • An UPDATE statement with an INNER JOIN

ORA-00933 Solution

The solution to the ORA-00933 error is to update your query to remove the clause that’s causing the issue. This would depend on the type of query being run.

Let’s take a look at some example solutions.

While you’re here, if you want an easy-to-use list of the main features in Oracle SQL, get my SQL Cheat Sheet here:

INSERT Statement

If you’re getting an “ORA-00933 sql command not properly ended” on INSERT, then it could be because:

  • You have a JOIN keyword (such as INNER JOIN, LEFT JOIN) in the query.
  • You have an ORDER BY in the query.

You might have a query that looks like this:

INSERT INTO student (student_id, first_name, last_name)
VALUES (20, 'Jack', 'Wheeler')
ORDER BY student_id;

This statement fails because the INSERT statement does not support ORDER BY. When you insert data, you don’t need to specify an order. The data is inserted into the table anyway, and the ORDER BY is only used for SELECT queries.

So, to correct the statement and stop the error, remove the ORDER BY:

INSERT INTO student (student_id, first_name, last_name)
VALUES (20, 'Jack', 'Wheeler');

Refer to my guide on the SQL INSERT statement here for more information.

UPDATE Statement

If you’re getting the “ORA-00933 sql command not properly ended” on UPDATE, then your query might look like this:

UPDATE student
SET student.fees_paid = payment.amount
INNER JOIN payment ON student.student_id = payment.student_id;

You can’t use a JOIN clause in an UPDATE statement. To update a value like this, include the JOIN logic in a  subquery:

UPDATE student
SET student.fees_paid = (
  SELECT amount
  FROM payment
  WHERE student.student_id = payment.student_id
);

This statement should now run without errors.

Read my guide on the SQL UPDATE statement for more information.

DELETE Statement

If you’re getting the “ORA-00933 sql command not properly ended” on DELETE, then your query might look like this:

DELETE FROM student
WHERE last_name = 'Smith'
ORDER BY student_id;

The error appears because the ORDER BY does not belong in a DELETE statement. The ORDER BY is only for ordering data returned by a SELECT statement, and serves no purpose in a DELETE statement.

So, change your query to remove the ORDER BY clause:

DELETE FROM student
WHERE last_name = 'Smith';

You can refer to my guide on the SQL DELETE statement for more information.

SELECT Statement

Are you getting an “ORA-00933 sql command not properly ended” in a SELECT query?

Well, the SELECT query can support joins and ORDER BY, so what could be causing it?

There can be several reasons for this:

  • Your SELECT statement is using UNION or UNION ALL, and you have an ORDER BY at any point except the end of the query. You can only have an ORDER BY at the end of the query, not within each UNION.
  • You have forgotten a comma in between tables when selecting them.
  • You’re running Oracle 8i and trying to use INNER JOIN keywords (or similar join keywords). These were implemented in Oracle 9i.

The exact solution will depend on your SELECT query, but here are a few things you can check:

  • Check that you have the right clauses for your query and are in the right place (e.g. not missing a FROM clause).
  • Check that you’re not missing a comma anywhere, such as in the SELECT clause or the FROM clause.
  • Check that you’re not missing a bracket anywhere. This can be made easier with SQL Developer’s matching bracket highlighting or formatting the SQL to see if something is missing. Other IDEs have similar features.

So, that’s how you resolve the ORA-00933 error.

While you’re here, if you want an easy-to-use list of the main features in Oracle SQL, get my SQL Cheat Sheet here:

ORA-00933: команда SQL не закончена надлежащим образом

Причина:

SQL оператор заканчивается несоответствующим выражением. Например предложение ORDER BY может быть включено в оператор CREATE VIEW или INSERT. ORDER BY не может быть использовано для создания упорядоченного VIEW или для INSERT в определенном порядке. Вы будете всегда получать несоответствующее SQL окончание, если вы используете условие IN только с одним аргументом (например ,IN (X) ). Условие IN должно иметь два или более аргументов.

Действие:

Проверьте синтаксис оператора и удалите неподходящие компоненты. У вас всегда есть возможность продублировать SQL предложение, другим оператором. Например, если вы хотите упорядочить строки VIEW, делайте это когда вы запрашиваете VIEW, но не когда вы его создаете. Ошибки также случаются в применениях SQL*Forms, если соединительная линия идентична. Проверьте на идентичность линии и удалите эти пространства (места).

ORA-00933 means that you use an unexpected word or phrase at the position where SQL parser knows what qualified keyword should be. Use cases that throw ORA-00933 may broadly vary. Here’re some cases of the error.

  1. ALTER TABLESPACE
  2. Create Table as Select (CTAS)
  3. Substitution Variable

ALTER TABLESPACE

Tried to add a tempfile to a tablespace, but it failed with ORA-00933.

SQL> alter tablespace temp add tempfile '+DATA/ORCLCDB/ERPAPP2A/TEMP32.dbf' size 10m auto extend on next 10m maxsize unlimited;
alter tablespace temp add tempfile '+DATA/ORCLCDB/ERPAPP2A/TEMP32.dbf' size 10m auto extend on next 10m maxsize unlimited
                                                                                *
ERROR at line 1:
ORA-00933: SQL command not properly ended

Solution

Actually, the keyword is AUTOEXTEND, not AUTO EXTEND. We should correct the statement like this:

SQL> alter tablespace temp add tempfile '+DATA/ORCLCDB/ERPAPP2A/TEMP32.dbf' size 10m autoextend on next 10m maxsize unlimited;

Tablespace altered.

We solve it.

To correctly operate temporary tablespace, you may refer to the post: How to Alter Temporary Tablespace.

Create Table as Select (CTAS)

Tried to backup a table to a another tablespace by CTAS, but it failed with ORA-00933.

SQL> create table hr.employees_bak as select * from hr.employees tablespace example;
create table hr.employees_bak as select * from hr.employees tablespace example
                                                                       *
ERROR at line 1:
ORA-00933: SQL command not properly ended

Solution

This is because the TABLESPACE clause cannot be at the last, it should stick with CREATE TABLE clause

SQL> create table hr.employees_bak tablespace example as select * from hr.employees;

Table created.

Substitution Variable

There’re hundreds of tables like pro001env, pro002env, … and so on.

Let’s see one of these tables.

SQL> desc pro220env
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 C1                                                 NUMBER

When we want to use a substitution variable to execute the statement, it failed with ORA-00933.

SQL> select * from pro'&num'env;
Enter value for num: 220
old   1: select * from pro'&num'env
new   1: select * from pro'220'env
select * from pro'220'env
                 *
ERROR at line 1:
ORA-00933: SQL command not properly ended

As you can see, we use single quotes to isolate the variable, but it’s not working.

Solution

To use substitution variable to concatenate a string, you need a period (.) to separate the substitution variable from rest of characters.

SQL> select * from pro&num.env;
Enter value for num: 220
old   1: select * from pro&num.env
new   1: select * from pro220env

        C1
----------
         1
         2
         3

It works!

By the way, the use case of substitution variables is different from the scenarios of using bind variables.

  • Ошибка ora 28001 the password has expired
  • Ошибка ora 28000 the account is locked
  • Ошибка ora 24247 network access denied by access control list acl
  • Ошибка ora 14400 inserted partition key does not map to any partition
  • Ошибка ora 12519 tns no appropriate service handler found