Меню

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

Wondering how to fix PostgreSQL Error code 42703? We can help you.

One of the most common error codes with the PostgreSQL database is 42703. It will be seen along with the error message “column does not exist”. This error indicates either that the requested column does not exist, or that the query is not correct.

Here at Bobcares, we often handle requests from our customers to fix similar PostgreSQL errors as a part of our Server Management Services. Today we will see how our support engineers fix this for our customers.

How to fix PostgreSQL Error code 42703

Often, the error is caused by a lack of quotes. We can add double quotes to the column name to fix this error.

For example:

We will try to run a simple select query:

SELECT return_part_i.CntrctTrmntnInd FROM return_part_i LIMIT 10;

And get the following error:

ERROR: column return_part_i.cntrcttrmntnind does not exist LINE 1: SELECT return_part_i.CntrctTrmntnInd FROM return_part_i LIMI... ^ HINT: Perhaps you meant to reference the column "return_part_i.CntrctTrmntnInd". SQL state: 42703 Character: 8

if we have a camel case in our column name we must ensure to wrap the column name with a double quote.

This can be done in the following way:

SELECT "CntrctTrmntnInd"  FROM return_part_i LIMIT 10;

PostgreSQL columns (object) names are case sensitive when specified with double quotes. Unquoted identifiers are automatically used as lowercase so the correct case sequence must be written with double quotes.

If we want a LIMIT in result we must use an order by

SELECT "CntrctTrmntnInd" FROM return_part_i ORDER BY "CntrctTrmntnInd" LIMIT 10;

When used with quotes, Postgresql is case sensitive regarding identifier names like table names and column names.
So a common issue that triggers this error is when we use the column name in our commands in any other cases other than that of the original one.

For instance, if the column name is “Price”, using “price” in the command can trigger the error.

Thus we need to make sure that the cases are correct.

[Need assistance? We can help you]

Conclusion

In short, we saw how our Support Techs fix PostgreSQL Error code 42703 for our customers.

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»;

I am trying to do a cohort analysis and compare average number of rentals based on the renter’s first rental year(= the year where a renter rented first time). Basically, I am asking the question: are we retaining renters whose first year renting was 2013 than renters whose first year was 2015?

Here is my code:

SELECT renter_id, 
       Min(Date_part('year', created_at)) AS first_rental_year, 
       ( Count(trip_finish) )             AS number_of_trips 
FROM   bookings 
WHERE  state IN ( 'approved', 'aboard', 'ashore', 'concluded', 'disputed' ) 
  AND  first_rental_year = 2013 
GROUP  BY 1 
ORDER  BY 1; 

The error message I get is:

ERROR:  column "first_rental_year" does not exist
LINE 6: ... 'aboard', 'ashore', 'concluded', 'disputed') AND first_rent...
                                                             ^

********** Error **********

ERROR: column "first_rental_year" does not exist
SQL state: 42703
Character: 208

Any help is much appreciated.

PostgreSQL database code 42703 is a common error encountered and triggers an error message «column does not exist«. Basically, this error indicates either that the requested column does not exist, or that the query is not correct.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related  PostgreSQL queries.

In this context, we shall look into how to fix this PostgreSQL error.

How to resolve PostgreSQL Error code 42703 ?

Sometimes this error is a result of lack of quotes. We can add double quotes to the column name to fix this error.

For example:

We will try to run a simple select query:

SELECT return_part_i.CntrctTrmntnInd FROM return_part_i LIMIT 10;

And get the following error:

ERROR: column return_part_i.cntrcttrmntnind does not exist LINE 1: SELECT return_part_i.CntrctTrmntnInd FROM return_part_i LIMI... ^ HINT: Perhaps you meant to reference the column "return_part_i.CntrctTrmntnInd". SQL state: 42703 Character: 8

if we have a camel case in our column name we must ensure to wrap the column name with a double quote.

This can be done in the following way:

SELECT "CntrctTrmntnInd"  FROM return_part_i LIMIT 10;

