I’m trying to add a column named order to my table. I realize that order is a reserved word in SQL. So, how do I do it?
My command:
alter table mytable add column order integer;
I’ve also tried:
alter table mytable add column 'order' integer;
PostgreSQL 9.1.
- sql
- postgresql
- quoted-identifier
asked Apr 15, 2014 at 19:08
ed_is_my_nameed_is_my_name
6013 gold badges9 silver badges24 bronze badges
3
-
Never use reserved words as identifiers. Only use legal, lower-case names in Postgres and live happily ever after (without the need for double-quoting).
Apr 15, 2014 at 19:45
-
May I suggest «display_order» or «ordinality» as the column name?
Apr 15, 2014 at 19:50
4 Answers
Use this:
alter table mytable add column "order" integer;
But, you might want to consider using a non-reserved name instead, like sort_order
or something similar that reflects what the column is used for (and isn’t a reserved word).
answered Apr 15, 2014 at 19:12
jpwjpw
44.4k6 gold badges66 silver badges86 bronze badges
3
-
Thanks. This one worked for me. StackOverflow wants me to wait for 9 minutes before I can resolve this.
Apr 15, 2014 at 19:15
-
Huh, just realized that it is probably a bad idea to name columns after reserved words…maybe I’ll rethink this.
Apr 15, 2014 at 19:16
-
@user1344643 Indeed it is a bad practice to use reserved keywords — just don’t do it and you’ll save yourself a lot of headache at some point
Apr 15, 2014 at 19:17
I think you don’t need «column». Plus «order» is a keyword in SQL, so you should use a different name for your column. Follow this syntax:
ALTER TABLE table_name ADD column_name datatype
Source: W3Schools
answered Apr 15, 2014 at 19:14
DerStrom8DerStrom8
1,3112 gold badges23 silver badges45 bronze badges
You are using order which is a reserved keyword you should consider renaming that to something like orders. And the problem should go away.
answered Sep 10, 2021 at 7:06
ALTER TABLE table_name
ADD COLUMN "order" integer
answered Apr 15, 2014 at 19:13
0
I’m trying to add a column named order to my table. I realize that order is a reserved word in SQL. So, how do I do it?
My command:
alter table mytable add column order integer;
I’ve also tried:
alter table mytable add column 'order' integer;
PostgreSQL 9.1.
- sql
- postgresql
- quoted-identifier
asked Apr 15, 2014 at 19:08
ed_is_my_nameed_is_my_name
6013 gold badges9 silver badges24 bronze badges
3
-
Never use reserved words as identifiers. Only use legal, lower-case names in Postgres and live happily ever after (without the need for double-quoting).
Apr 15, 2014 at 19:45
-
May I suggest «display_order» or «ordinality» as the column name?
Apr 15, 2014 at 19:50
4 Answers
Use this:
alter table mytable add column "order" integer;
But, you might want to consider using a non-reserved name instead, like sort_order
or something similar that reflects what the column is used for (and isn’t a reserved word).
answered Apr 15, 2014 at 19:12
jpwjpw
44.4k6 gold badges66 silver badges86 bronze badges
3
-
Thanks. This one worked for me. StackOverflow wants me to wait for 9 minutes before I can resolve this.
Apr 15, 2014 at 19:15
-
Huh, just realized that it is probably a bad idea to name columns after reserved words…maybe I’ll rethink this.
Apr 15, 2014 at 19:16
-
@user1344643 Indeed it is a bad practice to use reserved keywords — just don’t do it and you’ll save yourself a lot of headache at some point
Apr 15, 2014 at 19:17
I think you don’t need «column». Plus «order» is a keyword in SQL, so you should use a different name for your column. Follow this syntax:
ALTER TABLE table_name ADD column_name datatype
Source: W3Schools
answered Apr 15, 2014 at 19:14
DerStrom8DerStrom8
1,3112 gold badges23 silver badges45 bronze badges
You are using order which is a reserved keyword you should consider renaming that to something like orders. And the problem should go away.
answered Sep 10, 2021 at 7:06
ALTER TABLE table_name
ADD COLUMN "order" integer
answered Apr 15, 2014 at 19:13
0
Answer by Anais Small
Bad habits to kick : using old-style JOINs — that old-style comma-separated list of tables style was replaced with the proper ANSI JOIN syntax in the ANSI-92 SQL Standard (25 years ago) and its use is discouraged
– marc_s
Apr 4 ’17 at 16:18
,You are using a comma in the FROM clause instead of proper, explicit JOIN syntax.,
Is salesman the natural term to use about a male appliance store employee who walks around trying to help customers?
,Connect and share knowledge within a single location that is structured and easy to search.
You have more than one issue with the query. I would write this as:
SELECT customerid, numseats, firstname, surname, totalcost
FROM leadcutomer l JOIN
flightbooking b
ON ?? = ??
ORDER BY totalcost DESC;
Answer by Jessie Mullen
I’m trying to add a column named order to my table. I realize that order is a reserved word in SQL. So, how do I do it?
My command:,If you add any files,it will delete all existing files related to this answer-(only this answer),But, you might want to consider using a non-reserved name instead, like sort_order or something similar that reflects what the column is used for (and isn’t a reserved word).,I think you don’t need «column». Plus «order» is a keyword in SQL, so you should use a different name for your column. Follow this syntax:
I’m trying to add a column named order to my table. I realize that order is a reserved word in SQL. So, how do I do it?
My command:
alter table mytable add column order integer;
I’ve also tried:
alter table mytable add column 'order' integer;
Answer by Clark Horne
I am using you for bulk insert operation but I updated the other day and now I started getting the error below.,Also having the same issue, tried logging generated query, but I didn’t understand what can be wrong with it, I’ll try to find it in the logs and paste it later.,Don’t hesitate to contact us for any questions, issues or feedback!,Thank you for the code, we will try it and hope that it will reproduce the issue.
My code
DapperPlusManager.Entity<TEntity>().Table(typeof(TEntity).Name).Identity("Id").BatchTimeout(12000).BatchSize(50000); using (var connection = new NpgsqlConnection(_connectionString)) { connection.BulkInsert(entityList); }
Error Message : ERROR SqlState: 42601 MessageText: syntax error at or near «ORDER» Position: 510 File: scan.lsd Line: 1150 Routine: scanner_yyerror}
DapperPlusManager.Entity<TEntity>().Table(typeof(TEntity).Name).Identity("Id").BatchTimeout(12000).BatchSize(50000); using (var connection = new NpgsqlConnection(_connectionString)) { connection.BulkInsert(entityList); }
Answer by Paxton Grant
Recent versions of Postgres (since late 2010) have the string_agg(expression, delimiter) function which will do exactly what the question asked for, even letting you specify the delimiter string:,PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression) which concatenates the values into an array. Then array_to_string() can be used to give the desired result:,Prior to 9.0, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (suggested by Vajda Gabo in this mailing list post, among many others) is to use the built-in textcat function (which lies behind the || operator):,In case anyone comes across this looking for a compatibilty shim for pre-9.0 databases, it is possible to implement everything in string_agg except the ORDER BY clause.
Recent versions of Postgres (since late 2010) have the string_agg(expression, delimiter)
function which will do exactly what the question asked for, even letting you specify the delimiter string:
SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;
Postgres 9.0 also added the ability to specify an ORDER BY
clause in any aggregate expression; otherwise, the order is undefined. So you can now write:
SELECT company_id, string_agg(employee, ', ' ORDER BY employee)
FROM mytable
GROUP BY company_id;
Or indeed:
SELECT string_agg(actor_name, ', ' ORDER BY first_appearance)
PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression)
which concatenates the values into an array. Then array_to_string()
can be used to give the desired result:
SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;
So with the below definition this should work the same as in a 9.x Postgres DB:
SELECT string_agg(name, '; ') AS semi_colon_separated_names FROM things;
But this will be a syntax error:
SELECT string_agg(name, '; ' ORDER BY name) AS semi_colon_separated_names FROM things;
--> ERROR: syntax error at or near "ORDER"
Tested on PostgreSQL 8.3.
CREATE FUNCTION string_agg_transfn(text, text, text)
RETURNS text AS
$$
BEGIN
IF $1 IS NULL THEN
RETURN $2;
ELSE
RETURN $1 || $3 || $2;
END IF;
END;
$$
LANGUAGE plpgsql IMMUTABLE
COST 1;
CREATE AGGREGATE string_agg(text, text) (
SFUNC=string_agg_transfn,
STYPE=text
);
Prior to 9.0, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (suggested by Vajda Gabo in this mailing list post, among many others) is to use the built-in textcat
function (which lies behind the ||
operator):
CREATE AGGREGATE textcat_all(
basetype = text,
sfunc = textcat,
stype = text,
initcond = ''
);
This simply glues all the strings together, with no separator. In order to get a «, » inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the «textcat» above. Here is one I put together and tested on 8.3.12:
CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
This version will output a comma even if the value in the row is null or empty, so you get output like this:
a, b, c, , e, , g
If you would prefer to remove extra commas to output this:
a, b, c, e, g
Then add an ELSIF
check to the function like this:
CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSIF instr IS NULL OR instr = '' THEN
RETURN acc;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
How about using Postgres built-in array functions? At least on 8.4 this works out of the box:
SELECT company_id, array_to_string(array_agg(employee), ',')
FROM mytable
GROUP BY company_id;
As from PostgreSQL 9.0 you can use the aggregate function called string_agg. Your new SQL should look something like this:
SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;
Содержание
- PostgreSQL — SQL state: 42601 syntax error
- 1 Answer 1
- PostgreSQL error 42601- How we fix it
- What causes error 42601 in PostgreSQL?
- How we fix the error?
- Conclusion
- PREVENT YOUR SERVER FROM CRASHING!
- 10 Comments
- SQL state: 42601 syntax error at or near «11»
- 3 Answers 3
- Major points:
- Postgres: Error [42601] Error: Syntax error at or near «$2». Error while executing the Query
- 2 Answers 2
- Состояние SQL: синтаксическая ошибка 42601 на уровне или около «11»
- 3 ответы
- Основные моменты:
PostgreSQL — SQL state: 42601 syntax error
I would like to know how to use a dynamic query inside a function. I’ve tried lots of ways, however, when I try to compile my function a message SQL 42601 is displayed.
The code that I use:
Error message I receive:
What is wrong? How can I solve this problem?
1 Answer 1
Your function would work like this:
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count() returns bigint , but you had rowcount defined as integer , so you need an explicit cast ::int to make this work.
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish — though I wouldn’t even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It’s impossible to make this secure.
Craig (a sworn enemy of SQL injection) might get a light stroke when he sees what you forged from his answer to your preceding question. 🙂
The query itself seems rather odd, btw. The two SELECT terms might be merged into one. But that’s beside the point here.
Источник
PostgreSQL error 42601- How we fix it
by Sijin George | Sep 12, 2019
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,
But, this ended up in PostgreSQL error 42601. And he got the following error message,
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,
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.
SELECT * FROM long_term_prediction_anomaly WHERE + “‘Timestamp’” + ‘”BETWEEN ‘” +
2019-12-05 09:10:00+ ‘”AND’” + 2019-12-06 09:10:00 + “‘;”)
Hello Joe,
Do you still get PostgreSQL errors? If you need help, we’ll be happy to talk to you on chat (click on the icon at right-bottom).
У меня ошибка drop table exists “companiya”;
CREATE TABLE “companiya” (
“compania_id” int4 NOT NULL,
“fio vladelca” text NOT NULL,
“name” text NOT NULL,
“id_operator” int4 NOT NULL,
“id_uslugi” int4 NOT NULL,
“id_reklama” int4 NOT NULL,
“id_tex-specialist” int4 NOT NULL,
“id_filial” int4 NOT NULL,
CONSTRAINT “_copy_8” PRIMARY KEY (“compania_id”)
);
CREATE TABLE “filial” (
“id_filial” int4 NOT NULL,
“street” text NOT NULL,
“house” int4 NOT NULL,
“city” text NOT NULL,
CONSTRAINT “_copy_5” PRIMARY KEY (“id_filial”)
);
CREATE TABLE “login” (
“id_name” int4 NOT NULL,
“name” char(20) NOT NULL,
“pass” char(20) NOT NULL,
PRIMARY KEY (“id_name”)
);
CREATE TABLE “operator” (
“id_operator” int4 NOT NULL,
“obrabotka obrasheniya” int4 NOT NULL,
“konsultirovanie” text NOT NULL,
“grafick work” date NOT NULL,
CONSTRAINT “_copy_2” PRIMARY KEY (“id_operator”)
);
CREATE TABLE “polsovateli” (
“id_user” int4 NOT NULL,
“id_companiya” int4 NOT NULL,
“id_obrasheniya” int4 NOT NULL,
“id_oshibka” int4 NOT NULL,
CONSTRAINT “_copy_6” PRIMARY KEY (“id_user”)
);
CREATE TABLE “reklama” (
“id_reklama” int4 NOT NULL,
“tele-marketing” text NOT NULL,
“soc-seti” text NOT NULL,
“mobile” int4 NOT NULL,
CONSTRAINT “_copy_3” PRIMARY KEY (“id_reklama”)
);
CREATE TABLE “tex-specialist” (
“id_tex-specialist” int4 NOT NULL,
“grafik” date NOT NULL,
“zarplata” int4 NOT NULL,
“ispravlenie oshibok” int4 NOT NULL,
CONSTRAINT “_copy_7” PRIMARY KEY (“id_tex-specialist”)
);
CREATE TABLE “uslugi” (
“id_uslugi” int4 NOT NULL,
“vostanavlenia parola” int4 NOT NULL,
“poterya acaunta” int4 NOT NULL,
CONSTRAINT “_copy_4” PRIMARY KEY (“id_uslugi”)
);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_operator_1” FOREIGN KEY (“id_operator”) REFERENCES “operator” (“id_operator”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_uslugi_1” FOREIGN KEY (“id_uslugi”) REFERENCES “uslugi” (“id_uslugi”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_filial_1” FOREIGN KEY (“id_filial”) REFERENCES “filial” (“id_filial”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_reklama_1” FOREIGN KEY (“id_reklama”) REFERENCES “reklama” (“id_reklama”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_tex-specialist_1” FOREIGN KEY (“id_tex-specialist”) REFERENCES “tex-specialist” (“id_tex-specialist”);
ALTER TABLE “polsovateli” ADD CONSTRAINT “fk_polsovateli_companiya_1” FOREIGN KEY (“id_companiya”) REFERENCES “companiya” (“compania_id”);
ERROR: ОШИБКА: ошибка синтаксиса (примерное положение: “”companiya””)
LINE 1: drop table exists “companiya”;
^
Источник
SQL state: 42601 syntax error at or near «11»
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.
I get this error:
3 Answers 3
Try this largely simplified form:
Major points:
You can assign variables in plpgsql at declaration time. Simplifies code.
Use to_char() to format your date. Much simpler.
now() and CURRENT_TIMESTAMP do the same.
Don’t quote ‘now()’ , use now() (without quotes) if you want the current timestamp.
Use the USING clause with EXECUTE , so you don’t have to convert the timestamp to text 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.
Apparently you need to quote backupdays, or it is not seen as a string from where to parse a timestamp.
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 : as quote_literal but properly handles NULLs as well.
Something like this will server you better:
The quote_ident calls aren’t necessary in your case but they’re a good habit.
Источник
Postgres: Error [42601] Error: Syntax error at or near «$2». Error while executing the Query
In the above query, In the where clause, (the first line: (messages. TIME > TIMESTAMP ? — ’30 day’::INTERVAL) AND ) when parameter is typecasted (i.e when I put TIMESTAMP before ?) I get the following error
Which is not true for the text data in the second line (messages. TIME ? ::TIMESTAMP — ’30 day’::INTERVAL) AND ) ( i.e I put the TIMESTAMP after ? ) Can anybody throw some light on what is happening? Thanks!!
Note: PostGresVersion — 9.6 OdBC driver — 32 bit driver (located at C:Program Files (x86)psqlODBC905binpsqlodbc30a.dll.) Same is true with Postgres 8.4 as well.
2 Answers 2
A constant of an arbitrary type can be entered using any one of the following notations:
The string constant’s text is passed to the input conversion routine for the type called type. The result is a constant of the indicated type.
The :: , CAST() , and function-call syntaxes can also be used to specify run-time type conversions of arbitrary expressions, as discussed in Section 4.2.9. To avoid syntactic ambiguity, the type ‘string‘ syntax can only be used to specify the type of a simple literal constant.
So you can use this syntax only with a string literal and not with a parameter as you are trying to do.
Источник
Состояние SQL: синтаксическая ошибка 42601 на уровне или около «11»
У меня есть таблица address_all и наследуется несколькими адресными таблицами. address_history наследуется от родительской таблицы history_all и сохраняет информацию о текущем адресе. Я создаю новую таблицу, которая наследует address_all таблицы и копирует информацию из address_history к новой таблице.
Моя хранимая процедура выглядит следующим образом. У меня какая-то ошибка при вызове. Чтобы лучше объяснить ошибку, я использую номер строки.
Я получаю эту ошибку:
3 ответы
Попробуйте эту в значительной степени упрощенную форму:
Основные моменты:
Вы можете назначать переменные в plpgsql во время объявления. Упрощает код.
Используйте to_char() для форматирования даты. Гораздо проще.
now() и CURRENT_TIMESTAMP сделать то же самое.
Не цитировать ‘now()’ , Используйте now() (без кавычек), если вам нужна текущая метка времени.
Использовать USING пункт с EXECUTE , так что вам не нужно конвертировать timestamp в text и обратно — возможно наткнувшись квотирование вопросы, как вы сделали. Быстрее, проще, безопаснее.
In LANGUAGE plpgsql , plpgsql является ключевым словом и не должен заключаться в кавычки.
Вы можете проверить, существует ли уже таблица с CREATE TABLE IF NOT EXISTS , доступный начиная с PostgreSQL 9.1.
Источник
Содержание
- PostgreSQL error 42601- How we fix it
- What causes error 42601 in PostgreSQL?
- How we fix the error?
- Conclusion
- Related posts:
- PREVENT YOUR SERVER FROM CRASHING!
- 10 Comments
- Приложение A. Коды ошибок PostgreSQL
PostgreSQL error 42601- How we fix it
by Sijin George | Sep 12, 2019
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,
But, this ended up in PostgreSQL error 42601. And he got the following error message,
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,
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.
SELECT * FROM long_term_prediction_anomaly WHERE + “‘Timestamp’” + ‘”BETWEEN ‘” +
2019-12-05 09:10:00+ ‘”AND’” + 2019-12-06 09:10:00 + “‘;”)
Hello Joe,
Do you still get PostgreSQL errors? If you need help, we’ll be happy to talk to you on chat (click on the icon at right-bottom).
У меня ошибка drop table exists “companiya”;
CREATE TABLE “companiya” (
“compania_id” int4 NOT NULL,
“fio vladelca” text NOT NULL,
“name” text NOT NULL,
“id_operator” int4 NOT NULL,
“id_uslugi” int4 NOT NULL,
“id_reklama” int4 NOT NULL,
“id_tex-specialist” int4 NOT NULL,
“id_filial” int4 NOT NULL,
CONSTRAINT “_copy_8” PRIMARY KEY (“compania_id”)
);
CREATE TABLE “filial” (
“id_filial” int4 NOT NULL,
“street” text NOT NULL,
“house” int4 NOT NULL,
“city” text NOT NULL,
CONSTRAINT “_copy_5” PRIMARY KEY (“id_filial”)
);
CREATE TABLE “login” (
“id_name” int4 NOT NULL,
“name” char(20) NOT NULL,
“pass” char(20) NOT NULL,
PRIMARY KEY (“id_name”)
);
CREATE TABLE “operator” (
“id_operator” int4 NOT NULL,
“obrabotka obrasheniya” int4 NOT NULL,
“konsultirovanie” text NOT NULL,
“grafick work” date NOT NULL,
CONSTRAINT “_copy_2” PRIMARY KEY (“id_operator”)
);
CREATE TABLE “polsovateli” (
“id_user” int4 NOT NULL,
“id_companiya” int4 NOT NULL,
“id_obrasheniya” int4 NOT NULL,
“id_oshibka” int4 NOT NULL,
CONSTRAINT “_copy_6” PRIMARY KEY (“id_user”)
);
CREATE TABLE “reklama” (
“id_reklama” int4 NOT NULL,
“tele-marketing” text NOT NULL,
“soc-seti” text NOT NULL,
“mobile” int4 NOT NULL,
CONSTRAINT “_copy_3” PRIMARY KEY (“id_reklama”)
);
CREATE TABLE “tex-specialist” (
“id_tex-specialist” int4 NOT NULL,
“grafik” date NOT NULL,
“zarplata” int4 NOT NULL,
“ispravlenie oshibok” int4 NOT NULL,
CONSTRAINT “_copy_7” PRIMARY KEY (“id_tex-specialist”)
);
CREATE TABLE “uslugi” (
“id_uslugi” int4 NOT NULL,
“vostanavlenia parola” int4 NOT NULL,
“poterya acaunta” int4 NOT NULL,
CONSTRAINT “_copy_4” PRIMARY KEY (“id_uslugi”)
);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_operator_1” FOREIGN KEY (“id_operator”) REFERENCES “operator” (“id_operator”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_uslugi_1” FOREIGN KEY (“id_uslugi”) REFERENCES “uslugi” (“id_uslugi”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_filial_1” FOREIGN KEY (“id_filial”) REFERENCES “filial” (“id_filial”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_reklama_1” FOREIGN KEY (“id_reklama”) REFERENCES “reklama” (“id_reklama”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_tex-specialist_1” FOREIGN KEY (“id_tex-specialist”) REFERENCES “tex-specialist” (“id_tex-specialist”);
ALTER TABLE “polsovateli” ADD CONSTRAINT “fk_polsovateli_companiya_1” FOREIGN KEY (“id_companiya”) REFERENCES “companiya” (“compania_id”);
ERROR: ОШИБКА: ошибка синтаксиса (примерное положение: “”companiya””)
LINE 1: drop table exists “companiya”;
^
Источник
Приложение A. Коды ошибок PostgreSQL
Всем сообщениям, которые выдаёт сервер PostgreSQL , назначены пятисимвольные коды ошибок, соответствующие кодам «SQLSTATE» , описанным в стандарте SQL. Приложения, которые должны знать, какое условие ошибки имело место, обычно проверяют код ошибки и только потом обращаются к текстовому сообщению об ошибке. Коды ошибок, скорее всего, не изменятся от выпуска к выпуску PostgreSQL , и они не меняются при локализации как сообщения об ошибках. Заметьте, что отдельные, но не все коды ошибок, которые выдаёт PostgreSQL , определены стандартом SQL; некоторые дополнительные коды ошибок для условий, не описанных стандартом, были добавлены независимо или позаимствованы из других баз данных.
Согласно стандарту, первые два символа кода ошибки обозначают класс ошибок, а последние три символа обозначают определённое условие в этом классе. Таким образом, приложение, не знающее значение определённого кода ошибки, всё же может понять, что делать, по классу ошибки.
В Таблице A-1 перечислены все коды ошибок, определённые в PostgreSQL 9.4.1. (Некоторые коды в настоящее время не используются, хотя они определены в стандарте SQL.) Также показаны классы ошибок. Для каждого класса ошибок имеется «стандартный» код ошибки с последними тремя символами 000. Этот код выдаётся только для таких условий ошибок, которые относятся к определённому классу, но не имеют более определённого кода.
Символ, указанный в колонке «Имя условия» , определяет условие в PL/pgSQL . Имена условий могут записываться в верхнем или нижнем регистре. (Заметьте, что PL/pgSQL , в отличие от ошибок, не распознаёт предупреждения; то есть классы 00, 01 и 02.)
Для некоторых типов ошибок сервер сообщает имя объекта базы данных (таблица, колонка таблицы, тип данных или ограничение), связанного с ошибкой; например, имя уникального ограничения, вызвавшего ошибку unique_violation. Такие имена передаются в отдельных полях сообщения об ошибке, чтобы приложениям не пришлось извлекать его из возможно локализованного текста ошибки для человека. На момент выхода PostgreSQL 9.3 полностью охватывались только ошибки класса SQLSTATE 23 (нарушения ограничений целостности), но в будущем должны быть охвачены и другие классы.
Источник
Please help me in understanding the below
Why is
(select top 1 * from dbo.module order by [order])
throwing an error?
When
select top 1 * from dbo.module
and
select top 1 * from dbo.module order by [order]
are not?
asked Sep 20, 2017 at 6:40
Naga SandeepNaga Sandeep
1,4212 gold badges13 silver badges26 bronze badges
3
Because SQL server execute statements, and the statements have the exact syntax specified for them.
The SELECT statement must start with SELECT keyword.
If the statement starts with bracket, it is subquery, and you cannot use ‘Order by’ in it.
answered Sep 20, 2017 at 6:44
2
Having brackets around the whole statement is not an ok syntax/statment. This works:
(SELECT top 1 * FROM dbo.module) ORDER BY [order]
answered Sep 20, 2017 at 6:43
SASSAS
3,9452 gold badges28 silver badges48 bronze badges