So I’m starting with this…
SELECT * FROM parts_finishing;
…I get this…
id, id_part, id_finish, id_metal, id_description, date,
inside_hours_k, inside_rate, outside_material(0 rows)
…so everything looks fine so far so I do this…
INSERT INTO parts_finishing
(
id_part, id_finish, id_metal, id_description,
date, inside_hours_k, inside_rate, outside_material
) VALUES (
('1013', '6', '30', '1', NOW(), '0', '0', '22.43'),
('1013', '6', '30', '2', NOW(), '0', '0', '32.45'));
…and I get…
ERROR: INSERT has more target columns than expressions
Now I’ve done a few things like ensuring numbers aren’t in quotes, are in quotes (would love a table guide to that in regards to integers, numeric types, etc) after I obviously counted the number of column names and values being inserted. I also tried making sure that all the commas are commas…really at a loss here. There are no other columns except for id
which is the bigserial
primary key
.
If you encounter an error that reads “INSERT has more expressions than target columns” when trying to insert data in Postgres, it’s because you’re trying to insert data into more columns than the table actually contains.
For example, you might be trying to insert four expressions into a table that contains just three columns.
To fix, remove the extra expression/s from your INSERT
statement. In other words, make sure you’re inserting the correct number of columns.
Example of Error
Suppose we have a table like this:
+-------+---------+---------+ | petid | petname | pettype | +-------+---------+---------+ | 1 | Fluffy | Cat | | 2 | Tweet | Bird | +-------+---------+---------+
That table has three columns.
Now, suppose we want to insert another row.
Here’s how to generate the error:
INSERT INTO Pets VALUES ( 3, 'Wag', 'Dog', 'Brown' );
Result:
ERROR: INSERT has more expressions than target columns LINE 1: INSERT INTO Pets VALUES ( 3, 'Wag', 'Dog', 'Brown' ); ^
Here, I tried to insert four expressions into a table that only has three columns.
Solution
The solution is easy. Remove the extra expression:
INSERT INTO Pets VALUES ( 3, 'Wag', 'Dog' );
Here, I removed the last expression (Brown
) from the VALUES
list. This resulted in the row being inserted without error.
Or, to make sure you don’t inadvertently insert data into the wrong column, you can explicitly state each column:
INSERT INTO Pets ( PetId, PetName, PetType )
VALUES ( 1, 'Wag', 'Dog' );
After running one of the above statements, the table now looks like this:
SELECT * FROM Pets;
Result:
+-------+---------+---------+ | petid | petname | pettype | +-------+---------+---------+ | 1 | Fluffy | Cat | | 2 | Tweet | Bird | | 3 | Wag | Dog | +-------+---------+---------+
We have successfully inserted the row into the table.
Содержание
- Database.Guide
- Beginners
- Categories
- Fix “INSERT has more expressions than target columns” in PostgreSQL
- Example of Error
- Solution
- PostgreSQL ERROR: INSERT имеет больше целевых столбцов, чем выражения, когда это не
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- ERROR: INSERT has more target columns than expressions
Database.Guide
Beginners
Categories
- Azure SQL Edge (16)
- Database Concepts (48)
- Database Tools (70)
- DBMS (8)
- MariaDB (420)
- Microsoft Access (17)
- MongoDB (265)
- MySQL (375)
- NoSQL (7)
- Oracle (296)
- PostgreSQL (255)
- Redis (184)
- SQL (588)
- SQL Server (888)
- SQLite (235)
Fix “INSERT has more expressions than target columns” in PostgreSQL
If you encounter an error that reads “INSERT has more expressions than target columns” when trying to insert data in Postgres, it’s because you’re trying to insert data into more columns than the table actually contains.
For example, you might be trying to insert four expressions into a table that contains just three columns.
To fix, remove the extra expression/s from your INSERT statement. In other words, make sure you’re inserting the correct number of columns.
Example of Error
Suppose we have a table like this:
That table has three columns.
Now, suppose we want to insert another row.
Here’s how to generate the error:
Here, I tried to insert four expressions into a table that only has three columns.
Solution
The solution is easy. Remove the extra expression:
Here, I removed the last expression ( Brown ) from the VALUES list. This resulted in the row being inserted without error.
Or, to make sure you don’t inadvertently insert data into the wrong column, you can explicitly state each column:
After running one of the above statements, the table now looks like this:
We have successfully inserted the row into the table.
Источник
PostgreSQL ERROR: INSERT имеет больше целевых столбцов, чем выражения, когда это не
Итак, я начинаю с этого.
id, id_part, id_finish, id_metal, id_description, date, inside_hours_k, inside_rate, outside_material
. так что все выглядит нормально до сих пор, поэтому я делаю это.
ОШИБКА: INSERT имеет больше столбцов назначения, чем выражения
Теперь я сделал несколько вещей, например, чтобы гарантировать, что числа не указаны в кавычках, в кавычках (хотелось бы, чтобы руководство по таблицам относилось к целым числам, числовым типам и т.д.) после того, как я, очевидно, подсчитал количество имен столбцов и значения вставляются. Я также попытался убедиться, что все запятые запятые. действительно в растерянности здесь. Нет других столбцов, кроме id , который является bigserial primary key .
ОТВЕТЫ
Ответ 1
Ответ 2
У меня была похожая проблема при использовании композиции строк SQL с psycopg2 в Python, но проблема была немного другой. Мне не хватало запятой после одного из полей.
Это заставило psycopg2 эту ошибку:
ОШИБКА: У INSERT больше целевых столбцов, чем выражений.
Ответ 3
Это произошло со мной в большой вставке, все было хорошо (запятая), мне потребовалось некоторое время, чтобы заметить, что я вставляю не в ту таблицу, конечно, БД не знает ваших намерений. Копи-паста — корень всего зла. 🙂
Ответ 4
Я также столкнулся с той же проблемой. Она будет поднята, когда количество приведенных столбцов и значений столбцов не совпадают.
Ответ 5
Я также сталкиваюсь с той же проблемой. ОШИБКА: В INSERT больше целевых столбцов, чем в выражениях. ЛИНИЯ 16: NAVIGATOR_KEYWORDS
Источник
ERROR: INSERT has more target columns than expressions
To: pgsql-novice(at)postgresql(dot)org Subject: ERROR: INSERT has more target columns than expressions Date: 2004-10-18 14:09:15 Message-ID: 20041018140915.64627.qmail@web51408.mail.yahoo.com Views: Raw Message | Whole Thread | Download mbox | Resend email Thread: Lists: pgsql-novice
Dear Group,
I am trying to insert data in to a single row
(although I have
10K rows to fill, I am
experimenting with one row because this data is highly
inconsistent )
mtdase=> INSERT INTO cdna_exp
(cdna_SPOT,cdna_NAME,cdna_Clone_ID,cdna_Gene_Symbol,cdna_Gene_Name,cdna_Cluster_ID,cdna_Accession,cdna_Preferred_name,cdna_SUID,cdna_CH1I_MEAN,cdna_CH1D_MEDIAN,cdna_CH1I_MEDIAN,cdna_CH1_PER_SAT,cdna_CH1I_SD,cdna_CH1B_MEAN,cdna_CH1B_MEDIAN,cdna_CH1B_SD,cdna_CH1D_MEAN,cdna_CH2I_MEAN,cdna_CH2D_MEAN,cdna_CH2D_MEDIAN,cdna_CH2I_MEDIAN,cdna_CH2_PER_SAT,cdna_CH2I_SD,cdna_CH2B_MEAN,cdna_CH2B_MEDIAN,cdna_CH2B_SD,cdna_CH2BN_MEDIAN,cdna_CH2DN_MEAN,cdna_CH2IN_MEAN,cdna_CH2DN_MEDIAN,cdna_CH2IN_MEDIAN,cdna_CORR,cdna_DIAMETER,cdna_FLAG,cdna_LOG_RAT2N_MEAN,cdna_LOG_RAT2N_MEDIAN,cdna_PIX_RAT2_MEAN,cdna_PIX_RAT2_MEDIAN,cdna_PERGTBCH1I_1SD,cdna_PERGTBCH1I_2SD,cdna_PERGTBCH2I_1SD,cdna_PERGTBCH2I_2SD,cdna_RAT1_MEAN,cdna_RAT1N_MEAN,cdna_RAT2_MEAN,cdna_RAT2_MEDIAN,cdna_RAT2_SD,cdna_RAT2N_MEAN,cdna_RAT2N_MEDIAN,cdna_REGR,cdna_SUM_MEAN,cdna_SUM_MEDIAN,cdna_TOT_BPIX,cdna_TOT_SPIX,cdna_X_COORD,cdna_Y_COORD,cdna_TOP,cdna_BOT,cdna_LEFT,cdna_RIGHT,cdna_SECTOR,cdna_SECTORROW,cdna_SECTORCOL,cdna_SOURCE,cdna_
PLATE,cd
na_PROW,cdna_PCOL,cdna_FAILED,cdna_IS_VERIFIED,cdna_IS_CONTAMINATED,cdna_LUID)
VALUES (
‘9215’,’18491′,’IMAGE:267638′,’FLJ22004′,’hypothetical
protein
FLJ22004′,’Hs.108812′,’N25427′,NULL,’115416′,’224′,NULL,NULL,NULL,NULL,’289′,’135′,NULL,’89’,’348′,’58’,NULL,NULL,NULL,NULL,’390′,’290′,NULL,’439′,’88’,’527′,NULL,NULL,’0.625′,NULL,’0′,’-0.019′,NULL,NULL,’0.782′,’34’,NULL,’23’,NULL,’1.534′,’1.013′,’0.652′,NULL,NULL,’0.987′,NULL,’0.6′,NULL,NULL,’1126′,’52’,NULL,NULL,’960′,’968′,’996′,’1004′,’16’,’24’,’23’,’GF201:96(69H10):384(24P20)’,’24’,’P’,’20’,’0′,’Y’,’U’);
ERROR: INSERT has more target columns than
expressions
How is this possible I have 71 expressions and 71
values in the statement. Is there a problem that I am
not exposed to deal with. Experts, can you please
help me.
Источник
Hello !
I have two tables: user
& test
located in a private
schema.
- user has :
user_id
,avatar
,fullName
andcolor
columns - test has :
user_id
,icon_id
andurl
columns
I tried this with :
db.private.user.insert({ user_id: 'b146c47f-3380-49b4-8022-58a7d47f56d7', avatar: 'string', fullName: 'string', color: 'string', 'private.test': [ { user_id: 'b146c47f-3380-49b4-8022-58a7d47f56d7', icon_id: 'twitter', url: 'http://plokok' } ] });
And got the error INSERT has more expressions than target columns
.
The SQL generated is:
WITH inserted AS ( INSERT INTO "private"."user" ("user_id", "avatar", "fullName", "color") VALUES ('481ea860-3555-4859-a373-7ae4da46816e', 'string', 'string', 'string') RETURNING * ), q_0_0 AS ( INSERT INTO private.test ("user_id", "icon_id", "url") SELECT "user_id", '481ea860-3555-4859-a373-7ae4da46816e', 'twitter', 'http://plokok' FROM inserted ) SELECT * FROM inserted
As we can see it seems massive adds a «SELECT «user_id»,» where it should not and use «VALUES(» instead.
Note:
I had to explicitly specify private
schema for link relation, I had though db.private
was enough, is this a bug?
Database.Guide
Beginners
Categories
- Azure SQL Edge (16)
- Database Concepts (48)
- Database Tools (70)
- DBMS (8)
- MariaDB (420)
- Microsoft Access (17)
- MongoDB (265)
- MySQL (375)
- NoSQL (7)
- Oracle (296)
- PostgreSQL (255)
- Redis (180)
- SQL (588)
- SQL Server (887)
- SQLite (235)
Fix “INSERT has more expressions than target columns” in PostgreSQL
If you encounter an error that reads “INSERT has more expressions than target columns” when trying to insert data in Postgres, it’s because you’re trying to insert data into more columns than the table actually contains.
For example, you might be trying to insert four expressions into a table that contains just three columns.
To fix, remove the extra expression/s from your INSERT statement. In other words, make sure you’re inserting the correct number of columns.
Example of Error
Suppose we have a table like this:
That table has three columns.
Now, suppose we want to insert another row.
Here’s how to generate the error:
Here, I tried to insert four expressions into a table that only has three columns.
Solution
The solution is easy. Remove the extra expression:
Here, I removed the last expression ( Brown ) from the VALUES list. This resulted in the row being inserted without error.
Or, to make sure you don’t inadvertently insert data into the wrong column, you can explicitly state each column:
After running one of the above statements, the table now looks like this:
We have successfully inserted the row into the table.
Источник
PostgreSQL ERROR: INSERT имеет больше целевых столбцов, чем выражения, когда это не
Итак, я начинаю с этого.
id, id_part, id_finish, id_metal, id_description, date, inside_hours_k, inside_rate, outside_material
. так что все выглядит нормально до сих пор, поэтому я делаю это.
ОШИБКА: INSERT имеет больше столбцов назначения, чем выражения
Теперь я сделал несколько вещей, например, чтобы гарантировать, что числа не указаны в кавычках, в кавычках (хотелось бы, чтобы руководство по таблицам относилось к целым числам, числовым типам и т.д.) после того, как я, очевидно, подсчитал количество имен столбцов и значения вставляются. Я также попытался убедиться, что все запятые запятые. действительно в растерянности здесь. Нет других столбцов, кроме id , который является bigserial primary key .
ОТВЕТЫ
Ответ 1
Ответ 2
У меня была похожая проблема при использовании композиции строк SQL с psycopg2 в Python, но проблема была немного другой. Мне не хватало запятой после одного из полей.
Это заставило psycopg2 эту ошибку:
ОШИБКА: У INSERT больше целевых столбцов, чем выражений.
Ответ 3
Это произошло со мной в большой вставке, все было хорошо (запятая), мне потребовалось некоторое время, чтобы заметить, что я вставляю не в ту таблицу, конечно, БД не знает ваших намерений. Копи-паста — корень всего зла. 🙂
Ответ 4
Я также столкнулся с той же проблемой. Она будет поднята, когда количество приведенных столбцов и значений столбцов не совпадают.
Ответ 5
Я также сталкиваюсь с той же проблемой. ОШИБКА: В INSERT больше целевых столбцов, чем в выражениях. ЛИНИЯ 16: NAVIGATOR_KEYWORDS
Источник
Home
PostgreSQL
PostgreSQL INSERT has more target columns than expressions
PostgreSQL INSERT has more target columns than expressions
INSERT has more target columns than expressions in PL/pgSQL
INSERT has more target columns
The cause of error: INSERT has more target columns than expressions in PL/pgSQL.
The solution is to check the number of columns from the insert row.
Create Students table
CREATE TABLE test.students ( id numeric NOT NULL, first_name character varying(50) NOT NULL, last_name character varying(50) NOT NULL, entry_date timestamp without time zone DEFAULT now(), address_id numeric, CONSTRAINT studentss_pkey PRIMARY KEY (id) );
CREATE TABLE
Query returned successfully in 506 msec.
Wrong insert
INSERT INTO test.students (id, first_name, last_name) VALUES (4, 'Sandra');
ERROR: INSERT has more target columns than expressions
LINE 1: INSERT INTO test.students (id, first_name, last_name) VALUES…
^
Query returned successfully in 430 msec.
Correct insert
INSERT INTO test.students (id, first_name, last_name) VALUES (4, 'Sandra', 'Green');
INSERT 0 1
Query returned successfully in 393 msec.
Итак, я начинаю с этого…
SELECT * FROM parts_finishing;
… Я получаю это…
id, id_part, id_finish, id_metal, id_description, date, inside_hours_k, inside_rate, outside_material
(0 строк)
… так что все выглядит нормально до сих пор, поэтому я делаю это…
INSERT INTO parts_finishing
(
id_part, id_finish, id_metal, id_description,
date, inside_hours_k, inside_rate, outside_material
) VALUES (
('1013', '6', '30', '1', NOW(), '0', '0', '22.43'),
('1013', '6', '30', '2', NOW(), '0', '0', '32.45'));
… и я получаю…
ОШИБКА: INSERT имеет больше столбцов назначения, чем выражения
Теперь я сделал несколько вещей, например, чтобы гарантировать, что числа не указаны в кавычках, в кавычках (хотелось бы, чтобы руководство по таблицам относилось к целым числам, числовым типам и т.д.) после того, как я, очевидно, подсчитал количество имен столбцов и значения вставляются. Я также попытался убедиться, что все запятые запятые… действительно в растерянности здесь. Нет других столбцов, кроме id
, который является bigserial
primary key
.
Ответ 1
Удалите лишний ()
:
INSERT INTO parts_finishing
(
id_part, id_finish, id_metal, id_description,
date, inside_hours_k, inside_rate, outside_material
) VALUES
('1013', '6', '30', '1', NOW(), '0', '0', '22.43')
, ('1013', '6', '30', '2', NOW(), '0', '0', '32.45')
;
Ответ 2
У меня была похожая проблема при использовании композиции строк SQL с psycopg2
в Python, но проблема была немного другой. Мне не хватало запятой после одного из полей.
INSERT INTO parts_finishing
(id_part, id_finish, id_metal)
VALUES (
%(id_part)s <-------------------- missing comma
%(id_finish)s,
%(id_metal)s
);
Это заставило psycopg2
эту ошибку:
ОШИБКА: У INSERT больше целевых столбцов, чем выражений.
Ответ 3
Это произошло со мной в большой вставке, все было хорошо (запятая), мне потребовалось некоторое время, чтобы заметить, что я вставляю не в ту таблицу, конечно, БД не знает ваших намерений. Копи-паста — корень всего зла…
Ответ 4
Я также столкнулся с той же проблемой. Она будет поднята, когда количество приведенных столбцов и значений столбцов не совпадают.
Ответ 5
INSERT INTO NAVIGATORS_DETAILS(
NAVIGATOR_NAME ,
NAVIGATOR_EMAIL ,
NAVIGATOR_GENDER ,
NAVIGATOR_COUNTRY_OF_RESIDENCE ,
NAVIGATOR_YEARS_OF_EXPERIENCE ,
NAVIGATOR_DOB ,
NAVIGATOR_SPELCIALIST ,
IS_ICF_CERTIFIED ,
ICF_NO ,
IS_VERIFIED ,
VERIFICATION_COUNTRY_ID ,
VERIFICATION_STATUS ,
NAVIGATOR_MOBILE ,
NAVIGATOR_BIO ,
NAVIGATOR_KEYWORDS
) VALUES (
'shrisom',
'[email protected]',
'MALE',
'India',
12,
'12/01/2019',
null,
false,
null,
false,
null,
'NOT_APPLIED'
'8961234500',
null,
null
)
Я также сталкиваюсь с той же проблемой. ОШИБКА: В INSERT больше целевых столбцов, чем в выражениях. ЛИНИЯ 16: NAVIGATOR_KEYWORDS
Remove the extra ()
:
INSERT INTO parts_finishing
(
id_part, id_finish, id_metal, id_description,
date, inside_hours_k, inside_rate, outside_material
) VALUES
(1013, 6, 30, 1, NOW(), 0, 0, 22.43)
, (1013, 6, 30, 2, NOW(), 0, 0, 32.45)
;
the (..., ...)
in Postgres is the syntax for a tuple literal; The extra set of (
)
would create a tuple of tuples, which makes no sense.
Also: for numeric literals you dont want the quotes:
(1013, 6, 30, 1, NOW(), 0, 0, 22.43)
, ...
, assuming all these types are numerical.
I had a similar problem when using SQL string composition with psycopg2
in Python, but the problem was slightly different. I was missing a comma after one of the fields.
INSERT INTO parts_finishing
(id_part, id_finish, id_metal)
VALUES (
%(id_part)s <-------------------- missing comma
%(id_finish)s,
%(id_metal)s
);
This caused psycopg2
to yield this error:
ERROR: INSERT has more target columns than expressions.
PostgreSQL ERROR: INSERT has more target columns than expressions, when it doesnt
This happened to me in a large insert, everything was ok (comma-wise), it took me a while to notice I was inserting in the wrong table of course the DB does not know your intentions.
Copy-paste is the root of all evil … 🙂
Related posts on PostgreSQL :
- Are there performance issues storing files in PostgreSQL?
- create table – What does regclass mean in Postgresql
- postgresql – How to get First and Last record from a sql query?
- plpgsql – Raising error in postgreSQL
- postgresql – Postgres default sort by id – worldship
- postgresql – Heroku download pg:backups how to
- .net – PostgreSQL set session variable
- postgresql – Querying Postgres 9.6 JSONB array of objects
- postgresql – Is there any shortcut for using dblink in Postgres?