Sql ошибка таблицы не существует

Because this post is the top one found on stackoverflow when searching for «ORA-00942: table or view does not exist insert», I want to mention another possible cause of this error (at least in Oracle 12c): a table uses a sequence to set a default value and the user executing the insert query does not have select privilege on the sequence. This was my problem and it took me an unnecessarily long time to figure it out.

To reproduce the problem, execute the following SQL as user1:

create sequence seq_customer_id;

create table customer (
c_id number(10) default seq_customer_id.nextval primary key,
name varchar(100) not null,
surname varchar(100) not null
);

grant select, insert, update, delete on customer to user2;

Then, execute this insert statement as user2:

insert into user1.customer (name,surname) values ('michael','jackson');

The result will be «ORA-00942: table or view does not exist» even though user2 does have insert and select privileges on user1.customer table and is correctly prefixing the table with the schema owner name. To avoid the problem, you must grant select privilege on the sequence:

grant select on seq_customer_id to user2;

I changed the datadir of a MySQL installation and all the bases moved correctly except for one.
I can connect and USE the database. SHOW TABLES also returns me all the tables correctly, and the files of each table exists on the MySQL data directory.

However, when I try to SELECT something from the table, I get an error message that the table does not exist. Yet, this does not make sense since I was able to show the same table through SHOW TABLES statement.

My guess is that SHOW TABLES lists file existence but does not check whether a file is corrupted or not. Consequently, I can list those files but not access them.

Nevertheless, it is merely a guess. I have never seen this before. Now, I cannot restart the database for testing, but every other application that uses it is running fine.
But that’s just a guess, I’ve never seen this before.

Does anyone know why this is happening?

Example:

mysql> SHOW TABLES;
+-----------------------+
| Tables_in_database    |
+-----------------------+
| TABLE_ONE             |
| TABLE_TWO             |
| TABLE_THREE           |
+-----------------------+
mysql> SELECT * FROM TABLE_ONE;
ERROR 1146 (42S02): Table 'database.TABLE_ONE' doesn't exist

SK98's user avatar

asked Oct 13, 2011 at 19:07

johnsmith's user avatar

13

Just in case anyone still cares:

I had the same issue after copying a database directory directly using command

cp -r /path/to/my/database /var/lib/mysql/new_database

If you do this with a database that uses InnoDB tables, you will get this crazy ‘table does not exist’ error mentioned above.

The issue is that you need the ib* files in the root of the MySQL datadir (e.g. ibdata1, ib_logfile0 and ib_logfile1).

When I copied those it worked for me.

the's user avatar

the

20.8k11 gold badges68 silver badges101 bronze badges

answered Jul 27, 2012 at 21:46

Mike Dacre's user avatar

Mike DacreMike Dacre

2,9051 gold badge12 silver badges2 bronze badges

23

For me on Mac OS (MySQL DMG Installation) a simple restart of the MySQL server solved the problem. I am guessing the hibernation caused it.

the's user avatar

the

20.8k11 gold badges68 silver badges101 bronze badges

answered Feb 12, 2014 at 12:38

Martin's user avatar

MartinMartin

6216 silver badges7 bronze badges

5

I get this issue when the case for the table name I’m using is off. So table is called ‘db’ but I used ‘DB’ in select statement. Make sure the case is the same.

answered Oct 13, 2011 at 19:13

dkinzer's user avatar

dkinzerdkinzer

31.9k12 gold badges66 silver badges85 bronze badges

1

This error can also occur when setting lower_case_table_names to 1, and then trying to access tables that were created with the default value for that variable. In that case you can revert it to the previous value and you will be able to read the table.

answered Jun 17, 2014 at 12:18

golimar's user avatar

golimargolimar

2,3891 gold badge22 silver badges33 bronze badges

2

I don’t know the reason but in my case I solved just disabling and enabling the foreign keys check

SET FOREIGN_KEY_CHECKS=0;
SET FOREIGN_KEY_CHECKS=1;

answered Jun 29, 2016 at 14:34

Bruno Caponi's user avatar

