Double quote in the name of table in select query of PostgreSQL - postgresql

I am running following simple select query in PostgreSQL:
SELECT * FROM "INFORMATION_SCHEMA.KEY_COLUMN_USAGE"
It gives me following error report:
ERROR: relation "INFORMATION_SCHEMA.KEY_COLUMN_USAGE" does not exist
LINE 1: SELECT * FROM "INFORMATION_SCHEMA.KEY_COLUMN_USAGE"
^
********** Error **********
ERROR: relation "INFORMATION_SCHEMA.KEY_COLUMN_USAGE" does not exist
SQL state: 42P01
Character: 15
But when I am running the following query it runs successfully:
SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
Again when I select from a table created by me the situation is reversed. Following one fails:
SELECT * FROM countryTable
while following one runs successfully.
SELECT * FROM "countryTable"
Why is it happening? What is the problem?

You probably created your table so:
CREATE TABLE "countryTable" (
id SERIAL NOT NULL,
country TEXT NOT NULL,
PRIMARY KEY(id)
);
Which create a tablespace wrapped in "", you shouldn't use double quote in general in postgres for table names or columns, try without double quotes:
CREATE TABLE countryTable (
id SERIAL NOT NULL,
country TEXT NOT NULL,
PRIMARY KEY(id)
);
An then you can use this query you already have SELECT * FROM countryTable

While my personal advice is to use legal, lower-case names exclusively and never use double-quote, it is no problem per se.
When you look at the table definition in psql (\d tbl), or at table names in the system catalog pg_class or column names in pg_attributes or any of the information schema views, you get identifiers in their correct spelling (and with all other oddities that may have been preserved by double-quoting them). You can use quote_ident() to quote such names automatically as needed - it only adds double quotes if necessary.
Postgres itself isn't foolish enough to use CaMeL case names. All objects in the information schema or in the system catalog are lower-cased (the names of the system tables and columns, not the names of user tables they carry as data).
Start at the basics, read the manual about identifiers.

Related

how to write DDL sql for create table in JPA

I want to use JPA to create tables automatically by persistence.xml setting, but i found each sql must write in a single line and there must not have a semicolon just like below:
The first situation dose not work(because the code is not in a single line manner)
create table student(
id Integer,
name varchar2(50)
)
The Second situation dose not work neither(because a semicolon added at the end of the sql sentence):
create table school(id Integer, name varchar2(50));
create table student(id Integer, name varchar2(50),school_id Integer);
The SQLs listed below are correct(which have not semicolons in each line end, and every line is a standalone sql),but create a table SQL in a single line should not be friendly to read and maintain. Is anybody know a better way to resolve this issue?
create table school(id Integer, name varchar2(50))
create table student(id Integer, name varchar2(50),school_id Integer)

Issue with basic create statements in postgreSQL

I've used the psql module to create a new database using the following syntax:
CREATE DATABASE fish
I can open the database. However, when I try to create tables or columns it gives me a syntax error for the following message.
CREATE TABLE salmon;
this is the error message:
ERROR: syntax error at or near ";"
LINE 1: CREATE TABLE species;
I've checked a lot of online postgreSQL resources and they haven't been of much help. To the best of my knowledge, I haven't messed up the syntax. Thanks.
you can use this syntax for empty table:
create table salmon();
You must create atleast one column in a table:
CREATE TABLE salmon ( column_name data_type ...........);
Postgres create table link: https://www.postgresql.org/docs/9.1/static/sql-createtable.html
You can't create an empty table - it must have at least one column. E.g.:
CREATE TABLE salmon (name VARCHAR(10));
psql is not a module. Please read https://www.postgresql.org/docs/current/static/app-psql.html
you odn't open a database - you connect to it.
Establishes a new connection to a PostgreSQL server
https://www.postgresql.org/docs/current/static/sql-createtable.html
{ column_name | ( expression ) }
Either column list (create table a (a int);) or expression (create table b as select now() time_column) is obligatory part.

Unable to use crosstab in Postgres

