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»;
Пользователь заполняет форму, где вводит значения в textBox-ы.
NpgsqlCommand com = new NpgsqlCommand("INSERT INTO 'Tip' (code_tip,
name_tip) VALUES (@p1, @p2)", con);
com.Parameters.Add("code_tip", NpgsqlTypes.NpgsqlDbType.Bigint).Value =
textBox1;
com.Parameters.Add("name_tip", NpgsqlTypes.NpgsqlDbType.Char, 40).Value =
textBox2;
com.ExecuteNonQuery();
На этом моменте visual-studio выдает мне ошибку:
Npgsql.NpgsqlException: "ОШИБКА: 42601: ошибка синтаксиса (примерное положение: "'Tip'")"
Подскажите, что не так?
задан 21 сен 2018 в 11:03
INSERT INTO ‘Tip’
По синтаксису (и стандарту SQL) insert
запроса после ключевого слова into
должно идти имя таблицы. Вы указали строковой литерал. Парсер соответственно удивляется и отвечает, что вы написали непонятно что.
- в одинарных кавычках
'Tip'
— строковой литерал. - без кавычек
Tip
— имя объекта, принудительно приводимое парсером к нижнему регистру, т.е.tip
- в двойных кавычках
"Tip"
— регистрозависимое имя объекта
Если у вас таблица именно Tip
, то единственным корректным способом к ней обращаться будут двойные кавычки:
INSERT INTO "Tip" ...
ответ дан 21 сен 2018 в 11:56
МелкийМелкий
21.5k3 золотых знака27 серебряных знаков53 бронзовых знака
6
Добрый вечер. Есть выражение:
$this->insertStmt = $this->connection->getPdo()->prepare("
INSERT INTO files (
real_name,
virtual_name,
album,
size,
resolution,
duration,
comment,
path,
user
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
");
Которое вызывается как обычно:
protected function doInsert(object $object)
{
$values = [
$object->getRealName(),
$object->getVirtualName(),
$object->getAlbum(),
$object->getSize(),
$object->getResolution(),
$object->getDuration(),
$object->getComment(),
$object->getPath(),
$object->getUser(),
];
$this->insertStmt->execute($values);
}
Примерное содержание $values:
array(9) {
[0]=> string(15) "BvrK9z6UPxY.jpg"
[1]=> string(16) "1265dde1c67abc1c"
[2]=> string(23) "По умолчанию"
[3]=> int(54973)
[4]=> string(7) "720x430"
[5]=> NULL
[6]=> string(0) ""
[7]=> string(108) "files/id5cd487313a93a/По умолчанию/2019-05-10/1265dde1c67abc1c.jpg"
[8]=> string(15) "id5cd487313a93a"
}
Сообщение ошибки:
Type: PDOException
Code: 42601
Message: SQLSTATE[42601]: Syntax error: 7 ОШИБКА: ошибка синтаксиса (примерное положение: "user") LINE 11: user ^
С точки зрения синтаксиса вроде все верно, много раз перепроверил, IDE ни на что не ругается. В чем трабл, господа?
I have a table address_all
and it is inherited by several address tables. address_history
inherits from parent table history_all
and keeps current address information. I am creating new table which inherits address_all
table and copies information from address_history
to new table.
My stored procedure is like this below. I am having some error when I call it. To better explain error I am using line number.
1 CREATE OR REPLACE FUNCTION somefunc()
2 RETURNS void AS
3 $BODY$
4 DECLARE
5 year_id INTEGER;
6 month_id INTEGER;
7 week_id INTEGER;
8 addresstablename text;
9 backupdays text;
10 BEGIN
11 week_id := EXTRACT(DAY FROM TIMESTAMP 'now()');
12 month_id := EXTRACT(MONTH FROM TIMESTAMP 'now()');
13 year_id := EXTRACT(YEAR FROM TIMESTAMP 'now()');
14 addresstablename := 'address_history_' || week_id || '_' || month_id || '_' || year_id;
15 backupdays:= date_trunc('hour',CURRENT_TIMESTAMP - interval '7 days');
16 EXECUTE 'create table ' || addresstablename || '() INHERITS (address_all)';
17 EXECUTE 'insert into ' || addresstablename || ' select * from address_history where address_timestamp >= ' || backupdays || ''; --AS timestamp without time zone);
18 END;
19 $BODY$
20 LANGUAGE 'plpgsql' VOLATILE;
When I run:
select somefunc()
I get this error:
ERROR: syntax error at or near "12"
LINE 1: ...story where address_timestamp >= 2012-07-31 12:00:00-0...
^
QUERY: insert into address_history_7_8_2012 select * from address_history where address_timestamp >= 2012-07-31 12:00:00-04
CONTEXT: PL/pgSQL function "somefunc" line 14 at EXECUTE statement
********** Error **********
ERROR: syntax error at or near "12"
SQL state: 42601
Context: PL/pgSQL function "somefunc" line 14 at EXECUTE statement
asked Aug 7, 2012 at 16:24
Try this largely simplified form:
CREATE OR REPLACE FUNCTION somefunc()
RETURNS void AS
$func$
DECLARE
addresstablename text := 'address_history_' || to_char(now(), 'FMDD_MM_YYYY');
BEGIN
EXECUTE
'CREATE TABLE ' || addresstablename || '() INHERITS (address_all)';
EXECUTE
'INSERT INTO ' || addresstablename || '
SELECT *
FROM address_history
WHERE address_timestamp >= $1'
USING date_trunc('hour', now() - interval '7 days');
END
$func$ LANGUAGE plpgsql;
Major points:
-
You can assign variables in plpgsql at declaration time. Simplifies code.
-
Use
to_char()
to format your date. Much simpler. -
now()
andCURRENT_TIMESTAMP
do the same. -
Don’t quote
'now()'
, usenow()
(without quotes) if you want the current timestamp. -
Use the
USING
clause withEXECUTE
, so you don’t have to convert thetimestamp
totext
and back — possibly running into quoting issues like you did. Faster, simpler, safer. -
In
LANGUAGE plpgsql
,plpgsql
is a keyword and should not be quoted. -
You may want to check if the table already exists with
CREATE TABLE IF NOT EXISTS
, available since PostgreSQL 9.1.
answered Aug 7, 2012 at 17:05
Erwin BrandstetterErwin Brandstetter
608k145 gold badges1083 silver badges1232 bronze badges
1
Apparently you need to quote backupdays, or it is not seen as a string from where to parse a timestamp.
answered Aug 7, 2012 at 16:27
LSerniLSerni
55.7k10 gold badges65 silver badges107 bronze badges
0
You’re building SQL using string manipulation so you have to properly quote everything just like in any other language. There are a few functions that you’ll want to know about:
quote_ident
: quote an identifier such as a table name.quote_literal
: quote a string to use as a string literal.quote_nullable
: asquote_literal
but properly handles NULLs as well.
Something like this will server you better:
EXECUTE 'create table ' || quote_ident(addresstablename) || ...
EXECUTE 'insert into ' || quote_ident(addresstablename) || ... || quote_literal(backupdays) ...
The quote_ident
calls aren’t necessary in your case but they’re a good habit.
answered Aug 7, 2012 at 17:07
mu is too shortmu is too short
427k70 gold badges834 silver badges801 bronze badges
5
Skip to content
I’m trying to make use of the SUBSTRING() function to extract a substring from vm.location_path, starting at the second character and ending at the position of the ‘]’ character, minus two.
I want to extract the text between the square brackets ([]) in vm.location_path but I’m hitting a syntax error.
SELECT
'UPDATE vm SET dstore_moref = ''' || datastore_inv.moref || ''' WHERE id = ''' || vm.id || ''';'
FROM
vm
INNER JOIN vapp_vm ON vapp_vm.svm_id = vm.id
INNER JOIN vm_inv ON vm_inv.moref = vm.moref
INNER JOIN datastore_inv ON datastore_inv.vc_display_name =(
SUBSTRING(
vm.location_path,
2,
POSITION(']',
vm.location_path) - 2
)
)
WHERE
vm.dstore_moref IS NULL AND vm_inv.is_deleted IS FALSE
GROUP BY datastore_inv.moref, vm.id;
SQL Error [42601]: ERROR: syntax error at or near ","
Position: 370
Error position: line: 11 pos: 369
It’s between the comma at the end of
POSITION(']',
and
vm.location_path) - 2
What am I not seeing?
This is for vCloud Director. I am trying to get a print out of all VMs that are NULL.
>Solution :
The syntax is POSITION(search_string in main_string)
with IN
Keyowrd instead of ,
SELECT
'UPDATE vm SET dstore_moref = ''' || datastore_inv.moref || ''' WHERE id = ''' || vm.id || ''';'
FROM
vm
INNER JOIN vapp_vm ON vapp_vm.svm_id = vm.id
INNER JOIN vm_inv ON vm_inv.moref = vm.moref
INNER JOIN datastore_inv ON datastore_inv.vc_display_name =(
SUBSTRING(
vm.location_path,
2,
POSITION(']' IN vm.location_path) - 2
)
)
WHERE
vm.dstore_moref IS NULL AND vm_inv.is_deleted IS FALSE
GROUP BY datastore_inv.moref, vm.id;