Sql error ora 00942 table or view does not exist

Have you gotten an ORA-00942 error? I’ll explain the cause and the solution of the error in this article.

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.

Class Table in Tree Explorer

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!

sql error ORA-00942: Table Or View Does Not Exist by manish sharma

SQL error ORA-00942: Table Or View Does Not Exist is very common. I was reading your comments the other day. Consequently I saw that some of you guys are having a problem in finding objects like table or views in the schema and facing an error. 

So what does this “ORA-00942: Table or View Does not Exist” error means?

It means exactly what it says, the table or view you are executing your query on does not exist in your schema. To explain, whenever you execute a query which includes a table, view, synonym or a cluster which does not exist into the schema with which you are connected the SQL engine will show you this error.

sql error ORA-00942: Table Or View Does Not Exist by manish sharma

So how can we solve it?

You can easily solve this error either by creating the missing object (by object I mean a table, view, synonym or a cluster) or by importing it from another source into your schema.

Is there any way we can check what objects do we have in our schema?

Yes, we can easily check out how many objects are created and saved in a schema. In addition to their types and names.

Oracle provides a View which comes pre-created into the SYS schema. And using it we can find out how many objects are there in a schema as well as what are their types and names. The name of that view is TAB.

What is this TAB view?

TAB is a pre-created view which is saved into the SYS schema of the Oracle Database. Furthermore this view stores the name, type and the cluster id of all the tables, views, synonyms and clusters created into the schema of the database.

Do we need to create this view?

No, TAB view is created by Oracle engine during the creation of the database thus you don’t have to worry about it. 

Can we use this view in any schema of the database?

TAB view can easily be accessed by any user/schema of the database through its public synonym. Moreover along with the TAB view, Oracle engine also creates its public synonym with the same name. Which provides the secure access to the TAB view to any schema in the database.

In addition, both the TAB view and its public synonym share the same name which is TAB and the same structure, so don’t be confused.

What is the structure of the TAB view?

TAB view consists of three columns, TNAME, TABTYPE, and CLUSTERID. First two columns are of VARCHAR2 type and hold the name of the database object and their types. Meanwhile the third column is of NUMBER type and holds the Cluster ID of the cluster if you have created any in your schema.

Check out the structure of TAB view here.

sql error ORA-00942: Table Or View Does Not Exist by manish sharma

Info Byte:
You can check out the structure of the TAB view just by using DESCRIBE command, Like this
DESC TAB;

Ok, I think I have answered almost all the questions about the TAB view. Do you think something is left out or you still have some doubts? Then feel free to write to me on my Facebook or Twitter.

Anyways, now let’s do some examples.

You first need to connect with the schema whose object’s information you want to find out. For example, let’s say I want to find out how many objects are created in HR schema and what are their names. Once you have decided that go ahead and connect your database with that schema.

You can read my blog on how to connect with the database using SQL Developer and SQL*Plus as well.

Before showing you the examples of TAB view let me tell you that I am connected to my database through the HR user. But you can use any of these queries in any user/schema of your desire. They will show you the result accordingly.

Example 1: Show me the complete information about all the tables, views, synonyms and clusters created in my schema.

SELECT * FROM tab;

On successful execution, the above query will show you the name, type and the cluster id of all the tables, views, synonyms and clusters created in the schema with which you are connected.

Example 2: Show me the total number of objects created into my schema.

In order to find out the total number of objects created in a schema, you can use the COUNT function with the TAB view. Like this

SELECT count (*) FROM tab;

On successful execution, this query will show you the total number of objects created in your schema.

Example 3: Show me how many tables are there in the schema and what are their names.

In order to find out the information of a specific object, you can use the WHERE clause and filter the result.

SELECT * FROM tab WHERE tabtype = ‘TABLE’;

This query will show the information of all the objects of the schema which are tables. You can refine this query even more like this:

SELECT tname FROM tab WHERE tabtype = ‘TABLE’;

This will show you only the names of all the tables created into the schema. In case you only want to find out the total number of tables created into the schema then you can modify this query like this:

SELECT count (*) FROM tab WHERE tabtype = ‘TABLE’;

This will show you the total number of tables created in your schema.

Like this you can tweak the queries according to your needs.

Now, if you have gone through the blog carefully then take this poll on my Facebook page and check out your knowledge.

Yes, I do have Facebook and I post a lot of Programming Quizzes there!

ORA-00942 is one of the many errors which Oracle developer ,Oracle DBA often gets.

Lets first look at the OERR output

ORA-00942 table or view does not exist

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 viewsORA-00942

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:

  1. Недостаточно прав пользователя
  2. Таблица или представление на самом деле не существуют
  3. Таблица или представление находятся в другой схеме

Я покажу вам, как обратиться к каждому.

Исправьте ошибку 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, сообщите нам об этом ниже!

Skip to content

ORA-00942 Table or View Does Not Exist Oracle Error

ORA-00942 Table or View Does Not Exist Oracle Error

Sometime when you compile an object or package or view in Oracle, or execute some PL/SQL statements on Oracle table, or when running an Oracle program or application, the following error my occurs:

ORA-00942: table or view does not exist

The cause or reason for ORA-00942 error message is because of Oracle tries to execute an SQL statement that references a table or view that either does not exist, or because of a synonym that is not allowed here was used, or because of you do not have access rights to the particular object. Other possible cause is that the table or view belongs to another schema and you didn’t reference the table by the schema name, or a view was referenced where a table is required.

Depending on what’s the cause of the problem, there are several resolutions or remedies to resolve this error. And due to several possible reasons that may cause the error, there are several actions or steps that you can take to identify where is the error and take the appropriate workaround or solution.

  1. Check existing user tables and views if they exists in Oracle by querying the data dictionary by executing the following SQL statement:
    select *
    from all_objects
    where object_type in ('TABLE','VIEW')
    and object_name = 'OBJECT_NAME';

    Replace OBJECT_NAME with the name of the table or view that you want to verify its existence.

    If this error occurred because the table or view does not exist, take the following actions:

    • Check and ensure that the spelling of the table (does not misspell) or view name is correct.
    • Check and ensure that a view is not specified where a table is required.
    • If no such table or view exists, create the table or view, or use another table or view.
  2. If the table or view exists, check and verify if the user has the necessary permissions and rights to read and access (i.e. select) from the table, as certain privileges may be required to access the table. In this case, you will need to have the owner of the table or view, or a Oracle DBA to grant the appropriate privileges, permissions or rights to this object.

    Note that when selecting from a system view (such as v$session) the privilege or access rights to select from the view must be granted to the user directly and not via a role. This is the case if you can select from the view without problem but then get this error when trying to create a view on it.

  3. If the table or view exists but is in a different schema from the current schema where the SQL is executing (in other word, the table doesn’t own by you, but owned by other user), the ORA-00942 error will return too. Resolve this by explicitly reference the table or view by specifying the schema name, i.e. schema_name.table_name.

About the Author: LK

LK is a technology writer for Tech Journey with background of system and network administrator. He has be documenting his experiences in digital and technology world for over 15 years.Connect with LK through Tech Journey on Facebook, Twitter or Google+.

Page load link

Go to Top

Понравилась статья? Поделить с друзьями:
  • Sql error ora 00917 missing comma
  • Sql error ora 00907 missing right parenthesis
  • Sql error ora 00904
  • Sql error or missing database near syntax error
  • Sql error or missing database incomplete input