Error syntax error at or near create table

PostgreSQL error 42601 mainly occurs due to the syntax errors in the code. Proper syntax check and code correction will fix it up.

Syntax errors are quite common while coding.

But, things go for a toss when it results in website errors.

PostgreSQL error 42601 also occurs due to syntax errors in the database queries.

At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.

Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.

What causes error 42601 in PostgreSQL?

PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.

Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.

But what causes error 42601?

PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.

Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.

In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:

Here, the syntax error has occurred in position 119 near the value “parents” in the query.

How we fix the error?

Now let’s see how our PostgreSQL engineers resolve this error efficiently.

Recently, one of our customers contacted us with this error. He tried to execute the following code,

CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
WITH m_ty_person AS (return query execute sql)
select name, count(*) from m_ty_person where name like '%a%' group by name
union
select name, count(*) from m_ty_person where gender = 1 group by name;
END
$$ LANGUAGE plpgsql;

But, this ended up in PostgreSQL error 42601. And he got the following error message,

ERROR: syntax error at or near "return"
LINE 5: WITH m_ty_person AS (return query execute sql)

Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,

RETURN QUERY EXECUTE '
WITH m_ty_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM m_ty_person WHERE name LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM m_ty_person WHERE gender = 1 GROUP BY name$x$;

This resolved the error 42601, and the code worked fine.

[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]

Conclusion

In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error 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»;

@YohDeadfall — I understand that part about it, but this is not script that I am creating or even code that I am creating. This is all created under the hood by Npsql/EntityFramework. My quick guess is that I am extending my DbContext from IdentityDbContext<IdentityUser> which wants to create all of the tables for roles, users, claims, etc. If I change this to just extend from DbContext, then everything works as advertised.

Below is the script that EF is trying to use created from dotnet ef migrations script — please be aware that I have removed my custom part of the script for brevity.

You can see there are two specific calls that are being made where [NormalizedName] and [NormalizedUserName] are being used.

CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" (
    "MigrationId" varchar(150) NOT NULL,
    "ProductVersion" varchar(32) NOT NULL,
    CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId")
);

CREATE TABLE "AspNetRoles" (
    "Id" text NOT NULL,
    "ConcurrencyStamp" text NULL,
    "Name" varchar(256) NULL,
    "NormalizedName" varchar(256) NULL,
    CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id")
);

CREATE TABLE "AspNetUsers" (
    "Id" text NOT NULL,
    "AccessFailedCount" int4 NOT NULL,
    "ConcurrencyStamp" text NULL,
    "Email" varchar(256) NULL,
    "EmailConfirmed" bool NOT NULL,
    "LockoutEnabled" bool NOT NULL,
    "LockoutEnd" timestamptz NULL,
    "NormalizedEmail" varchar(256) NULL,
    "NormalizedUserName" varchar(256) NULL,
    "PasswordHash" text NULL,
    "PhoneNumber" text NULL,
    "PhoneNumberConfirmed" bool NOT NULL,
    "SecurityStamp" text NULL,
    "TwoFactorEnabled" bool NOT NULL,
    "UserName" varchar(256) NULL,
    CONSTRAINT "PK_AspNetUsers" PRIMARY KEY ("Id")
);