PostgreSQL columns (object) names are case sensitive when specified with double quotes. Unquoted identifiers are automatically used as lowercase so the correct case sequence must be written with double quotes.

If we want a LIMIT in result we must use an order by:

SELECT "CntrctTrmntnInd" FROM return_part_i ORDER BY "CntrctTrmntnInd" LIMIT 10;

When used with quotes, Postgresql is case sensitive regarding identifier names like table names and column names.

So a common issue that triggers this error is when we use the column name in our commands in any other cases other than that of the original one.

For instance, if the column name is «Price», using «price» in the command can trigger the error.

Thus we need to make sure that the cases are correct.

[Need assistance in fixing PostgreSQL Errors? We can help you. ]

Asked
6 years, 5 months ago

Viewed
31k times

I am getting an error while running an update query with table name specified along with column name:

UPDATE Temp SET Temp.Id='234',Temp.Name='Test'WHERE Id='245'

This is the error:

ERROR:  column "temp" of relation "temp" does not exist
LINE 1:      UPDATE Temp SET Temp.Id='23...
                               ^
********** Error **********

ERROR: column "temp" of relation "temp" does not exist
SQL state: 42703
Character: 24

dezso's user avatar

dezso

29.9k13 gold badges95 silver badges140 bronze badges

asked Aug 3, 2016 at 9:02

You cannot (and need not) use table aliases (or tablename qualified column names) in the SET clause of an UPDATE. This even makes sense, as you can only update a single table in a single UPDATE, so there is no ambiguity in column names there.

Fortunately, the ever helpful documentation explicitly mentions your case:

column_name

The name of a column in the table named by table_name. The column name can be qualified with a subfield name or array subscript,
if needed. Do not include the table’s name in the specification of a
target column — for example, UPDATE tab SET tab.col = 1 is invalid.

So, the solution is to simply remove temp. from the SET clause:

UPDATE temp SET id = '234', name = 'Test' WHERE id = '245'

Notes:

  • Are you really storing numbers as text? If yes, why? It is usually a recipe for disaster. For example, how do you prevent something like 'mkjcvnd7y78r3tgbhvcjh' entering your id column?
  • The way you are using object names starting with capital letters is confusing. Without double-quoting its name, your table in reality is called temp as opposed to Temp. Using it the latter way may decrease readability (depending on your preferences and habits, of course).

answered Aug 3, 2016 at 9:13

dezso's user avatar

dezsodezso

29.9k13 gold badges95 silver badges140 bronze badges

What would happen in the case of doing an update for 2 tables that have the same field name?

update car c, airplane a
set c.nr_rute = 1
set a.nr_rute = 1

answered Dec 8, 2021 at 17:52

LUIS FERNANDO GUERRERO ORTEGA's user avatar

2

@fatim

Simple LINQ query produces the following sql:
SELECT «Extent1″.»price» FROM «schema1».»table1″ AS «Extent1»
which fails with «ERROR: 42703: column Extent1.price does not exist»

Another example from modified LINQ query
SELECT «Alias1″.»Id», «Alias1″.»price» FROM «schema1».»table1″ AS «Alias1» LIMIT 1
ERROR: 42703: column Alias1.Id does not exist

Manually running those statements without the quotes works fine.
My setup is Npgsql.EntityFramework 2.2.5.0 / EF 6.1.3.0 / Postgres 9.4.1

@franciscojunior

When used with quotes, Postgresql is case sensitive regarding identifier names like table names and columns names.
In your case, your column name may have been created with double quotes using a different case of price. Maybe it was created as "Price"? If so, just recreate it without quotes, or using the same case sensitivity of your queries.

I need to check it, but I think those quotes are added by EF when generating the queries.

I hope it helps.

@fatim

Thanks Francisco, you are right, this issue is caused by case mismatch.
Is there way to switch Npgsql to case-insensitive mode apart from applying data annotations to the model columns ?

@franciscojunior

Hi, @fatim !
I’m glad you got it working.

