Have you gotten an ORA-00942 error? I’ll explain the cause and the solution of the error in this article.
ORA-00942 Cause
The error message appears when you try to run an SQL statement:
ORA-00942: table or view does not exist
This happens for one of many reasons:
- The statement references a table or view that does not exist
- You do not have access to that table or view
- The table or view belongs to a different schema and you did not refer to the schema name
- You’re running Oracle 12c, using a sequence as a default value, but don’t have select privileges on the sequence.
The cause of the error should be the same in each database version. It shouldn’t matter if you’re getting this “table or view does not exist” error in Oracle 10g, Oracle 11g, or Oracle 12c.
The only difference is the sequence-related cause mentioned above because one of the new features in Oracle 12c is the ability to use a sequence as a default value.
Let’s take a look at some of the solutions, depending on the cause.
There are several solutions for this error, depending on the cause.
First, check that the table exists. You can do that by running this query:
SELECT owner, object_name, object_type
FROM all_objects
WHERE object_type IN ('TABLE','VIEW')
AND object_name = 'OBJECT_NAME';
Substitute the word OBJECT_NAME with your table name. It must be in upper case as well.
SELECT owner, object_name, object_type
FROM all_objects
WHERE object_type IN ('TABLE','VIEW')
AND object_name = 'CLASS';
Results:
OWNER | OBJECT_NAME | OBJECT_TYPE |
SYSTEM | CLASS | TABLE |
If your table does not show, then it does not exist, and you’ll need to look into why it doesn’t exist.
Or, if you’re using SQL Developer, you can check the table exists by expanding the Tables section on the left side of the screen. If you see the table there, it means it exists and you’re the owner.
Next, check the owner of the table.
If the table exists, and you’re getting this error, then check the owner of the table.
You can use the same query as above, and take note of the owner of the table.
If the owner is not you, then you’ll need to contact the database administrator to request privileges to select from the table (or to perform whatever operation you were trying to do).
Finally, check your query to ensure it refers to the correct schema.
If the table or view exists, and you have the privileges you need, then it could be an issue in your query.
Let’s say your username is “bob”. You have a set of tables under the “bob” schema.
If you want to select from a table called “employee”, and this is in the “mary” schema, it is owned by “mary”. When you refer to the table (such as in a SELECT statement), you might have a query like this:
SELECT *
FROM employee;
You might get the ORA-00942 error at this point. This is because Oracle is looking in your schema, or “bob”, for an employee table. But, it doesn’t exist in your schema – it’s in the “mary” schema.
So, you’ll need to change your query to include the schema name.
SELECT *
FROM mary.employee;
This query should run without the error.
Oracle 12c and Sequences
If you’re getting the ora-00942 table or view does not exist in Oracle 12c, then it could be caused by this situation:
- Another user has a table and a sequence
- One of the columns in the table has a default value of the sequence.nextval
- You have the right privileges on the table
However, you can get this error if you’re querying this table and don’t have select privileges on the sequence.
Consider this situation:
As user “bob”:
CREATE SEQUENCE sequence_book_id;
CREATE TABLE books (
book_id NUMBER(5) DEFAULT sequence_book_d.nextval PRIMARY KEY,
title VARCHAR2(100)
);
GRANT SELECT, INSERT, UPDATE, DELETE ON books TO "mary";
Now, logged in as “mary”:
INSERT INTO books (title)
VALUES ('The Adventure');
You’ll get an ORA-00942 error here.
The reason for this is that “mary” doesn’t have SELECT privileges on sequence_book_id. She has INSERT privileges on the table, but as a result of inserting into the table, a SELECT on the sequence is called, which causes this error.
To resolve this, grant SELECT privileges to the second user.
GRANT SELECT ON sequence_book_id TO mary;
That should now work.
I hope this article has helped you resolve the ORA-00942 error.
Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!
ORA-00942 means that SQL engine found no table or view in your usable scope. In other words, table or view does not exist. The usable scope is a range which defines what tables and views you can use and how you can use them. In reality, almost every SQL developers have ever seen the error before. The real causes of ORA-00942 may be varying from case to case though.
Now let’s take a look at some error patterns of ORA-00942 and their solutions described in the following sections.
- No Right to Use Table
- No Right to Reference Table
- Missing Schema Name
- Misspelled Table Name
- Missing Quotes on Table
- Not a Table Essentially
No Right to Use Table
Let’s see an example, which is to query a table owned by someone else.
SQL> conn sh/sh
Connected.
SQL> select first_name from hr.employees where last_name = 'Chen';
select first_name from hr.employees where last_name = 'Chen'
*
ERROR at line 1:
ORA-00942: table or view does not exist
TOAD Error ORA-00942: Table or View Does not Exist
This error pattern is caused by a very elementary concept on using the database system. By default, we cannot use other user’s objects until we are granted to do it, otherwise, we will see ORA-00942. You might think that every user knows the basic knowledge, actually, some don’t.
To know all tables that we can use, please query ALL_TABLES dictionary view with specifying table owner.
SQL> select * from all_tables where owner = 'HR';
no rows selected
As we can see, there’s no matching table from owner HR in this case. That’s why we got ORA-00942 because we don’t have SELECT privilege on that table, we can’t pretend it’s existing in our visual scope.
In fact, not only by querying ALL_TABLES, there’re several ways that can instantly check if the table has been ever granted to you for using.
Solutions to ORA-00942
The solutions to ORA-00942 are simple, you can either ask DBA or the table owner for the object privilege SELECT. In other words, draw it into our visual scope.
SQL> grant select on hr.employees to sh;
Grant succeeded.
System privilege SELECT ANY TABLE is also a cure to ORA-00942, but it may be too strong to be granted to a normal user, especially when the user is used by public database links, it would become a security hole, even though some restrictions are imposed on database links.
For DBA, we should keep least required privileges of the account that accesses a database in order to prevent unexpected security vulnerabilities, although it somewhat compromises on fighting ORA-00942.
In some cases, users may need SELECT privileges on all tables of another owner, but granting each of every tables could be a tedious job to do. DBA had better know some tricks about how to grant all tables owned by other user at a time in case of occasional ORA-00942.
View vs Synonym
Let’s study a more advanced case about ORA-00942, which involves DBA who tried to CREATE VIEW for a third party.
SQL> conn / as sysdba
SQL> create view sh.employees as select * from hr.employees;
create view sh.employees as select * from hr.employees
*
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-00942 in here did not mean that DBA has no right to use the table, it was meant for the third user SH in this case. OK, we tried anther way around by creating a synonym for the grantee, SH.
SQL> create synonym sh.employees for hr.employees;
Synonym created.
Although the synonym was created successfully without ORA-00942, it’s useless until the base table is granted to the grantee, i.e. to be seen as existing in grantee’s scope. As has been noted, the principle is always the same, the user must have proper privileges to use other’s objects.
What will see if we try to describe the synonym?
SQL> conn sh/sh
Connected.
SQL> desc SH.EMPLOYEES;
ERROR:
ORA-04043: object "HR"."EMPLOYEES" does not exist
In the above, we tried to describe the synonym, but it handed over the base table eventually. Consequently, ORA-04043 was thrown instead of ORA-00942 for the unknown object.
No Right to Reference Table
If your constraint needs to reference a table owned by others, you should get an object privilege called REFERENCES on the table. For example:
SQL> conn sh/sh
Connected.
SQL> create table temp (id number, e_id number, text varchar2(30));
Table created.
SQL> alter table temp add constraint fk_eid foreign key (e_id) references hr.employees (employee_id);
alter table temp add constraint fk_eid foreign key (e_id) references hr.employees (employee_id)
*
ERROR at line 1:
ORA-00942: table or view does not exist
Solutions to ORA-00942
To resolve ORA-00942 in such situation, we should grant REFERENCES on the table to grantee like this:
SQL> conn hr/hr;
Connected.
SQL> grant references on hr.employees to sh;
Grant succeeded.
Let’s try to add the foreign key again.
SQL> conn sh/sh
Connected.
SQL> alter table temp add constraint fk_eid foreign key (e_id) references hr.employees (employee_id);
Table altered.
As we can see, a reference constraint that points to another user’s table was added.
SELECT vs REFERENCES
Now it’s time to know some points on the differences between SELECT privilege and REFERENCES privilege.
- SELECT privilege is not the right choice to solve ORA-00942 in such error pattern. As a result of only SELECT privilege presents, you will get ORA-01031 instead of ORA-00942 in this case.
- For convenience, you can grant SELECT object privilege to a role, but you cannot grant REFERENCES to a role, which will fail with ORA-01931.
- There is NO such system privilege called REFERENCE ANY TABLE just like SELECT ANY TABLE available to DBA to grant to. No, not such thing.
Missing Schema Name
First of all, we granted SELECT privilege on a table EMPLOYEES of HR to SH, which means SH can query EMPLOYEES even though it does not belong to him.
SQL> conn hr/hr
Connected.
SQL> grant select on employees to sh;
Grant succeeded.
Phenomenon
As the user SH, we tried to query the table.
SQL> conn sh/sh
Connected.
SQL> select first_name from employees where last_name = 'Chen';
select first_name from employees where last_name = 'Chen'
*
ERROR at line 1:
ORA-00942: table or view does not exist
Why is ORA-00942? Haven’t we been granted to access the table? This is because we forgot to prefix schema name. Without schema name prefixed, SQL parser will search for the table in the scope of current user, SH. We had better to query USER_TABLES to list all tables that belongs to current user SH for sure.
Solutions to ORA-00942
We can have several solutions to ORA-00942 here, the first one is very straightforward, just prefix the schema name.
1. Prefix Schema Name
SQL> select first_name from hr.employees where last_name = 'Chen';
FIRST_NAME
--------------------
Ed
Prefixing the schema name in every kind of statements could be the safest way to use schema objects, especially when you are using a database link to retrieve data from the remote database. I talked about some examples of using database link including rights and wrongs in another post: DB Link, How and Why
2. Use Private or Public Synonyms
If the schema name must be ignored for some reasons, you can create a synonym, either private or public one for this table.
For current user only, we can create a private synonym for this table:
SQL> conn sh/sh
Connected.
SQL> create or replace synonym employees for hr.employees;
Synonym created.
For all users, we can create a public synonym for this table:
SQL> conn / as sysdba
Connected.
SQL> create or replace public synonym employees for hr.employees;
Synonym created.
Now we can reissue the statement again without problems, this is because the synonym will be replaced with the base object at run-time.
SQL> select first_name from employees where last_name = 'Chen';
FIRST_NAME
--------------------
Ed
That is to say, ORA-00942 can be solved without changing statements by using a synonym. We can save our time on modifying the original programs.
3. Switch Working Schema Name
If we would like to use other’s schema for the rest of SQL statements, we can switch current schema to the owner by this:
SQL> alter session set current_schema=hr;
Session altered.
In this way, we set the current schema as HR, so we can ignore the schema name for rest of statements. In other words, we don’t need to prefix schema name to solve ORA-00942, because our working schema has been changed.
SQL> select first_name from employees where last_name = 'Chen';
FIRST_NAME
--------------------
Ed
That’s the trick to avoid ORA-00942 without changing statements in your programs, just don’t forget to revert the setting afterwards.
Misspelled Table Name
We might think we were right, but eventually, we were wrong. For example:
SQL> select first_name from hr.emlpoyees where last_name = 'Chen';
select first_name from hr.emlpoyees where last_name = 'Chen'
*
ERROR at line 1:
ORA-00942: table or view does not exist
Do you notice that? I misspelled the table name deliberately, as a result, ORA-00942 was our company. In fact, misspelling happens all the time. A misspelled table or view of course is not existing. Just like we wanted to type «like», but we typed «liek» eventually.
Solutions to ORA-00942
Please make sure the identifier is correct by querying ALL_TABLES to list the correct table name that we can use, even though they belong to other users.
SQL> select table_name from all_tables where owner = 'HR';
TABLE_NAME
------------------------------
EMPLOYEES
If you found nothing wrong, just call someone else to help you to identify the mistake. It’s especially helpful when you cooperate with a senior developer.
Some GUI tools like Toad, PL/SQL developer or SQL developer can also reduce ORA-00942 by automatically completing the object name in their SQL editors. For sqlplus users, sorry, it does not have any spell checker.
Autocomplete Table Name in SQL Developer Editor so as to Avoid ORA-00942
Missing Quotes on Table
Seriously, I have talked about database object naming rules a lot including non-quoted and quoted name and how to use them properly. This is exactly the same case related to naming rules.
First of all, we create a table small in exact form by quoting the name.
SQL> create table "small" (c1 int);
Table created.
Phenomenon
Then, we tried to query this new table by this:
SQL> select * from small;
select * from small
*
ERROR at line 1:
ORA-00942: table or view does not exist
Without quoting table name, the query was looking for an upper-cased table named SMALL by default, not small from SQL parser’s eyes. Consequently, SQL parser found nothing existing and threw ORA-00942 to notify this issue. This might sound strange, but this is how the exact form, the quoted naming rule works.
Solutions to ORA-00942
Just use exactly the same quoted name as we provided in table definition.
SQL> select * from "small";
no rows selected
Good! At least we have no ORA-00942 this time.
For proving this, we may check the original table name by this query.
SQL> select table_name from user_tables order by 1;
TABLE_NAME
------------------------------
...
small
...
Eventually, it’s a lower-cased table comparing to normal upper-cased tables. Furthermore, we can create a table with a case-insensitively same name.
SQL> create table small (c1 int);
Table created.
There is no trick, even though I used an lower-cased name without quotes in the statement, an upper-cased table named SMALL was created which differs from small within the namespace of current user.
SQL> select table_name from user_tables order by 1;
TABLE_NAME
------------------------------
...
SMALL
small
...
Also, there is no name collision, no ORA-00942 as long as they are essentially different.
Not a Table Essentially
Some database objects may act like tables, but they are not tables essentially. Here is a sample object named HAPPY_EMPLOYEES.
SQL> select first_name, last_name from happy_employees;
FIRST_NAME LAST_NAME
-------------------- -------------------------
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
Jose Manuel Urman
Luis Popp
6 rows selected.
ORA-00942 when ALTER TABLE
Let’s see an example of ALTER TABLE.
SQL> alter table happy_employees move;
alter table happy_employees move
*
ERROR at line 1:
ORA-00942: table or view does not exist
The error message told us that it tried to find a table named HAPPY_EMPLOYEES, but nothing is found.
ORA-00942 when DROP TABLE
You can not even DROP TABLE.
SQL> drop table happy_employees purge;
drop table happy_employees purge
*
ERROR at line 1:
ORA-00942: table or view does not exist
Has the table been removed before our actions? As a matter of fact, the object is not a table, even though it looks like a table. That’s why SQL parser flagged its non-existence problem.
Solutions to ORA-00942
Now, we have to know what the object type it is. A dictionary view USER_OBJECTS can be helpful.
SQL> select object_type from user_objects where object_name = upper('happy_employees');
OBJECT_TYPE
-------------------
VIEW
As a result, it’s a VIEW. Now the question is: What is the base table? How can we find it? Actually, we can learn the fact by querying USER_VIEWS:
SQL> select text from user_views where view_name = upper('happy_employees');
TEXT
--------------------------------------------------------------------------------
select first_name, last_name from employees where department_id = 100
Not only views, but synonyms are also schema objects based on tables. That is to say, no matter what you are trying to do is ALTER TABLE or DROP TABLE, you should do it on their base tables in case of ORA-00942.
ORA-00942 is one of the many errors which Oracle developer ,Oracle DBA often gets.
Lets first look at the OERR output
Cause: The Oracle table or Oracle view entered does not exist, a synonym that is not allowed here was used, or a view was referenced where a table is required.
Existing user tables and views can be listed by querying the data dictionary. Certain privileges may be required to access the table. If an application returned this message, the table the application tried to access does not exist in the database, or the application does not have access to it.
Action: Check each of the following:
- the spelling of the table or view name.
- that a view is not specified where a table is required.
- that an existing table or view name exists.
- Contact the database administrator if the table needs to be created or
if user or application privileges are required to access the table.
Checklist to run for ORA-00942
(1) If you user owns the table or view ,check for spelling mistakes. Query User_objects to check if the table or view exists
select object_name,object_type from user_objects;
(2) If you dont own the table or view, check if you have permission for the table or view. Query all_objects to check if the table or view you are querying is having permission
select * from all_objects where object_type in ('TABLE','VIEW') and object_name = '&1';
If it is not shown here, it means you dont have access to that particular view.You have to get access for the view for the table
GRANT privileges ON object TO user;
Following access can be granted
If the synonym is not created , then you have to use the owner.<table_name> to access the table
Desc <owner>.<table_name>
select * from <owner>.<table_name>;
You can create public synonym using the below command
create public synonym exp_table for test.exp_table
(3) ORA-00942 may also occurs while refreshing a Oracle Materialized views
You will need to check all the tables in the materialized query to find out the issue. You can use sql trace to find that
Sometimes while creating the table,special character get copied ,So you may get this error. Check the table name in all_tables and then act accordingly.
Related Articles
ORA-00936 missing expression
ORA-00904: invalid identifier
ORA-00257: archiver error. Connect internal only, until freed.
ORA-06512 at line num
Oracle Create table
ORA-00911: invalid character
Oracle documentation
Reader Interactions
Содержание
- 1 Исправьте ошибку ora-00942
- 1.1 Недостаточно прав пользователя
- 1.2 Таблица или представление на самом деле не существуют
- 1.3 Таблица или представление находятся в другой схеме
Иногда вы видите ошибку ora-00942 при выполнении оператора SQL. У него есть несколько причин, и, как обычно, синтаксис ошибок не является наиболее описательным. Если вы сталкиваетесь с этим и хотите знать, как исправить ошибку ora-00942, читайте дальше.
Насколько я знаю, есть три основные причины ошибки ora-00942:
- Недостаточно прав пользователя
- Таблица или представление на самом деле не существуют
- Таблица или представление находятся в другой схеме
Я покажу вам, как обратиться к каждому.
Исправьте ошибку ora-00942
Прежде всего, небольшой отказ от ответственности. Я не администратор баз данных, я администратор Windows, а также специалист по аппаратному и настольному оборудованию. Я знаю, как запустить SQL, но не до какой-то степени опыта и, конечно, не до уровня, который может устранять проблемы. Я должен был попросить моего друга Oracle DBA о помощи, поэтому, пока я писал эту часть, все умные биты принадлежали ему.
Этот список из трех причин ошибки ora-00942 не является исчерпывающим. Есть, очевидно, другие случайные причины этого, но эти три, по-видимому, наиболее распространены.
Недостаточно прав пользователя
Одной из основных причин ошибки ora-00942 является то, что у пользователя недостаточно прав для доступа к рассматриваемой таблице. Вы можете проверить это, выполнив два запроса.
-- перечислить системные привилегии для пользователя или роли SELECT * FROM dba_sys_privs ГДЕ получатель гранта (user_role, 'PUBLIC');
— список привилегий объекта для пользователя или роли
SELECT грантополучатель, владелец || '.' || объект table_name, привилегия, грантируемое FROM dba_tab_privs ГДЕ получатель гранта (user_role) ORDER BY грантополучатель, владелец || '.' || table_name, привилегия;
Эти двое скажут вам, имеет ли данный пользователь правильные привилегии для запуска команды. Если пользователь имеет правильные привилегии, переходите к следующему. Если пользователь не имеет правильных привилегий, предоставьте их им или попросите администратора БД сделать это.
Ошибка ora-00942 также может возникнуть, если пользователь используемой схемы имеет привилегии INSERT, но не привилегии SELECT. Опять же, проверьте уровень привилегий и добавьте SELECT в список или попросите администратора БД сделать это. Очевидно, что каждой схеме должна быть предоставлена определенная привилегия SELECT, в противном случае вы все равно увидите ошибку ora-00942.
Таблица или представление на самом деле не существуют
Причиной ошибки ora-00942 может быть неправильный синтаксис запроса или отсутствие таблицы. Хотя это может показаться логичным для начала, я уверен, что привилегия пользователя является причиной ошибки номер один. Таблица, которой там нет или используется неверный синтаксис таблицы, занимает второе место.
Чтобы проверить, существует ли таблица, сначала проверьте синтаксис запроса. Если синтаксис правильный, запустите этот запрос.
ВЫБЕРИТЕ владельца, имя_объекта, тип_объекта ОТ всех_объектов WHERE object_type IN ('TABLE', 'VIEW') AND имя_объекта = ‘YOUR_TABLE_NAME ';
В последней строке вставьте фактическое имя таблицы, где вы видите «YOUR_TABLE_NAME». Это должно точно сказать вам, существует ли таблица, к которой вы пытаетесь обратиться, или нет. Если он возвращается без таблицы, запрашиваемая вами таблица не существует в схеме или базе данных.
Если в используемой вами системе есть меню «Таблицы», вы можете вручную проверить таблицу, если хотите, но вышеуказанный запрос выполняет свою работу.
Таблица или представление находятся в другой схеме
Если у пользователя есть права, и таблица существует, но вы все еще видите ошибку ora-00942, скорее всего, это связано со схемой. Если вы управляете несколькими схемами, легко выполнить запрос к схеме, которая не принадлежит вам. Когда вы заняты и против этого, это простая ошибка, чтобы сделать.
Проверьте схему вручную, если можно или добавьте имя схемы в строке ОТ вашего запроса. Если у вас нет правильных привилегий для новой схемы, вы снова увидите ошибку ora-00942. Вернитесь к первому исправлению привилегий пользователя и проверьте соответствующую схему или попросите своего администратора базы данных сделать это за вас.
Как упомянуто выше, я проконсультировался с моим приятелем по DBA Oracle для этой работы, так что вся заслуга ему в тяжелой работе. Если вы обнаружите здесь какие-либо ошибки или упущения, они одни. Дайте мне знать в разделе комментариев, если я что-то пропустил или ошибся, и я исправлю это.
Если вам известен какой-либо другой способ исправить ошибку ora-00942, сообщите нам об этом ниже!