CREATE TABLE "AspNetRoleClaims" (
    "Id" int4 NOT NULL,
    "ClaimType" text NULL,
    "ClaimValue" text NULL,
    "RoleId" text NOT NULL,
    CONSTRAINT "PK_AspNetRoleClaims" PRIMARY KEY ("Id"),
    CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserClaims" (
    "Id" int4 NOT NULL,
    "ClaimType" text NULL,
    "ClaimValue" text NULL,
    "UserId" text NOT NULL,
    CONSTRAINT "PK_AspNetUserClaims" PRIMARY KEY ("Id"),
    CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserLogins" (
    "LoginProvider" text NOT NULL,
    "ProviderKey" text NOT NULL,
    "ProviderDisplayName" text NULL,
    "UserId" text NOT NULL,
    CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY ("LoginProvider", "ProviderKey"),
    CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserRoles" (
    "UserId" text NOT NULL,
    "RoleId" text NOT NULL,
    CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY ("UserId", "RoleId"),
    CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE,
    CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE TABLE "AspNetUserTokens" (
    "UserId" text NOT NULL,
    "LoginProvider" text NOT NULL,
    "Name" text NOT NULL,
    "Value" text NULL,
    CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY ("UserId", "LoginProvider", "Name"),
    CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE
);

CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ("RoleId");

CREATE UNIQUE INDEX "RoleNameIndex" ON "AspNetRoles" ("NormalizedName") WHERE [NormalizedName] IS NOT NULL;

CREATE INDEX "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ("UserId");

CREATE INDEX "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ("UserId");

CREATE INDEX "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ("RoleId");

CREATE INDEX "EmailIndex" ON "AspNetUsers" ("NormalizedEmail");

CREATE UNIQUE INDEX "UserNameIndex" ON "AspNetUsers" ("NormalizedUserName") WHERE [NormalizedUserName] IS NOT NULL;

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20180514204732_initial', '2.0.3-rtm-10026');
Автор Тема: [Решено]различия при работе с mysql и postgresql при создании таблиц  (Прочитано 7451 раз)
soiam

Гость


Добрый день. Изначально программа была написана на Qt4 для работы с базой данных mysql. Но теперь появилась необходимость перевести ее на postgresql. Драйвер qpsql подхватился программой нормально, подключение с базой данных устанавливается. Но вот не работает создание таблиц на сервере БД из qt программы(INSERT,SELECT работает)

       remote_db.setHostName(remote_addr);
        remote_db.setPassword(pass);
        remote_db.setUserName(login);
        remote_db.setDatabaseName(«mydb»);
        remote_db.setPort(5432);
        remote_db.setConnectOptions(«connect_timeout=5;»);
        if (remote_db.open())
        {
             remote_query = new QSqlQuery(remote_db);
        //таблица типов помещений
             if (!remote_query -> exec(«CREATE TABLE LocationList (loc_number SERIAL, location VARCHAR(50));»))
             {
                   write_log(remote_query -> lastError().text());
             }
        }

При выполнении в лог выводится

ERROR:  syntax error at end of input
LINE 1: EXECUTE
                ^
QPSQL: Unable to create query.

Совсем неинформативная ошибка, в интернете по ней ничего подходящего не нашел. При создании такой таблицы через сторонни клиент БД(например, psql), она создается нормально.
В чем может быть проблема? Заранее благодарен за помощь

« Последнее редактирование: Май 29, 2013, 14:30 от soiam »
Записан
soiam

Гость


Залез на сервер postgresl в логи. вот, что он выдает

1970-01-01 05:47:27 UTC STATEMENT:  PREPARE qpsqlpstmt_4 AS CREATE TABLE LocationList (loc_number SERIAL, location VARCHAR(50));
1970-01-01 05:47:27 UTC ERROR:  syntax error at end of input at character 9
1970-01-01 05:47:27 UTC STATEMENT:  EXECUTE
1970-01-01 05:47:27 UTC ERROR:  syntax error at or near «CREATE» at character 25

DROP тоже не работает. Грустный Лог сервера

1970-01-01 05:47:27 UTC STATEMENT:  PREPARE qpsqlpstmt_3 AS drop table locationlist;
1970-01-01 05:47:27 UTC ERROR:  syntax error at end of input at character 9
1970-01-01 05:47:27 UTC STATEMENT:  EXECUTE
1970-01-01 05:47:27 UTC ERROR:  syntax error at or near «CREATE» at character 25


Записан
Serr500

Гость


А нет ли в БД функции с именем locationlist?


Записан
soiam

Гость


у меня таких разных таблиц штук 20. ни одна из ПО не создается, только из сторонних клиентов. Функции пока не использую, вся обработка на стороне клиента


Записан
soiam

Гость


Вообщем, походу я разобрался. Всё дело в драйвере qpsql для Qt4. Их баг походу.
Когда я через программу формирую «CREATE TABLE LocationList (loc_number SERIAL, location VARCHAR(50));», драйвер Qt4 автоматически добавляет вначале «PREPARE %1 AS «, и посылает на сервер. Когда я вызываю exec(), драйвер посылает на сервер «EXECUTE %1».
Так вот для всяких select,update,insert эти кэшируемые параметризированные запросы(prepared statements) вполне подходят. Но не для create,alter,drop table, так как это единичные неповторяемые statements. Поэтому prepare и не поддерживается с create,drop.
А разработчики qt4 этого не учли… Странно, что это нигде не всплыло до сих пор…

Также не поддерживается создание хранимых процедур походу, вообще обрубок какой-то

« Последнее редактирование: Май 27, 2013, 18:34 от soiam »
Записан
joker

Новичок

Offline Offline

Сообщений: 49

Просмотр профиля


Похоже, дело в том, что для многих SQL серверов есть 2 различных понятия:
-DDL (Data Definition Language — язык определения данных)
-DML (Data Manipulation Language — язык манипуляции данными)

При этом первый используется для разработки БД (сюда относятся создания/удаление таблиц/полей, права и т.п.), а второй — для работы с данными (select, insert, update, delete)
Вполне возможно что у мускула эти понятия просто слиты.

Честно говоря, я всегда проектировал БД в отдельных прогах, поэтому не знаю как из Qt но посоветую копать именно в этом направлении.

Хотя нет, еще переспрошу — а вы уверены что создание таблиц «влет» это «хороший» стиль программирования?


Записан
soiam

Гость


есть случаи, когда это необходимо. Тот же ALTER TABLE, когда программа поменялась, и нужны, допустим дополнительные столбцы. Программное обеспечение же развивается постоянно. Где-то нужно будет ввести новую таблицу для увеличения функционала. В таком случае клиент просто скачивает новую версию, которая дообновляет базу данных сервера. А если это не поддерживает программа, что тогда делать клиенту, чтобы получить дополнительный функционал ПО?


Записан
joker

Новичок

Offline Offline

Сообщений: 49

Просмотр профиля


Слушай, а ведь все нормально выполняется.
Есть подозрение что у тебя беда с синтаксисом SQL

Попробуй просто

CREATE TABLE test(id integer);


Записан
soiam

Гость


Твоя таблица тоже не создается. У меня Qt 4.8.0, 4.7.4 и postgresql 9.1

Подправил драйвер, косяк с созданием и удалением таблиц исчез. Учу драйвер использовать bind параметры новым способом

« Последнее редактирование: Май 28, 2013, 15:03 от soiam »
Записан

  Last tested: Feb 2021

Overview

This SQL error generally means that somewhere in the query, there is invalid syntax.
Some common examples:

  • Using a database-specific SQL for the wrong database (eg BigQuery supports DATE_ADD, but Redshift supports DATEADD)
  • Typo in the SQL (missing comma, misspelled word, etc)
  • Missing a sql clause (missed from, join, select, etc)
  • An object does not exist in the database or is not accessible from the current query (eg referencing orders.id when there is no orders table joined in the current query, etc)

In some circumstances, the database error message may display extra detail about where the error was raised, which can be helpful in narrowing down where to look.

Error Message

SQL ERROR: syntax error at or near

Troubleshooting

This should generally be the first step to troubleshoot any SQL syntax error in a large query: iteratively comment out blocks of SQL to narrow down where the problem is.

TIP: To make this process easier, change the group by clause to use position references
eg: group by 1,2,3,4,5 instead of group by orders.status, orders.date, to_char(...)...
as well as separate the where and having clauses onto multiple lines.

So for example, say we have the following query:

play_arrow

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, sum(cte.sales_amount), count(*) from cte
join foo on cte.date = foo.date
group by status, foo.date
order by 3 desc

We could start by running just the portion in the CTE:

play_arrow

-- WITH cte AS (
select id, status, sales_amountfrom orders
-- )
-- select status, foo.date, sum(cte.sales_amount), count(*)
-- from cte
-- join foo on cte.date = foo.date
-- group by 1, 2
-- order by 3 desc

Then strip out the aggregates and portions related to them

play_arrow

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, -- sum(cte.sales_amount), count(*)
from cte
join foo on cte.date = foo.date
-- group by 1, 2
-- order by 3 desc

Iteratively stripping out / adding back in portions of the query until you find the minimum query to trigger the error.

  • Lookup functions and syntax If the query is small enough, or if we’ve narrowed the scope enough with 1, google all the functions used in the query and verify that they exist and are being used correctly.

  • Verify all objects exist Verify that you’ve joined all tables used in the select, where, and having clause, and that those tables exist in the db. Once we’ve narrowed things down from 1, also check that each column exists in the table specified.

Понравилась статья? Поделить с друзьями:
  • Error syntax error at or near call
  • Error syncing pod skipping
  • Error synchronizing data with database
  • Error synchronizing after initial wipe timed out waiting for object
  • Error sync firefox