Is there way to switch Npgsql to case-insensitive mode apart from applying data annotations to the model columns ?

I don’t know it yet. I need to check if we can make something about those quotes.
@Emill , do you have any idea if it is possible to remove those quotes from EF queries?
Thanks in advance.

@Emill

Postgresql’s names are case-sensitive but for some strange reason the identifiers put in an sql query are automatically converted to lower case by the lexer unless they are surrounded by quotes.

If the properties of the models don’t match the column names, it is possible by using attributes to use other column names.

If requested, we could have some option to automatically convert CamelCase identifiers to lower_case_with_underlines to better fit the naming conventions used by .net and Postgresql.

@roji

You can use EF6’s own API to specify the database names on all classes and properties (some Linq on the model + EF6’s fluent API should do the trick).

The problem persisting occasionaly. Occurs when I try a insert.
Do anyone have any idea?

«An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.»

InnerException = ERRO: 42703: coluna»Convenios_Id» da relação «plano» não existe

My properties for relationship:

//Convenio Model

[Table(name: "convenio", Schema = "public")]
[Serializable]
public class Convenios
{       
    [Key, Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<Planos> ListaPlanos { get; set; }

    /* ... */
}

/* Model Planos */

[Table(name: "plano", Schema = "public")]
[Serializable]
public class Planos
{

    [Key, Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("convenio_id")]
    [Required]
    public int ConvenioId { get; set; }

    [ForeignKey("ConvenioId")]
    public virtual Convenios ConvenioVinculado { get; set; }

    /* ... */

}

This is a query generated by Npgsql/Entity Framework:

ERROR: coluna «Convenios_Id» da relação «plano» não existe no
caracter 421 COMMAND: INSERT INTO
«public».»plano»(«convenio_id»,»descricao»,»codigo»,»tabela_id»,»padrao»,»percpac»,»percconv»,»banda_porte»,»banda_uco»,»valch»,»usuario»,»status»,»valfilme»,»codfilme»,»codigofilm»,»motivo»,»limite»,»mpercconv»,»mpercpac»,»fpercpac»,»fpercconv»,»autoriza»,»deparapla»,»valorauto»,»autori»,»ambobriga»,»descmat»,»obs»,»tipotab»,»valcopart»,»dtultger»,»operador_id_ultger»,»marca»,»dtultgerini»,»dtultgerfin»,»Convenios_Id»)
VALUES (0,E’Qui et eum soluta sed et expedita’,NULL,cast(177 as
int8),1,25,75,35,65,cast(30 as
numeric),NULL,0,NULL,NULL,NULL,NULL,8,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,E’Eos,
modi deserunt beatae et eveniet, mollitia omnis voluptate nulla
eiusmod labore.’,2,61,NULL,NULL,NULL,NULL,NULL,cast(5143 as int8));

I don’t have idea about this problem…

The problem persisting occasionaly. Occurs when I try a insert.
Do anyone have any idea?

«An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.»

InnerException = ERRO: 42703: coluna»Convenios_Id» da relação «plano» não existe

My properties for relationship:

//Convenio Model

[Table(name: "convenio", Schema = "public")]
[Serializable]
public class Convenios
{       
    [Key, Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<Planos> ListaPlanos { get; set; }

    /* ... */
}

/* Model Planos */

[Table(name: "plano", Schema = "public")]
[Serializable]
public class Planos
{

    [Key, Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("convenio_id")]
    [Required]
    public int ConvenioId { get; set; }

    [ForeignKey("ConvenioId")]
    public virtual Convenios ConvenioVinculado { get; set; }

