Sql error 42p01 error invalid reference to from clause entry for table

HI All i am trying to do a left join on query but i have an invalid reference to FROM-Clause here are the structure of the code this is the product table CREATE TABLE products ( id BIGINT GENERATED...

HI All

i am trying to do a left join on query but i have an invalid reference to FROM-Clause
here are the structure of the code

this is the product table

CREATE TABLE products
(
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title VARCHAR(255),
    productdesc TEXT,
    costprice DOUBLE PRECISION,
    recommendprice DOUBLE PRECISION,
    views BIGINT DEFAULT 0,
    enabled BOOLEAN DEFAULT FALSE,

    category_id BIGINT REFERENCES categories (id) ON DELETE CASCADE NOT NULL,

    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)

this is the category table

CREATE TABLE categories
(
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    pid BIGINT NOT NULL,
    title VARCHAR(255),
    image VARCHAR(255),

);

this is the type struct

type Product struct {
    TableName struct{} `sql:"products"`
    ID          int64  `json:"id"`
    TITLE string `json:"title"`
    PRODUCTDESC string `json:"product_desc"`
    COSTPRICE float64 `json:"costprice"`
    RECOMMENDPRICE float64 `json:"recommendprice"`
    VIEWS int64 `json:"views"`
    ENABLED bool `json:"enabled"`
    CATEGORYNAME string `json:"categoryname"`
}
type Category struct {
	 tableName struct{} `pg:"categories"`
	ID      int64  `json:"id"`
	Title   string `json:"title"`
	Image   string `json:"image"`
}

this is the actual query to database

func (t *ProductRepo) GetAllProducts() ([]*domain.Product, error) {
    var products []*domain.Product
    query := t.DB.Model(&products).
        ColumnExpr("products.*").
        ColumnExpr("c.id AS category_id, c.title AS categoryname").
        Join("LEFT JOIN categories AS c ON c.id = products.category_id")

    err := query.Select()
    if err != nil {
        return nil, err
    }

    return products, nil
}

this is the actual error from postman

{
    "error": "ERROR #42P01 invalid reference to FROM-clause entry for table "products""
}

any help would be great,

thanks advance

Jason

PostgreSQL error 42P01 actually makes users dumbfounded, especially the newbies.

Usually, this error occurs due to an undefined table in newly created databases.

That’s why at Bobcares, we often get requests to fix PostgreSQL errors, as a part of our Server Management Services.

Today, let’s have a look into the PostgreSQL error 42P01 and see how our Support Engineers fix it.

What is PostgreSQL error 42P01?

PostgreSQL has a well-defined error code description. This helps in identifying the reason for the error.

Today, let’s discuss in detail about PostgreSQL error 42P01. The typical error code in PostgreSQL appears as:

ERROR: relation "[Table name]" does not exist

SQL state:42P01

Here the 42P01 denotes an undefined table.

So, the code description clearly specifies the basic reason for the error.

But what does an undefined table means?

Let’s discuss it in detail.

Causes and fixes for the PostgreSQL error 42P01

Customer query on undefined tables of a database often shows up the 42P01 error.

Now let’s see a few situations when our customers get the 42P01 error. We will also see how our Support Engineers fix this error.

1. Improper database setup

Newbies to Postgres often make mistakes while creating a new database. Mostly, this improper setup ends up in a 42P01 error.

In such situations, our Support Team guides them for easy database setup.

Firstly, we create a new database. Next, we create a new schema and role. We give proper privileges to tables.

Postgres also allows users to ALTER DEFAULT PRIVILEGES.

2. Unquoted identifiers

Some customers create tables with mixed-case letters.

Usually, the unquoted identifiers are folded into lowercase. So, when the customer queries the table name with the mixed case it shows 42P01 error.

The happens as the PostgreSQL has saved the table name in lower case.

To resolve this error, our Support Engineers give mixed case table name in quotes. Also, we highly recommend to NOT use quotes in database names. Thus it would make PostgreSQL behave non-case sensitive.

3. Database query on a non-public schema

Similarly, the PostgreSQL 42P01 error occurs when a user queries a non-public schema.

Usually, this error occurs if the user is unaware of the proper Postgres database query.

For instance, the customer query on table name ‘pgtable‘ was:

SELECT * FROM  pgtable

This query is totally correct in case of a public schema. But, for a non-public schema ‘xx’ the query must be:

SELECT * FROM  "xx"."pgtable"

Hence, our Support Engineers ensure that the query uses the correct schema name.

[Still having trouble in fixing PostgreSQL errors? – We’ll fix it for you.]

Conclusion

In short, PostgreSQL error 42P01 denotes the database query is on an undefined table. This error occurs due to improper database setup, unidentified table name, and so on. Today, we saw how our Support Engineers fix the undefined table error in Postgres.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Your Answer

StackExchange.ifUsing(«editor», function () {
StackExchange.using(«externalEditor», function () {
StackExchange.using(«snippets», function () {
StackExchange.snippets.init();
});
});
}, «code-snippets»);

StackExchange.ready(function() {
var channelOptions = {
tags: «».split(» «),
id: «1»
};
initTagRenderer(«».split(» «), «».split(» «), channelOptions);

StackExchange.using(«externalEditor», function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using(«snippets», function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: ‘answer’,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: «»,
imageUploader: {
brandingHtml: «Powered by u003ca class=»icon-imgur-white» href=»https://imgur.com/»u003eu003c/au003e»,
contentPolicyHtml: «User contributions licensed under u003ca href=»https://creativecommons.org/licenses/by-sa/3.0/»u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href=»https://stackoverflow.com/legal/content-policy»u003e(content policy)u003c/au003e»,
allowUrls: true
},
onDemand: true,
discardSelector: «.discard-answer»
,immediatelyShowMarkdownHelp:true
});

}
});

Sign up or log in

StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave(‘#login-link’);
});

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function () {
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f53274265%2fpostgresql-there-is-an-entry-for-table-but-it-cannot-be-referenced-from-this-par%23new-answer’, ‘question_page’);
}
);

Post as a guest

Email

Required, but never shown

Понравилась статья? Поделить с друзьями:
  • Sql 2003 error
  • Sql error 42883 error could not identify an equality operator for type json
  • Sql 1396 error
  • Sql error 42803 error aggregate functions are not allowed in group by
  • Sql 104 ошибка