I have a postgresql db with a number of tables. If I query:
SELECT column_name
FROM information_schema.columns
WHERE table_name="my_table";
I will get a list of the columns returned properly.
However, when I query:
SELECT *
FROM "my_table";
I get the error:
(ProgrammingError) relation "my_table" does not exist
'SELECT *n FROM "my_table"n' {}
Any thoughts on why I can get the columns, but can’t query the table? Goal is to be able to query the table.
asked Apr 20, 2016 at 19:38
patkilpatkil
1,8993 gold badges15 silver badges17 bronze badges
3
You have to include the schema if isnt a public one
SELECT *
FROM <schema>."my_table"
Or you can change your default schema
SHOW search_path;
SET search_path TO my_schema;
Check your table schema here
SELECT *
FROM information_schema.columns
For example if a table is on the default schema public
both this will works ok
SELECT * FROM parroquias_region
SELECT * FROM public.parroquias_region
But sectors need specify the schema
SELECT * FROM map_update.sectores_point
answered Apr 20, 2016 at 19:44
6
You can try:
SELECT *
FROM public."my_table"
Don’t forget double quotes near my_table.
4b0
21.8k30 gold badges95 silver badges142 bronze badges
answered Sep 3, 2019 at 2:13
2
I had to include double quotes with the table name.
db=> d
List of relations
Schema | Name | Type | Owner
--------+-----------------------------------------------+-------+-------
public | COMMONDATA_NWCG_AGENCIES | table | dan
...
db=> d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".
???
Double quotes:
db=> d "COMMONDATA_NWCG_AGENCIES"
Table "public.COMMONDATA_NWCG_AGENCIES"
Column | Type | Collation | Nullable | Default
--------------------------+-----------------------------+-----------+----------+---------
ID | integer | | not null |
...
Lots and lots of double quotes:
db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR: relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR: column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
ID
----
1
(1 row)
This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:
DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";
CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...
answered Sep 26, 2019 at 21:57
dfrankowdfrankow
19.9k40 gold badges149 silver badges210 bronze badges
1
I hit this error and it turned out my connection string was pointing to another database, obviously the table didn’t exist there.
I spent a few hours on this and no one else has mentioned to double check your connection string.
answered Nov 13, 2020 at 2:29
Jeremy ThompsonJeremy Thompson
61.4k33 gold badges188 silver badges318 bronze badges
2
I had the same problem that occurred after I restored data from a postgres dumped db.
My dump file had the command below from where things started going south.
SELECT pg_catalog.set_config('search_path', '', false);
Solutions:
- Probably remove it or change that
false
to betrue
. - Create a private schema that will be used to access all the tables.
The command above simply deactivates all the publicly accessible schemas.
Check more on the documentation here: https://www.postgresql.org/docs/9.3/ecpg-connect.html
answered Sep 17, 2019 at 16:51
dmigwidmigwi
611 silver badge5 bronze badges
0
The error can be caused by access restrictions. Solution:
GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;
answered Oct 1, 2020 at 0:47
MarcelMarcel
2,7982 gold badges26 silver badges43 bronze badges
I was using pgAdmin to create my tables and while I was not using reserved words, the generated table had a quote in the name and a couple of columns had quotes in them. Here is an example of the generated SQL.
CREATE TABLE public."Test"
(
id serial NOT NULL,
data text NOT NULL,
updater character varying(50) NOT NULL,
"updateDt" time with time zone NOT NULL,
CONSTRAINT test_pk PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE public."Test"
OWNER to svc_newnews_app;
All of these quotes were inserted at «random». I just needed to drop and re-create the table again without the quotes.
Tested on pgAdmin 4.26
answered Oct 9, 2020 at 14:05
ChewyChewy
6416 silver badges21 bronze badges
Please ensure that:
- Your password is non-empty
- In case it is empty, do not pass the
password
param in the connection string
This is one of the most common errors when starting out with the tutorial.
answered Mar 6, 2022 at 8:21
In my case, the dump file I restored had these commands.
CREATE SCHEMA employees;
SET search_path = employees, pg_catalog;
I’ve commented those and restored again. The issue got resolved
answered Oct 30, 2020 at 12:03
samsrisamsri
1,10414 silver badges25 bronze badges
Keep all your table names in lower case because when you rollback and then go to latest, it’s looking for lowercase apparently.
answered Oct 25, 2021 at 8:00
ErickErick
211 silver badge4 bronze badges
Lets say we have database name as students
and schema name as studentinformation
then to use all the table of this schema we need to set the path first which we can do in postgresql
like:
client.connect()
.then(()=>console.log("connected succesfully"))
.then(()=>client.query("set search_path to students"))
.then(()=>client.query("show search_path"))
.then(()=>client.query("set search_path to studentinformation"))
.then(()=>client.query("show search_path"))
.then(results => console.table(results.rows)) //setting the search path
Toni
1,5454 gold badges15 silver badges23 bronze badges
answered Jul 1, 2021 at 17:36
I was using psql from PostgreSQL, and somehow I created the table in the «postgres=#» directory instead of first connecting to the database and creating it there.
So make sure that you connected to the database you want before creating tables
answered Feb 5 at 18:11
What you had originally was a correct syntax — for tables, not for schemas. As you did not have a table (dubbed ‘relation’ in the error message), it threw the not-found error.
I see you’ve already noticed this — I believe there is no better way of learning than to fix our own mistakes
But there is something more. What you are doing above is too much on one hand, and not enough on the other.
Running the script, you
- create a schema
- create a role
- grant
SELECT
on all tables in the schema created in (1.) to this new role_ - and, finally, grant all privileges (
CREATE
andUSAGE
) on the new schema to the new role
The problem lies within point (3.) You granted privileges on tables in replays
— but there are no tables in there! There might be some in the future, but at this point the schema is completely empty. This way, the GRANT
in (3.) does nothing — this way you are doing too much.
But what about the future tables?
There is a command for covering them: ALTER DEFAULT PRIVILEGES
. It applies not only to tables, but:
Currently [as of 9.4], only the privileges for tables (including views and foreign tables), sequences, functions, and types (including domains) can be altered.
There is one important limitation, too:
You can change default privileges only for objects that will be created by yourself or by roles that you are a member of.
This means that a table created by alice
, who is neither you nor a role than you are a member of (can be checked, for example, by using du
in psql
), will not take the prescribed access rights. The optional FOR ROLE
clause is used for specifying the ‘table creator’ role you are a member of. In many cases, this implies it is a good idea to create all database objects using the same role — like mydatabase_owner
.
A small example to show this at work:
CREATE ROLE test_owner; -- cannot log in
CREATE SCHEMA replays AUTHORIZATION test_owner;
GRANT ALL ON SCHEMA replays TO test_owner;
SET ROLE TO test_owner; -- here we change the context,
-- so that the next statement is issued as the owner role
ALTER DEFAULT PRIVILEGES IN SCHEMA replays GRANT SELECT ON TABLES TO alice;
CREATE TABLE replays.replayer (r_id serial PRIMARY KEY);
RESET ROLE; -- changing the context back to the original role
CREATE TABLE replays.replay_event (re_id serial PRIMARY KEY);
-- and now compare the two
dp replays.replayer
Access privileges
Schema │ Name │ Type │ Access privileges │ Column access privileges
─────────┼──────────┼───────┼───────────────────────────────┼──────────────────────────
replays │ replayer │ table │ alice=r/test_owner ↵│
│ │ │ test_owner=arwdDxt/test_owner │
dp replays.replay_event
Access privileges
Schema │ Name │ Type │ Access privileges │ Column access privileges
─────────┼──────────────┼───────┼───────────────────┼──────────────────────────
replays │ replay_event │ table │ │
As you can see, alice
has no explicit rights on the latter table. (In this case, she can still SELECT
from the table, being a member of the public
pseudorole, but I didn’t want to clutter the example by revoking the rights from public
.)
scooter_rent=# dt
List of relations
Schema | Name | Type | Owner
———+—————+——-+——-
public | Couriers | table | root
public | Orders | table | root
public | SequelizeMeta | table | root
(3 rows)
scooter_rent=# SELECT * FROM Couriers;
ERROR: relation «couriers» does not exist
LINE 1: SELECT * FROM Couriers;
Пробовал с разными регистрами
-
Вопрос заданболее года назад
-
1199 просмотров
Пригласить эксперта
SELECT * FROM "Couriers";
Если название таблицы/поля и пр. объектов в постгресе содержит заглавные буквы — его надлежит брать в кавычки. Поэтому, во избежание лишних проблем, заглавные обычно избегают.
-
Показать ещё
Загружается…
22 июн. 2023, в 00:59
8000 руб./за проект
22 июн. 2023, в 00:56
8000 руб./за проект
22 июн. 2023, в 00:39
12000 руб./за проект
Минуточку внимания
What are you doing?
edit2: Remember folks, when you change your env variables, you have to restart your server/pm2 instance =) This fixed it, although I would expect a more helpful error message when host, port etc. are undefined.
Hey guys,
I am switching my node/express app from mysql
to postgresql
. Everything was pretty seamless except I had to swap some data types. When I try to run the following command I get an error.
edit: Looks like something else is up. Sequelize throws the same error for all other queries, including relation "users" does not exist
. I know this was marked as support, but mysql was working perfectly before changing to postgres, so I imagine it should also work now.
const [ serviceUser, created ] = await ServiceUserAccountModel.findOrCreate({ where: { service_user_id: '123456' }, });
relation "serviceUserAccounts" does not exist
. or with users relation "users" does not exist
const userModel = Sequelize.define('user', { // has many ServiceUserAccounts id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, email: { type: DataTypes.STRING, allowNull: false }, age: { type: DataTypes.SMALLINT, allowNull: false }, gender: { type: DataTypes.STRING, allowNull: false }, first_name: { type: DataTypes.STRING, allowNull: true }, last_name: { type: DataTypes.STRING, allowNull: true } }); const serviceUserAccountsModel = Sequelize.define('serviceUserAccount', { // belongs to User id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, display_name: { type: DataTypes.STRING, allowNull: true }, email_address: { type: DataTypes.STRING, allowNull: true }, service_id: { type: DataTypes.SMALLINT, allowNull: true, }, service_user_id: { type: DataTypes.STRING, allowNull: true, }, refresh_token: { type: DataTypes.STRING, allowNull: true }, access_token: { type: DataTypes.STRING, allowNull: true }, token_type: { type: DataTypes.STRING, allowNull: true }, expiration_date: { type: DataTypes.INTEGER, allowNull: true }, storage_limit: { type: DataTypes.INTEGER, allowNull: true }, storage_usage: { type: DataTypes.INTEGER, allowNull: true }, trashed_storage_usage: { type: DataTypes.INTEGER, allowNull: true }, }); // Relations module.exports = function( database ){ const User = database.models.user.user; const ServiceUserAccounts = database.models.user.serviceUserAccounts; User.hasMany(ServiceUserAccounts); ServiceUserAccounts.belongsTo(User); };
What do you expect to happen?
As it was working perfectly before with mysql dialect, I expect it to also work with Postgresql.
What is actually happening?
relation "serviceUserAccounts" does not exist
. I’m able to run the query just fine in pgAdmin, so it must be something with sequelize. What am I missing?
Here’s the gist with the stacktrace
https://gist.github.com/Mk-Etlinger/569093387a0cb97699acfcba3994f59d
Any ideas? I checked my permissions and it came back public, $user
.
also looked here but no luck:
https://stackoverflow.com/questions/28844617/sequelize-with-postgres-database-not-working-after-migration-from-mysql
https://stackoverflow.com/questions/946804/find-out-if-user-got-permission-to-select-update-a-table-function-in-pos
Dialect: postgres
Dialect version: XXX
Database version: 9.6.2
Sequelize version: ^4.38.1
Tested with latest release: Yes, 4.39.0
Note : Your issue may be ignored OR closed by maintainers if it’s not tested against latest version OR does not follow issue template.
The error «relation does not exist» in Hibernate + PostgreSQL can occur when trying to access a table in the database that doesn’t exist. This error can be caused by various issues such as incorrect table name, incorrect schema, incorrect database connection, and others. In order to resolve this error, there are several methods that can be followed.
Method 1: Verify the table name
To fix the «relation does not exist» error in Hibernate and PostgreSQL, you can verify the table name in your code. Here are the steps:
- Check the entity class that you are using in your Hibernate configuration. Make sure that the table name specified in the @Table annotation matches the actual table name in your PostgreSQL database.
@Entity
@Table(name = "my_table")
public class MyEntity {
// ...
}
- If the table name is correct, check the SQL query generated by Hibernate. You can enable the show_sql property in your Hibernate configuration to see the SQL queries in the console.
<property name="hibernate.show_sql" value="true"/>
- Look for the SQL query that is causing the error. Make sure that the table name in the query matches the actual table name in your PostgreSQL database.
SELECT * FROM my_table WHERE id = 1
- If the table name in the query is correct, check the schema of your PostgreSQL database. Make sure that the table is in the correct schema.
SELECT * FROM my_schema.my_table WHERE id = 1
- If the schema is correct, check the permissions of the PostgreSQL user that you are using in your Hibernate configuration. Make sure that the user has permission to access the table.
GRANT ALL PRIVILEGES ON my_table TO my_user;
By following these steps, you should be able to fix the «relation does not exist» error in Hibernate and PostgreSQL.
Method 2: Verify the schema
To fix the «relation does not exist» error when using Hibernate with PostgreSQL in Eclipse, you can verify the schema by following these steps:
-
Open the PostgreSQL command prompt and connect to your database.
-
Run the following command to list all the tables in your schema:
-
Make sure that the table you are trying to access exists in the list.
-
If the table does not exist, create it using the following command:
CREATE TABLE <table_name> ( <column_name> <data_type>, ... );
-
If the table exists but the schema is different, you can update it using the following command:
ALTER TABLE <table_name> ADD COLUMN <column_name> <data_type>;
-
Make sure that the schema name is correct in your Hibernate configuration file. It should match the schema name in your PostgreSQL database.
<hibernate-configuration> <session-factory> ... <property name="hibernate.default_schema">public</property> ... </session-factory> </hibernate-configuration>
-
If you are using annotations to map your entities, make sure that the schema name is specified in the
@Table
annotation.@Entity @Table(name = "table_name", schema = "public") public class MyEntity { ... }
By verifying the schema, you can ensure that the table you are trying to access exists in the correct schema and has the correct columns. This should fix the «relation does not exist» error when using Hibernate with PostgreSQL in Eclipse.
Method 3: Verify the database connection
To fix the error «relation does not exist — SQL Error: 0, SQLState: 42P01» in Eclipse with Hibernate and PostgreSQL, you can verify the database connection. Here are the steps:
- Open the Hibernate configuration file «hibernate.cfg.xml» and check the database connection settings. Make sure the URL, username, and password are correct.
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/mydatabase</property>
<property name="hibernate.connection.username">myusername</property>
<property name="hibernate.connection.password">mypassword</property>
- Create a simple Java class to test the database connection. Use the Hibernate SessionFactory to get a Session object, and then execute a simple query to check if the table exists.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestDatabaseConnection {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
String tableName = "mytable";
String query = "SELECT 1 FROM " + tableName + " LIMIT 1";
try {
session.createSQLQuery(query).uniqueResult();
System.out.println("Table " + tableName + " exists");
} catch (Exception e) {
System.err.println("Table " + tableName + " does not exist");
e.printStackTrace();
}
session.close();
sessionFactory.close();
}
}
- Run the Java class and check the output. If the table exists, you should see the message «Table mytable exists». Otherwise, you should see the message «Table mytable does not exist» and the stack trace of the exception.
That’s it! By verifying the database connection, you can confirm if the table exists or not, and then fix the error accordingly.
Method 4: Check if the table exists in the database
To fix the error «relation does not exist» in Hibernate and PostgreSQL, you can check if the table exists in the database before executing the query. Here are the steps to do it:
- Get the database metadata:
Session session = sessionFactory.getCurrentSession();
Connection connection = session.doReturningWork(
connection -> connection
);
DatabaseMetaData metadata = connection.getMetaData();
- Check if the table exists:
ResultSet resultSet = metadata.getTables(
null, null, "table_name", null
);
boolean tableExists = resultSet.next();
- If the table exists, execute the query:
if (tableExists) {
Query query = session.createQuery("from Entity where ...");
List<Entity> entities = query.getResultList();
}
Here is the complete code:
Session session = sessionFactory.getCurrentSession();
Connection connection = session.doReturningWork(
connection -> connection
);
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet = metadata.getTables(
null, null, "table_name", null
);
boolean tableExists = resultSet.next();
if (tableExists) {
Query query = session.createQuery("from Entity where ...");
List<Entity> entities = query.getResultList();
}
Note that you need to replace «table_name» with the actual name of the table you want to check. Also, you need to replace «Entity» with the name of your Hibernate entity class.
Method 5: Ensure that Hibernate is using the correct dialect
To ensure that Hibernate is using the correct dialect, you need to add the following line to your Hibernate configuration file:
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
This will tell Hibernate to use the PostgreSQL dialect, which is necessary for proper interaction with the database.
In addition, make sure that you have the correct PostgreSQL JDBC driver in your project’s classpath. You can download the latest version from the PostgreSQL website.
Here is an example Hibernate configuration file with the PostgreSQL dialect:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/mydatabase</property>
<property name="hibernate.connection.username">myuser</property>
<property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
</session-factory>
</hibernate-configuration>
Make sure to replace the values for hibernate.connection.url
, hibernate.connection.username
, and hibernate.connection.password
with your own database connection details.
With these changes, Hibernate should be able to interact with your PostgreSQL database without any issues.