Postgres 9.2.1 on OSX 10.9.2.
If I run the following crosstab example query:
CREATE EXTENSION tablefunc;
CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT);
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1');
SELECT *
FROM crosstab(
'select rowid, attribute, value
from ct
where attribute = ''att2'' or attribute = ''att3''
order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text);
I get: ERROR: extension "tablefunc" already exists
But if I comment out CREATE EXTENSION
I get: ERROR: function crosstab(unknown) does not exist
How can I get out of this vicious circle? Is it a known issue?
You can change the first line into:
CREATE EXTENSION IF NOT EXISTS tablefunc;
the problem in my case was that the 'tablefunc' extension was defined on one specific schema in my DB, and not accessible to all schemas in it.
[edit: as explained above, 'not accessible to all schemas' should read 'cannot be loaded on all schemas']
I learned that:
the Extension can only be loaded into one schema - so load it into 'public'
you have to manually drop the extension from one schema before you can load it in another
you can list the loaded extensions per schema in pqsl using the command: \df *.crosstab
[edit: 4. you can access the extension either by search_path, by loading it on public schema or by explicitly specifying a schema]
There's a misconception in your answer:
and not accessible to all schemas in it.
All schemas inside the same database are accessible to all sessions in that same database, (as long as privileges are given). It's a matter of setting the search_path. Schemas work much like directories / folders in the file system.
Alternatively, you can schema-qualify the function (and even operators) to access it independently of the search_path:
SELECT *
FROM my_extension_schema.crosstab(
$$select rowid, attribute, "value"
from ct
where attribute IN ('att2', 'att3')
order by 1,2$$
,$$VALUES ('att2'), ('att3')$$
) AS ct(row_name text, category_2 text, category_3 text);
More:
How to use % operator from the extension pg_trgm?
Dubious crosstab()
Your query returned attributes 'att2' and 'att3', but the column definition list had three categories (category_1, category_2, category_3) that do not match the query.
I removed category_1 and added the second parameter to crosstab() - the "safe" version. More details here:
PostgreSQL Crosstab Query
Aside:
Don't use value as column name, even if Postgres allows it. It's a reserved word in standard SQL.

pgAdmin error - relation "[name of function/Views/Trigger Functions]" does not exist

I'm just new to pgAdmin, so I don't really know what causes these errors:
ERROR: relation "ongoingprojects" does not exist
LINE 1: SELECT * FROM ongoingProjects;
^
********** Error **********
ERROR: relation "ongoingprojects" does not exist
SQL state: 42P01
Character: 15
Even if the function/view exists in the schema. Why does it give that error? And what should I do to fix it?
Pay careful attention to the error message:
ERROR: relation "ongoingprojects" does not exist
Note that it is complaining about ongoingprojects when your SQL talks about ongoingProjects. You probably created the table with something like:
create table "ongoingProjects" ( ...
PostgreSQL folds all identifiers (table names, column names, ...) to lower case unless they are double quoted. Once you've created the table as "ongoingProjects", you'll have to double quote the name everywhere and exactly match that case:
select * from "ongoingProjects";
The usual practice with PostgreSQL is to create tables with unquoted names in lower case with word separated using underscores:
create table ongoing_projects ( ...
so that you don't have worry about quoting.
Here is the link to the relevant part of the manual
For me the issue was having a schema named differently than the database.
Two solutions:
1) Modify schema name to match db name
or
2) Prepend table in query with schema name, eg: SELECT * FROM my_schema.ongoingProjects;

Postgresql: inserting value of a column from a file

For example, there is a table named 'testtable' that has following columns: testint (integer) and testtext (varchar(30)).
What i want to do is pretty much something like that:
INSERT INTO testtable VALUES(15, CONTENT_OF_FILE('file'));
While reading postgresql documentation, all I could find is COPY TO/FROM command, but that one's applied to tables, not single columns.
So, what shall I do?
If this SQL code is executed dynamically from your programming language, use the means of that language to read the file, and execute a plain INSERT statement.
However, if this SQL code is meant to be executed via the psql command line tool, you can use the following construct:
\set content `cat file`
INSERT INTO testtable VALUES(15, :'content');
Note that this syntax is specific to psql and makes use of the cat shell command.
It is explained in detail in the PostgreSQL manual:
psql / SQL Interpolation
psql / Meta-Commands
If I understand your question correctly, you could read the single string(s) into a temp table and use that for insert:
DROP SCHEMA str CASCADE;
CREATE SCHEMA str;
SET search_path='str';
CREATE TABLE strings
( string_id INTEGER PRIMARY KEY
, the_string varchar
);
CREATE TEMP TABLE string_only
( the_string varchar
);
COPY string_only(the_string)
FROM '/tmp/string'
;
INSERT INTO strings(string_id,the_string)
SELECT 5, t.the_string
FROM string_only t
;
SELECT * FROM strings;
Result:
NOTICE: drop cascades to table str.strings
DROP SCHEMA
CREATE SCHEMA
SET
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "strings_pkey" for table "strings"
CREATE TABLE
CREATE TABLE
COPY 1
INSERT 0 1
string_id | the_string
-----------+---------------------
5 | this is the content
(1 row)
Please note that the file is "seen" by the server as the server sees the filesystem. The "current directory" from that point of view is probably $PG_DATA, but you should assume nothing, and specify the complete pathname, which should be reacheable and readable by the server. That is why I used '/tmp', which is unsafe (but an excellent rendez-vous point ;-)