“Column ’x’ does not exist” error for string literal ’x’ in PostgreSQL [duplicate]

╄→гoц情女王★ 提交于 2019-12-05 02:40:25

Your text editor or word processor is using so-called smart quotes, like , not ordinary single quotes, like '. Use ordinary single quotes (actually apostrophes) ' for literals, or double quotes " for identifiers. You also have some odd commas in there which may cause syntax errors. See the PostgreSQL manual on SQL syntax, specicifically lexical structure.

Don't edit SQL (or any other source code) in a word processor. A decent text editor like Notepad++, BBEdit, vim, etc, won't mangle your SQL like this.

Corrected example:

CREATE TABLE Professoren 
(PersNr INTEGER PRIMARYKEY,
 Name VARCHAR(30) NOT NULL,
 Rang CHAR(2) CHECK (Rang in ('C2' ,'C3' ,'C4')), 
 Raum INTEGER UNIQUE);

The reason it doesn't cause an outright syntax error - and instead gives you an odd error message about the column not existing - is because PostgreSQL accepts unicode column names and considers the character a perfectly valid character for an identifier. Observe:

regress=> SELECT 'dummy text' AS won’t, 'dummy2' as ’alias’;
   won’t    | ’alias’ 
------------+---------
 dummy text | dummy2
(1 row)

Thus, if you have a column named test and you ask for the column named ’test’, PostgreSQL will correctly tell you that there is no column named ’test’. In your case you're asking for a column named ’verkehrsunfall’ when you meant to use the literal string Verkehrsunfall instead, hence the error message saying that the column ’verkehrsunfall’ does not exit.

If it were a real single quote that'd be invalid syntax. The 1st wouldn't execute in psql at all because it'd have an unclosed single quote; the 2nd would fail with something like:

regress=>  SELECT 'dummy2' as 'alias';
ERROR:  syntax error at or near "'alias'"
LINE 1: SELECT 'dummy2' as 'alias';

... because in ANSI SQL, that's trying to use a literal as an identifier. The correct syntax would be with double-quotes for the identifier or no quotes at all:

regress=> SELECT 'dummy2' as "alias", 'dummy3' AS alias;
 alias  | alias  
--------+--------
 dummy2 | dummy3
(1 row)

You also have an unwanted space in the varchar typmod; varchar( 3 0 ) is invalid:

regress=> SELECT 'x'::varchar( 3 0 );
ERROR:  syntax error at or near "0"
LINE 1: SELECT 'x'::varchar( 3 0 );

BTW, in PostgreSQL it's usually better to use a text column instead of varchar. If you want a length constraint for application or validation reasons, add a check constraint on length(colname).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!