    /* ... */

}

This is a query generated by Npgsql/Entity Framework:

ERROR: coluna «Convenios_Id» da relação «plano» não existe no
caracter 421 COMMAND: INSERT INTO
«public».»plano»(«convenio_id»,»descricao»,»codigo»,»tabela_id»,»padrao»,»percpac»,»percconv»,»banda_porte»,»banda_uco»,»valch»,»usuario»,»status»,»valfilme»,»codfilme»,»codigofilm»,»motivo»,»limite»,»mpercconv»,»mpercpac»,»fpercpac»,»fpercconv»,»autoriza»,»deparapla»,»valorauto»,»autori»,»ambobriga»,»descmat»,»obs»,»tipotab»,»valcopart»,»dtultger»,»operador_id_ultger»,»marca»,»dtultgerini»,»dtultgerfin»,»Convenios_Id»)
VALUES (0,E’Qui et eum soluta sed et expedita’,NULL,cast(177 as
int8),1,25,75,35,65,cast(30 as
numeric),NULL,0,NULL,NULL,NULL,NULL,8,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,E’Eos,
modi deserunt beatae et eveniet, mollitia omnis voluptate nulla
eiusmod labore.’,2,61,NULL,NULL,NULL,NULL,NULL,cast(5143 as int8));

I don’t have idea about this problem…

yoimelv

0 / 0 / 0

Регистрация: 16.01.2019

Сообщений: 12

1

08.10.2022, 21:58. Показов 971. Ответов 4

Метки postgres sql, sql posrgre (Все метки)


Здравствуйте! Не получается объединить таблицы по внешнему ключу. PGadmin пишет:
«ERROR: ОШИБКА: столбец users.fk не существует
LINE 1: SELECT * FROM users INNER JOIN hobby ON users.fk = hobby.pk
^

SQL state: 42703
Character: 41″
Не понимаю в чём проблема. Внешний ключ существует и с ним всё в порядке.

Таблица hobby:

SQL
1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE IF NOT EXISTS public.hobby
(
    id INTEGER NOT NULL DEFAULT NEXTVAL('hobby_id_seq'::regclass),
    hobby_name CHARACTER VARYING COLLATE pg_catalog."default" NOT NULL,
    CONSTRAINT hobby_pkey PRIMARY KEY (hobby_name)
        INCLUDE(id)
)
 
TABLESPACE pg_default;
 
ALTER TABLE IF EXISTS public.hobby
    OWNER TO postgres;

Таблица users:

SQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
CREATE TABLE IF NOT EXISTS public.users
(
    id INTEGER NOT NULL DEFAULT NEXTVAL('users_id_seq'::regclass),
    first_name CHARACTER VARYING COLLATE pg_catalog."default" NOT NULL,
    second_name CHARACTER VARYING COLLATE pg_catalog."default" NOT NULL,
    date_of_birth DATE NOT NULL,
    email CHARACTER VARYING COLLATE pg_catalog."default" NOT NULL,
    hobby CHARACTER VARYING COLLATE pg_catalog."default",
    CONSTRAINT users_pkey PRIMARY KEY (id),
    CONSTRAINT hobby_fkey FOREIGN KEY (hobby)
        REFERENCES public.hobby (hobby_name) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
)
 
TABLESPACE pg_default;
 
ALTER TABLE IF EXISTS public.users
    OWNER TO postgres;

Запрос, который не получается произвести:

SQL
1
SELECT * FROM users INNER JOIN hobby ON users.fk = hobby.pk

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



4716 / 3924 / 994

Регистрация: 29.08.2013

Сообщений: 25,176

Записей в блоге: 3

08.10.2022, 22:57

2

а ткните пальцем где именно в таблице users колонка fk

да и pk я не вижу



0



yoimelv

0 / 0 / 0

Регистрация: 16.01.2019

Сообщений: 12

08.10.2022, 23:22

