Ошибка столбец не существует postgresql

As others suggested in comments, this is probably a matter of upper-case versus lower-case, or some whitespace in the column name. (I’m using an answer so I can format some code samples.) To see what the column names really are, try running this query:

SELECT '"' || attname || '"', char_length(attname)
  FROM pg_attribute
  WHERE attrelid = 'table_name'::regclass AND attnum > 0
  ORDER BY attnum;

You should probably also check your PostgreSQL server log if you can, to see what it reports for the statement.

If you quote an identifier, everything in quotes is part of the identifier, including upper-case characters, line endings, spaces, and special characters. The only exception is that two adjacent quote characters are taken as an escape sequence for one quote character. When an identifier is not in quotes, all letters are folded to lower-case. Here’s an example of normal behavior:

test=# create table t (alpha text, Bravo text, "Charlie" text, "delta " text);
CREATE TABLE
test=# select * from t where Alpha is null;
 alpha | bravo | Charlie | delta  
-------+-------+---------+--------
(0 rows)

test=# select * from t where bravo is null;
 alpha | bravo | Charlie | delta  
-------+-------+---------+--------
(0 rows)

test=# select * from t where Charlie is null;
ERROR:  column "charlie" does not exist
LINE 1: select * from t where Charlie is null;
                              ^
test=# select * from t where delta is null;
ERROR:  column "delta" does not exist
LINE 1: select * from t where delta is null;
                              ^

The query I showed at the top yields this:

 ?column?  | char_length 
-----------+-------------
 "alpha"   |           5
 "bravo"   |           5
 "Charlie" |           7
 "delta "  |           6
(4 rows)

Создаю отношение

create table ПОТРЕБИТЕЛЬ (
    ИДЕНТИФИКАТОР serial not null primary key,
    НАЗВАНИЕ varchar(50) not null,
    "АДРЕС ЖИТЕЛЬСТВА" varchar(255) not null,
    "СКИДКА, %" smallint check ("СКИДКА, %" >= 0 and "СКИДКА, %" <= 100) not null
);

Затем пытаюсь заполнить таблицу, используя значения

insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (001, "АО ВАРЯ", "Сормовский", 10);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (002, "ГАЗ", "Автозаводский", 7);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (003, "МП ВЕРА", "Канавинский", 5);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (004, "МП", "Канавинский", 3);
insert into ПОТРЕБИТЕЛЬ (ИДЕНТИФИКАТОР, НАЗВАНИЕ, "АДРЕС ЖИТЕЛЬСТВА", "СКИДКА, %") values (005, "АО СТАЛЬ", "Советский", 0);

Возникает ошибка в каждой строчке, якобы столбец не существует, при этом это даже не столбцы а аргументы
введите сюда описание изображения

    Меня все больше удивляют авторы СУБД PostgreSQL. На моих тестовых серверах и у клиентов установлена ее 11-я версия. Обычно я стараюсь себе на компьютер устанавливать последние версии программного обеспечения. Так же было и с PostgreSQL — когда возникла необходимость ее установить локально, я установил 12-ю версию. Залил дамп базы, запустил свою утилиту и получил ошибку «column pd.adsrc does not exist». Я сразу подумал, что при импорте дампа возникла ошибка и загрузил его снова. Но ошибка повторилась. Установил PostgreSQL на другой компьютер и получил «столбец pd.adsrc не существует».
    Гугл быстро дал ответ на мою проблему. Оказалось, что в PostgreSQL 12-й версии из системной таблицы pg_catalog.pg_attrdef разработчики удалили поле «adsrc». Они просто решили, что это поле устаревшее и оно им не нужно… Вот разве так можно? Гора программного обеспечения, которую годами разрабатывали программисты по всему миру, перестанет корректно работать на новой версии СУБД. Может мне везло, но с подобной проблемой я не сталкивался ни у Oracle, ни у MS SQLServer. Например, недавно я узнал, что несколько почтовых сервисов, который я писал примерно 16-18 лет тому назад, успешно работают с базой данных на MS SQLServer 2019. Таким образом в моих глазах СУБД PostgreSQL получает очередной минус.
    Все предлагаемые мне гуглом варианты решения этой проблемы были для pgAdmin. А что делать тем, у кого запросы не в скрипте, а в бинарнике? Первая моя мысль была добавить поле adsrc в таблицу pg_catalog.pg_attrdef. Но все же я решил, что это не выход. Правильно решать ее в своей программе. В используемой мной библиотеке для доступа к базам данных «PostgreSQL 12 is supported» только с версии 8.1. То есть для меня путь к 12-й версии PostgreSQL один — «достать кошелек» и обновить UniDac. Эта ситуация с PostgreSQL еще раз подтвердила, что использование open source продуктов, даже если не на прямую, а косвенно, но все равно приводит к лишним затратам.

PostgreSQL column does not exist

Definition of the PostgreSQL column does not exist exception.

PostgreSQL column does not exist exception occurs when we have used a column that did not exist in the table, or it will occur when the used column name has a lower case name, and we have used upper case in our query. We can avoid this exception in many ways, like double-quote the column name for which column we have to get the exception. We can also check the column name which existed in the table or not. If the column name does not exist in the table, then we need to create the same into the table.

Syntax:

Below is the column name syntax that does not exist except in PostgreSQL.

  • Column name does not exist exception using select
Select name_of_column from name_of_table limit (number);
  1. Error: column name_of_column does not exist
  2. Line1: select name_of_column from name_of_table limit (number);
  • Column name does not exist exception using insert