4

  1. stop mysqld
  2. backup mysql folder: cp -a /var/lib/mysql /var/lib/mysql-backup
  3. copy database folder from old machine to /var/lib/mysql
  4. override ib* (ib_logfile* , ibdata ) from old database
  5. start mysqld
  6. dump dabase
  7. mysqldump >dbase.mysql
  8. stop mysql service
  9. remove /var/lib/mysql
  10. rename /var/lib/mysql-backup to /var/lib/mysql
  11. start mysqld
  12. create the database
  13. mysqldump < dbase.mysql

Djizeus's user avatar

Djizeus

4,1611 gold badge23 silver badges42 bronze badges

answered Dec 3, 2012 at 0:51

user1772382's user avatar

user1772382user1772382

5366 silver badges5 bronze badges

4

Please run the query:

SELECT 
    i.TABLE_NAME AS table_name, 
    LENGTH(i.TABLE_NAME) AS table_name_length,
    IF(i.TABLE_NAME RLIKE '^[A-Za-z0-9_]+$','YES','NO') AS table_name_is_ascii
FROM
    information_schema.`TABLES` i
WHERE
    i.TABLE_SCHEMA = 'database'

Unfortunately MySQL allows unicode and non-printable characters to be used in table name.
If you created your tables by copying create code from some document/website, there is a chance that it has zero-width-space somewhere.

answered Oct 13, 2011 at 19:58

dev-null-dweller's user avatar

dev-null-dwellerdev-null-dweller

29.2k3 gold badges65 silver badges85 bronze badges

1

I had the same problem and I searched for 2-3 days, but the solution for me was really stupid.

Restart the mysql

$ sudo service mysql restart

Now tables become accessible.

answered Feb 25, 2017 at 7:55

Siraj Alam's user avatar

Siraj AlamSiraj Alam

9,0389 gold badges52 silver badges64 bronze badges

2

I have just spend three days on this nightmare. Ideally, you should have a backup that you can restore, then simply drop the damaged table. These sorts of errors can cause your ibdata1 to grow huge (100GB+ in size for modest tables)

If you don’t have a recent backup, such as if you relied on mySqlDump, then your backups probably silently broke at some point in the past. You will need to export the databases, which of course you cant do, because you will get lock errors while running mySqlDump.

So, as a workaround, go to /var/log/mysql/database_name/ and remove the table_name.*

Then immediately try to dump the table; doing this should now work. Now restore the database to a new database and rebuild the missing table(s). Then dump the broken database.

In our case we were also constantly getting mysql has gone away messages at random intervals on all databases; once the damaged database were removed everything went back to normal.

Krythic's user avatar

Krythic

4,1345 gold badges26 silver badges67 bronze badges

answered Nov 28, 2012 at 12:50

Andy's user avatar

AndyAndy

3782 silver badges8 bronze badges

3

Try to run sql query to discard tablespace before copying idb-file:

ALTER TABLE mydatabase.mytable DISCARD TABLESPACE;

Copy idb-file

ALTER TABLE mydatabase.mytable IMPORT TABLESPACE;

Restart MySql

reformed's user avatar

reformed

4,45011 gold badges60 silver badges87 bronze badges

answered Apr 13, 2014 at 20:39

l0pan's user avatar

l0panl0pan

4667 silver badges11 bronze badges

2

O.k. this is going to sound pretty absurd, but humor me.
For me the problem got resolved when I changed my statement to this :

SELECT * FROM `table`