 [ТС]

3

Честно говоря, не знаю. Делали задание в классе, там всё получилось, а вот дома — нет, ошибка где-то. Нужно было выполнить запрос:

SQL
1
SELECT * FROM table1 INNER JOIN table2 ON table1.fk = table2.pk

В классе программа сама предложила дописать запрос в конце, поэтому как раз часть

SQL
1
table1.fk = table2.pk

так и не понял, просто не запомнил, что там написал.



0



Аватар

1419 / 887 / 339

Регистрация: 31.05.2012

Сообщений: 3,114

09.10.2022, 09:13

4

SQL
1
ON users.hobby = hobby.hobby_name



0



4716 / 3924 / 994

Регистрация: 29.08.2013

Сообщений: 25,176

Записей в блоге: 3

09.10.2022, 17:40

5

Цитата
Сообщение от yoimelv
Посмотреть сообщение

Делали задание в классе, там всё получилось

так голову нужно включать
таблицы то соединяются по колонкам, а у вас явное сообщение «столбец users.fk не существует»



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

09.10.2022, 17:40

Помогаю со студенческими работами здесь

DataGridView. Существует ли столбец?
Как мне узнать, существует ли столбец с заданным именем в DataGridView?
Проверять в цикле не…

Ошибка — Не существует в пространстве имен, но оно существует!
Всем привет! В соседней ветке пытаюсь разобраться как адекватно сделать вертикальную менюшку, но…

База данных — столбец в таблице не существует
pgAdmin 4 выдает ошибку: ERROR: ОШИБКА: столбец &quot;Дискретная математика&quot; в таблице &quot;Экзамены&quot; не…

Как проверить существует ли столбец в DGV
у меня в компоненте грид столбцы создаются динамически, так вот как создать условие которое…

Существует ли в матрице столбец, состоящий только из нулей
Заполнить массив 2 на 5 случайными числами от 0 до 1. вывести «да», если существует столбец,…

Существует ли в матрице строка или столбец палиндром
помогите пожалуйста создать программу для задачи :
существует ли в матрице строка или столбец…

Функция определяющая, существует ли столбец матрицы, упорядоченный по возрастанию
помогите написать ТОЛЬКО ФУНКЦИЮ.
А именно, описать функцию проверки, существует ли в квадратной…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

5

Ребят, я неофит в SQL и только учусь..может кто подсказать, в чём проблема ?
Таблицу создал, название колонок также заполнил, а вот с самим наполнением этих самых колонок беда, не понимаю из-за чего проблема. Помогите пожалуйста:
6229b1176741e325792085.pngQ


  • Вопрос задан

    10 мар. 2022

  • 302 просмотра

Проблема из-за того, что вы нарушили синтаксис запроса в месте вставки значения, подсвеченного курсором на скриншоте. Более подробно можно ответить, если вы предоставите структуру данной таблицы. Пока же можно лишь предположить, что вы, пытаясь вставить текстовые данные, забыли обрамить их в одинарные кавычки.

Пригласить эксперта


  • Показать ещё
    Загружается…

29 янв. 2023, в 03:07

300000 руб./за проект

29 янв. 2023, в 02:16

700000 руб./за проект

29 янв. 2023, в 01:54

5000 руб./за проект

Минуточку внимания

Problem

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703 when running CDT and comparing source and target environments

Symptom

You are running CDT tool and using Configuration Data Deployment option to compare source and target database. You are seeing the above mentioned error.

Environment

Sterling Order Management

Diagnosing The Problem

Error example:

<Error ErrorCode=»-206″         ErrorDescription=»DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=YFS_USER.EXTN_USER_ACTIVE, DRIVER=3.62.56″ ErrorRelatedMoreInfo=»»>

This error suggests database is missing EXTN_USER_ACTIVE column in YFS_USER table.

Resolving The Problem

You have extended source database but did not apply same extensions on target environment. CDT can not add extended column(s) to target database, CDT migrates its data. Please apply same extensions to your target environment (database) to resolve the problem.

Note: At the moment, CDT does not migrate Shadow columns data. To populate Shadow columns please run YCPCaseInsensitiveDataLoaderAgent in the target environment.

[{«Product»:{«code»:»SS6PEW»,»label»:»Sterling Order Management»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Extensions»,»Platform»:[{«code»:»PF016″,»label»:»Linux»}],»Version»:»9.3″,»Edition»:»»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}}]

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Sql как вызвать ошибку
  • Sql error 42702 ошибка неоднозначная ссылка на столбец