Insert into name_of_table (name_of_column1, name_of_column2, name_of_column3, …, name_of_columnN) values (Value_of_column1, Value_of_column2, Value_of_column3, …, Value_of_columnN);
  1. ERROR: column “name_of_column” does not exist
  2. LINE 1: insert into name_of_table (name_of_column1, name_of_column2, name_of_column3, …, name_of_columnN) values (Value_of_column1, Value_of_column2, Value_of_column3, …, Value_of_columnN)
  • Column name does not exist exception using update
update name_of_table set name_of_column = (value_of_column) where condition;
  1. ERROR: column “name_of_column” does not exist
  2. LINE 1: update name_of_table set name_of_column = value_of_column where name_of_column = ‘value_of_column’;
  • Column name does not exist exception using delete
Delete from name_of_table where name_of_column = value_of_column;
  1. ERROR: column “name_of_column” does not exist
  2. LINE 1: delete from name_of_table where name_of_column = value_of_column;

Below is the parameter description syntax of column name does not exist exception in PostgreSQL.

  • Select –Column name does not exist, an exception will display while we have to execute a select operation on the specified column.
  • Insert – Column name does not exist exception will display while we have to execute insert operation on a specified column.
  • Update – Column name does not exist exception will display while we have to execute update operation on the specified column.
  • Delete – Column name does not exist exception will display while we have to execute delete operation on the specified column.
  • Name of the column –This is defined as the column name from which we have received the exception that the column name does not exist.
  • Name of the table –This is defined as the table name from which we have received the exception that the column name does not exist.

How column does not exist exception raised in PostgreSQL?

  • The column does not exist exception occurs when a column does not exist in the table. If the searching column does not exist in the table, then it will raise the exception that the column does not exist in the table.
  • The below example shows that if a searching column does not exist in the table, it will give the exception that the column name does not exist.
d+ test_col;
select ID_Name from test_col;

PostgreSQL column does not exist 1

  • In the above example, we have used the ID_Name column for searching the data from the test_col table, but it will issues an error that the column name does not exist in the table because the ID_Name column does not exist in the table.
  • To select, update, delete, and insert the data into the table, we need to define the correct column name, which we searched for.
  • Also, we need to define the column name in a double quote if our column name contains a mixed letter.
  • The example below shows that we need to define the double quote when using a mixed letter column in operations.
select address from test_col;
d+ test_col;

PostgreSQL column does not exist 2

  • In the above example, we have used the address column, which contains the mixed letter, after using this column, it will issue an error because it will contain the mixed column letter.

Examples

  • Below is an example of a column that does not exist exception. We have using a test_col table to describe an example of a column name that does not exist exception.
  • Below are the data and table structure of the test_col table.
select * from test_col;
d+ test_col;

PostgreSQL column does not exist 3

1. Column name does not exist exception using select

  • The below example shows that the column name does not exception using select operations.
select Name, ID from test_col;
select "Name", "ID" from test_col;

example 1

2. Column name does not exist exception using insert

  • The below example shows that the column name does not exception using insert operations.
insert into test_col (ID, Name, AddRess, PhoNe) values (3, 'ABC', 'Mumbai', 1234567890);
insert into test_col ("ID", "Name", "AddRess", "PhoNe") values (4, 'PQR', 'Mumbai', 1234567890);

example 2

3. Column name does not exist exception using update

  • The below example shows that the column name does not exception using update operations.
update test_col set ID = 5 where Name = 'ABC';
update test_col set "ID" = 5 where "Name" = 'ABC';
select * from test_col;

example 3

4. Column name does not exist exception using delete

  • The below example shows that the column name does not exception using delete operations.
delete from test_col where ID = 4;
delete from test_col where "ID" = 4;
select * from test_col;

example 4

How to avoid a column that does not exist exception?

  • We can avoid the column does not exist exception by specifying the name of the column. Below is the example to avoid the column does not exist exception.
select test_name from test_col;
select "Name" from test_col;

PostgreSQL column does not exist 4

  • We can also avoid the exception by using the double quote in the column. Below example shows that use a double quote to avoid exception.
select Name from test_col;
select "Name" from test_col;

PostgreSQL column does not exist 5

Conclusion

The column does not exist exception occurs in PostgreSQL when we have not used a specified column name while doing any operations. Also, it occurs when we have not used a double quote to the mismatch case letter column name in PostgreSQL.

Recommended Articles

We hope that this EDUCBA information on “PostgreSQL column does not exist” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. PostgreSQL enum
  2. Count PostgreSQL
  3. PostgreSQL Partition
  4. PostgreSQL Describe Table

yoimelv

0 / 0 / 0

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

Сообщений: 12

1

08.10.2022, 21:58. Показов 2556. Ответов 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



5090 / 4103 / 1027

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

Сообщений: 26,011

Записей в блоге: 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



Аватар

1556 / 988 / 376

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

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

09.10.2022, 09:13

4

SQL
1
ON users.hobby = hobby.hobby_name



0



5090 / 4103 / 1027

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

Сообщений: 26,011

Записей в блоге: 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

Понравилась статья? Поделить с друзьями:
  • Ошибка стоит дорого
  • Ошибка срс мерседес 220
  • Ошибка срс мерседес 210
  • Ошибка срок службы впитывающей чернила подкладки принтера заканчивается
  • Ошибка срок использования равен нулю для основного средства