I made two changes
1.) Made the table name lower case — I know !!
2.) Used the specific quote symbol = ` : It’s the key above your TAB

The solution does sound absurd, but it worked and it’s Saturday evening and I’ve been working since 9 a.m. — So I’ll take it :)

Good luck.

answered Dec 13, 2014 at 22:55

PlanetUnknown's user avatar

PlanetUnknownPlanetUnknown

3,9564 gold badges49 silver badges66 bronze badges

3

What worked for me, was just dropping the table, even though it didnt exist. Then I re created the table and repopulated from an sql dump done previously.

There must be some metabase of table names, and it was most likely still existing in there till i dropped it.

answered Nov 19, 2013 at 17:39

Zoobra McFly's user avatar

1

Had a similar problem with a ghost table. Thankfully had an SQL dump from before the failure.

In my case, I had to:

  1. Stop mySQL
  2. Move ib* files from /var/mysql off to a backup
  3. Delete /var/mysql/{dbname}
  4. Restart mySQL
  5. Recreate empty database
  6. Restore dump file

NOTE: Requires dump file.

bjb568's user avatar

bjb568

11k11 gold badges50 silver badges71 bronze badges

answered Jan 5, 2013 at 16:45

Oli Stockman's user avatar

2

I had this problem after upgrading WAMP but having no database backup.

This worked for me:

  1. Stop new WAMP

  2. Copy over database directories you need and ibdata1 file from old WAMP installation

  3. Delete ib_logfile0 and ib_logfile1

  4. Start WAMP

You should now be able to make backups of your databases. However after your server restarts again you will still have problems. So now reinstall WAMP and import your databases.

Rohan Khude's user avatar

Rohan Khude

4,3455 gold badges49 silver badges44 bronze badges

answered Jun 8, 2016 at 15:10

ykay says Reinstate Monica's user avatar

3

After having to reinstall MySQL I had this same problem, it seems that during the install, some configuration files that store data about the InnoDB log files, these files ib_logfile* (they are log files right?), are overwriten. To solve this problem I just deleted the ib_logfile* files.

answered Sep 5, 2012 at 22:21

jonathancardoso's user avatar

jonathancardosojonathancardoso

11.6k7 gold badges53 silver badges72 bronze badges

1

  1. Do mysqldump to database:

    mysqldump -u user -ppass dbname > D:Back-upsdbname.sql
    
  2. Restore database

    mysql -u user -ppass dbname < D:Back-upsdbname.sql
    

Now all tables in database were restored completely. Try..

SELECT * FROM dbname.tablename;

Stephen Rauch's user avatar

Stephen Rauch

47.5k31 gold badges106 silver badges135 bronze badges

answered Jan 18, 2018 at 1:42

Zaw Htoon's user avatar

Zaw HtoonZaw Htoon

591 silver badge5 bronze badges

It appears that the issue has to do (at least in mine and a few others) with invalid (corrupt?) innodb log files. Generally speaking, they simply need to be recreated.

Here are solutions, most of which require a restart of mysql.

  • Recreate your log files (Delete and restart mysql)
  • Resize your log files (MySql 5.6+ will regenerate the file for you)
  • If you are doing some type of a data migration, make sure you have correctly migrated the right file and given it permissions as others have already stated
  • Check permissions of your data and log files, that mysql is owner of both
  • If all else fails, you will likely have to recreate the database

Community's user avatar

answered Jul 17, 2014 at 16:22

SeanDowney's user avatar

SeanDowneySeanDowney

17.3k20 gold badges81 silver badges90 bronze badges

1

In my case, i had defined a trigger on the table and then was trying to insert the row in table. seems like, somehow trigger was erroneous, and hence insert was giving error, table doesn’t exist.

answered Dec 31, 2017 at 6:26

Yogesh Kumar Gupta's user avatar

1

Copy only ibdata1 file from your old data directory. Do not copy ib_logfile1 or ib_logfile0 files. That will cause MySQL to not start anymore.

answered Feb 18, 2018 at 7:02

Plabon Dutta's user avatar

Plabon DuttaPlabon Dutta

6,7393 gold badges29 silver badges33 bronze badges

1

Came cross same problem today. This is a mysql «Identifier Case Sensitivity» issue.

Please check corresponding data file. It is very likely that file name is in lower case on file system but table name listed in «show tables» command is in upper case. If system variable «lower_case_table_names» is 0, the query will return «table not exist» because name comparisons are case sensitive when «lower_case_table_names» is 0.

answered Apr 10, 2018 at 10:19

Hudson Liang's user avatar

Its possible you have a hidden character in your table name. Those don’t show up when you do a show tables. Can you do a «SHOW CREATE TABLE TABLE_ONE» and tab complete the «TABLE_ONE» and see if it puts in any hidden characters. Also, have you tried dropping and remaking the tables. Just to make sure nothing is wrong with the privileges and that there are no hidden characters.

answered Oct 13, 2011 at 19:57

Hoopdady's user avatar

HoopdadyHoopdady

2,2763 gold badges25 silver badges40 bronze badges

1

I installed MariaDB on new computer,
stopped Mysql service
renamed data folder to data-
I solved my problem copying just
Mysqldatatable_folders and ibdata1
from crashed HD MySql data Folder to the new installed mysql data folder.

I Skipped ib_logfile0 and ib_logfile1 (otherwise the server did not start service)

Started mysql service.

Then server is running.

answered Mar 10, 2014 at 13:34

Tony's user avatar

TonyTony

16.3k15 gold badges78 silver badges132 bronze badges

1

Same exact problem after TimeMachine backup import. My solution was to stop the MySQL server and fix read-write permissions on the ib* files.

answered Mar 13, 2014 at 13:12

user3415481's user avatar

One other answer I think is worth bringing up here (because I came here with that same problem and this turned out to be the answer for me):

Double check that the table name in your query is spelled exactly the same as it is in the database.

Kind of an obvious, newbie thing, but things like «user» vs «users» can trip people up and I thought it would be a helpful answer to have in the list here. :)

answered Aug 13, 2014 at 18:57

vazor's user avatar

vazorvazor

1233 silver badges12 bronze badges

In my case, when I was importing the exported sql file, I was getting an error like table doesn’t exist for the create table query.

I realized that there was an underscore in my database name and mysql was putting an escape character just before that.

So I removed that underscore in the database name, everything worked out.

Hope it helps someone else too.

answered Jan 28, 2015 at 8:57

Onur Kucukkece's user avatar

Onur KucukkeceOnur Kucukkece

1,6981 gold badge20 silver badges46 bronze badges

Here is another scenario (version upgrade):

I reinstalled my OS (Mac OS El Captain) and installed a new version of mysql (using homebrew). The installed version (5.7) happened to be newer than my previous one. Then I copied over the tables, including the ib* files, and restarted the server. I could see the tables in mysql workbench but when I tried to select anything, I got «Table doesn’t exist».

Solution:

  1. stop the mysql server e.g. mysql.server stop or brew services stop mysql
  2. start the server using mysqld_safe --user=mysql --datadir=/usr/local/var/mysql/ (change path as needed)
  3. run mysql_upgrade -u root -p password (in another terminal window)
  4. shut down the running server mysqladmin -u root -p password shutdown
  5. restart the server in normal mode mysql.server start or brew services start mysql

Relevant docs are here.

answered May 31, 2016 at 23:34

Roman Kutlak's user avatar

Roman KutlakRoman Kutlak

2,6741 gold badge19 silver badges24 bronze badges

1

My table had somehow been renamed to ' Customers' i.e. with a leading space

This meant

a) queries broke

b) the table didn’t appear where expected in the alphabetical order of my tables, which in my panic meant I couldn’t see it!

RENAME TABLE ` Customer` TO `Customer`;

answered Aug 26, 2016 at 12:55

zzapper's user avatar

zzapperzzapper

4,6835 gold badges48 silver badges45 bronze badges

In my case it was SQLCA.DBParm parameter.

I used

SQLCA.DBParm = "Databse = "sle_database.text""

but it must be

SQLCA.DBParm = "Database='" +sle_database.text+ "'"

Explaination :

You are going to combine three strings :

 1. Database='              -  "Database='"

 2. (name of the database)  - +sle_database.text+

 3. '                       - "'" (means " ' "  without space)

Don’t use spaces in quatermarks.
Thank to my colleague Jan.

Rohìt Jíndal's user avatar

Rohìt Jíndal

25.4k12 gold badges70 silver badges123 bronze badges

answered Apr 3, 2013 at 13:13

Marek's user avatar

MarekMarek

111 bronze badge

Go to :xamppmysqldatadbname
inside dbname have tablename.frm and tablename.ibd file.
remove it
and restart mysql and try again.

answered Jun 14, 2017 at 8:40

Abu Sufian's user avatar

Abu SufianAbu Sufian

4395 silver badges8 bronze badges

I had the same issue in windows.
In addition to copying the ib* files and the mysql directory under thd data directory, I also had to match the my.ini file.

The my.ini file from my previous installation did not have the following line:

innodb-page-size=65536

But my new installation did. Possibly because I did not have that option in the older installer.
I removed this and restarted the service and the tables worked as expected.
In short, make sure that the new my.ini file is a replica of the old one, with the only exception being the datadir, the plugin-dir and the port#, depending upon your new installation.

answered Dec 22, 2019 at 21:02

Thennan's user avatar

ThennanThennan

7685 silver badges13 bronze badges

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.

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-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.

  1. SELECT (Query)
  2. This may also apply to the following statements.

    • INSERT
    • UPDATE
    • DELETE
    • CREATE VIEW
    • GRANT SELECT ON
  3. ALTER TABLE
  4. This may also apply to the following statements.

    • DROP TABLE
    • ALTER TABLE ADD COLUMN
    • ALTER TABLE ADD CONSTRAINT
    • ALTER TABLE MOVE

SELECT (Query)

This may also apply to the following statements.

  • INSERT
  • UPDATE
  • DELETE
  • CREATE VIEW

Usually, we see ORA-00942 in SELECT statements. For example, we select a table which belongs to other user in SQL*Plus.

SQL> show user
USER is "SH"
SQL> select count(*) cnt from hr.lottery_list;
select count(*) cnt from hr.lottery_list
                            *
ERROR at line 1:
ORA-00942: table or view does not exist

Or in any database connection tools like Toad for Oracle.

TOAD Error ORA-00942: Table or View Does not Exist

TOAD Error ORA-00942: Table or View Does not Exist

Here we take the following steps to solve ORA-00942 in SELECT statements.

  1. Simple Test
  2. Enter Values
  3. Check Result
  4. Synonym Problem

Simple Test

You can use a simple query to test whether you have used the right way to access the table or not.

select ‘»‘ || owner || ‘».»‘ || object_name || ‘»‘ use_this from all_objects where object_type in (‘TABLE’, ‘VIEW’) and lower(owner) = lower(‘&owner’) and lower(object_name) = lower(‘&table_name’);

Enter Values

After issuing the above SQL statement, the tool you use will ask you two substitution values.

Enter owner of the table.

Enter value for owner: hr

Enter the table name.

Enter value for table_name: lottery_list

Then we’ll see the result.

Check Result

There’re only 2 possible results.

Returns Nothing

If it returns nothing or «no rows selected«, then you need to ask for the owner of the table or DBA to grant SELECT privilege to you.

GRANT SELECT ON <OWNER>.<TABLE_NAME> TO <GRANTEE>;

Returns Something

If it does return something like the following:

USE_THIS
----------------------------------------
"HR"."lottery_list"

Then you can use (copy / paste) the result in your statement.

SQL> select count(*) cnt from "HR"."lottery_list";

       CNT
----------
       107

The points to use the table correctly are:

  • Make sure the table name is correctly spelled.
  • Prefix owner’s name if the table is not yours.
  • Enclose the table name by a pair of double quotes if the identifier is case-sensitive.

Synonym Problem

If your query still failed with ORA-00942, please make sure that the table you thought is really a table or a synonym. Let’s see a case.

SQL> show user
USER is "HR"
SQL> select * from customers;
select * from customers
              *
ERROR at line 1:
ORA-00942: table or view does not exist

What message didn’t tell is the base table of the synonym. Let’s check the base table of the synonym.

SQL> select '"' || table_owner || '"."' || table_name || '"' use_this from all_synonyms where lower(synonym_name) = lower('customers');

USE_THIS
----------------------------------------
"OE"."CUSTOMERS"

The synonym could be public or private, it doesn’t matter. In either situation, you simply need the SELECT object privilege on the base table by the owner or a privileged user.

SQL> show user
USER is "SYSTEM"
SQL> grant select on "OE"."CUSTOMERS" to hr;

Grant succeeded.

We fixed the synonym problem.

ALTER TABLE

This may also apply to the following statements.

  • DROP TABLE
  • ALTER TABLE ADD COLUMN
  • ALTER TABLE ADD CONSTRAINT
  • ALTER TABLE MOVE

Now we turn to some more advanced topics.

There’re only 2 error patterns of ORA-00942 in ALTER TABLE statement.

  1. Not a Table
  2. No REFERENCES Privilege

Not a Table

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 upper(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 upper(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.

No REFERENCES Privilege

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.

Содержание

  • 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, сообщите нам об этом ниже!

Понравилась статья? Поделить с друзьями:
  • Sql ошибка строки не были обновлены
  • Sql server ошибка операционной системы 5 отказано в доступе
  • Sql ошибка синтаксиса create table
  • Sql server ошибка выделения памяти hresult 80004005
  • Sql ошибка при установке 20476