ERROR: syntax error at or near "(" when creating a new table - postgresql

I am extremely new to PostgreSQL and every time I try to create a new table, I run into the following error:
ERROR: syntax error at or near "(" LINE 1: ..." ("id_azucarusuario"
SERIAL, "id_usuario" integer(128) NOT ...
Here is the SQL for the table I am trying to define:
CREATE TABLE "public"."usuario_azucar"
( "id_azucarusuario" SERIAL,
"id_usuario" integer(128) NOT NULL,
"codigogeneral" character varying(240) NOT NULL,
"razonsocial" character(240),
"nombrecomercial" character(240),
"nit" integer(128),
"nummatricula" integer(128),
"direccionempresa" character(240),
"subdepartamento" character(240),
"subciudad" character(240),
"subdireccion" character varying(240),
"subcalle" character varying(240),
"subreferencia" character varying(240),
"subtelefono" integer(128),
"subpagweb" character(240),
"subemail" character varying(240),
"rai" character varying(240),
"descripcion_proceso_azucar" character varying(240),
"descripcion_proceso_alcohol" character varying(240),
"balance_energeticoomasic" character varying(240),
"productos_obtenidos" character varying(240),
"capacidad_azuoalco" character varying(240),
"capacidadreal_azuoalcoho" character varying(240),
PRIMARY KEY ("id_azucarusuario")
)
WITHOUT OIDS;

There is no type as integer(...), choose smallint, integer or bigint given the ranges here:
http://www.postgresql.org/docs/current/interactive/datatype-numeric.html

Do not use any reserved keywords..
You must change the table name from 'public' to something else.. as it is a reserved keyword on postgresql..
Here is a link for reserved keywords in postgresql

Related

How to automatically fill columns on a row based on the foreign key being the primary key on another table

I'm working on a sql database for QGIS. I have 8 tables: 3 three of them are the base tables and the others are relational tables. One relational table,
"tabela_is_po", has 4 fields:
indice_sequencial_po (integer and Primary Key),
tema (character varying),
subtema (character varying),
designacao (character varying)
And the base table, "tabela_objecto_area", has 7 fields:
identificador integer ,
dtcc character varying(4),
planta_po boolean,
indice_sequencial_po integer (foreign key),
tema_po character varying(254),
subtema_po character varying(254),
designacao_po character varying(254)
In "tabela_objecto area", when I fill, indice_sequencial_po integer (foreign key), I want the table to be able to automatically get the data from the relational table "tabela_is_po", based on the number that is filled in indice_sequencial_po.
I've tried the trigger function but it never worked well.
tabela_objecto_area code:
CREATE TABLE pdm2019.tabela_objecto_area
(
identificador integer NOT NULL DEFAULT nextval('pdm2019.tabela_objecto_area_identificador_seq'::regclass),
dtcc character varying(4) NOT NULL DEFAULT '0101',
planta_po boolean NOT NULL,
indice_sequencial_po integer,
tema_po character varying(254),
subtema_po character varying(254),
designacao_po character varying(254),
CONSTRAINT tabela_objecto_area_pkey PRIMARY KEY (identificador)
)
WITH (
OIDS=FALSE
);
Trigger function:
CREATE OR REPLACE FUNCTION tema_e_subtema_automatico() RETURNS TRIGGER AS $tema_e_subtema_automatico$
BEGIN
IF NEW.pdm2019.tabela_objecto_area.indice_sequencial_po IS NOT NULL THEN
INSERT INTO pdm2019.tabela_objecto_area(tema_po,subtema_po,designacao_po) SELECT tema,subtema,designacao FROM pdm2019.tabela_is_po WHERE indice_sequencial_po = NEW.pdm2019.tabela_objecto_area.indice_sequencial_po;
END IF;
END;
$tema_e_subtema_automatico$ LANGUAGE plpgsql;
CREATE TRIGGER tema_e_subtema_automatico AFTER INSERT OR UPDATE ON pdm2019.tabela_objecto_area
FOR EACH ROW EXECUTE PROCEDURE tema_e_subtema_automatico();
You would probably be better off using a view. See https://en.wikipedia.org/wiki/Relational_model for an overview, basically each item should appear only once in the database.
For data entry, it's often easier to use a framework like django (https://www.djangoproject.com/) to create the structure of your tables and input data, which you can then view in qgis.
CREATE TABLE pdm2019.tabela_objecto_area
(
identificador integer NOT NULL DEFAULT nextval('pdm2019.tabela_objecto_area_identificador_seq'::regclass),
dtcc character varying(4) NOT NULL DEFAULT '0101',
planta_po boolean NOT NULL,
indice_sequencial_po integer,
-- tema_po character varying(254), -- use a view to populate these
-- subtema_po character varying(254), -- use a view to populate these
-- designacao_po character varying(254), -- use a view to populate these
CONSTRAINT tabela_objecto_area_pkey PRIMARY KEY (identificador)
)
WITH (
OIDS=FALSE
);
CREATE VIEW v_tabela_objecto_area as (
select a.*, b.tema_po, b.subtema_po, b.designacao_po
from tabela_objecto_area a, tabela_is_po b
where a.indice_sequencial_po = b.indice_sequencial_po);

POSTGRESQL PG/PGSQL- Function with params

I'm having some issues making a function in Postgresql, I have this function:
CREATE OR REPLACE FUNCTION public.isp_ticket(_cr integer, _grupo character varying(255), _numero integer, _descripcion text, _resumen character varying(255), _fechaaper timestamp with time zone, _fechacierr timestamp with time zone, _tipo smallint, _apellidousuarioafectado character varying(255), _apellidosolicitante character varying(255), _tenant character varying(255), _metodoreportado character varying(100), _prioridad smallint, _sla character varying(255), _categoria character varying(255), _estado character varying(255), _herramienta_id integer, _asignado character varying(255), _nombresolicitante character varying(255), _nombreusuarioafectado character varying(255))
RETURNS void AS $$
BEGIN
CASE
WHEN _asignado = '' AND _close_date = '' AND _sla = ''
THEN INSERT INTO public.website_ticket(cr, grupo, numero, descripcion, resumen, fechaaper, tipo, apellidousuarioafectado, apellidosolicitante, tenant, metodoreportado, prioridad, categoria, estado, herramienta_id, nombresolicitante, nombreusuarioafectado) VALUES (_cr, _grupo, _numero, _descripcion, _resumen, _fechaaper, _tipo, _apellidousuarioafectado, _apellidosolicitante, _tenant, _metodoreportado, _prioridad, _categoria, estado, _herramienta_id, _nombresolicitante, _nombreusuarioafectado);
WHEN _asignado = '' AND _close_date = ''
THEN INSERT INTO public.website_ticket(cr, grupo, numero, descripcion, resumen, fechaaper, tipo, apellidousuarioafectado, apellidosolicitante, tenant, metodoreportado, prioridad, sla, categoria, estado, herramienta_id, nombresolicitante, nombreusuarioafectado) VALUES (_cr, _grupo, _numero, _descripcion, _resumen, _fechaaper, _tipo, _apellidousuarioafectado, _apellidosolicitante, _tenant, _metodoreportado, _prioridad, _sla, _categoria, _estado, _herramienta_id, _nombresolicitante, _nombreusuarioafectado);
WHEN new_close_date = ''
THEN INSERT INTO public.website_ticket(cr, grupo, numero, descripcion, resumen, fechaaper, tipo, apellidousuarioafectado, apellidosolicitante, tenant, metodoreportado, prioridad, sla, categoria, estado, herramienta_id, asignado,nombresolicitante, nombreusuarioafectado)
VALUES (_cr, _grupo, _numero, _descripcion, _resumen, _fechaaper, _tipo, _apellidousuarioafectado, _apellidosolicitante, _tenant, _metodoreportado, _prioridad, _sla, _categoria, _estado, _herramienta_id, _asignado, _nombresolicitante, _nombreusuarioafectado);
ELSE
UPDATE public.website_ticket SET fechacierr = _fechacierr WHERE numero = _numero;
END CASE;
END;
$$ LANGUAGE plpgsql;
and when I try to use the function doing this:
SELECT public.isp_ticket(924266,
'EUS_Zona V Region',
512294,
'Nombre: Gisselle Espinoza Contreras\nCorreo: gespinoza#bancoripley.cl
\nAnexo: 6221\nUbicación: Valparaiso\nPais: Chile\nMotivo: Usuario indica
que su computador se apagó repentinamente. Se pudo entrar a windows después
de un buen rato, pero no puede ingresar a las aplicaciones que se conecten a
red.\n\nDirección: Plaza Victoria 1646 - Piso 1 - Banco',
'Valparaiso // Computador con problemas de conexión.',
'2018-01-23 15:17:51',
'',
1,
'Espinoza Contreras',
'Espinoza Contreras',
'Ripley',
'Telephone',
3,
'',
'Ripley.Hardware.Desktop.Falla',
'Open',
1,
'',
'Gissel Rose Marie',
'Gissel Rose Marie')
I tried to CAST every value, and it didn't work either, always appear the same error:
ERROR: no existe la función public.isp_ticket(integer, character varying, integer, text, character varying, timestamp with time zone, unknown, integer, character varying, character varying, character varying, character varying, integer, unknown, character varying, character varying, integer, unknown, character varying, character varying)
LINE 1: SELECT public.isp_ticket(
^
SQL state: 42883
Character: 8
I need help how can I fix it?
Forwards thanks everyone!!!
Parameter #7, _fechacierr should be timestamp with time zone. You can not pass '', change it to null (and cast it to timestamp with time zone) if you need empty value.
And it's worth to read how PostgreSQL finds specific function to call, especially:
If any input arguments are unknown, check the type categories accepted
at those argument positions by the remaining candidates. At each
position, select the string category if any candidate accepts that
category. (This bias towards string is appropriate since an
unknown-type literal looks like a string.) Otherwise, if all the
remaining candidates accept the same type category, select that
category; otherwise fail because the correct choice cannot be deduced
without more clues. Now discard candidates that do not accept the
selected type category. Furthermore, if any candidate accepts a
preferred type in that category, discard candidates that accept
non-preferred types for that argument. Keep all candidates if none
survive these tests. If only one candidate remains, use it; else
continue to the next step.

ERROR: extra data after last expected column - COPY

When I try to import the data with delimiter | I receive the error:
ERROR: extra data after last expected column
I am able to load the data if I remove double quote or single quote from the filed which have issue in the below sample data but my requirement is I need all data without removing any.
This is my copy command:
COPY public.dimingredient FROM '/Users//Downloads/archive1/test.txt'
DELIMITER '|' NULL AS '' CSV HEADER ESCAPE AS '"' ;
My table:
public.dimingredient
(
dr_id integer NOT NULL,
dr_loadtime timestamp(6) without time zone NOT NULL,
dr_start timestamp(6) without time zone NOT NULL,
dr_end timestamp(6) without time zone NOT NULL,
dr_current boolean NOT NULL,
casnumber character varying(100) COLLATE pg_catalog."default" NOT NULL,
ingredientname character varying(300) COLLATE pg_catalog."default" NOT NULL,
matchingstrategy character varying(21) COLLATE pg_catalog."default",
percentofconfidence double precision,
disclosurestatus character varying(42) COLLATE pg_catalog."default",
issand character varying(1) COLLATE pg_catalog."default",
sandmeshsize character varying(20) COLLATE pg_catalog."default",
sandquality character varying(20) COLLATE pg_catalog."default",
isresincoated character varying(1) COLLATE pg_catalog."default",
isartificial character varying(1) COLLATE pg_catalog."default",
CONSTRAINT dimingredient_pkey PRIMARY KEY (dr_id)
)
my data:
5144|2016-07-01 13:34:25.1001891|1900-01-01 00:00:00.0000000|9999-12-31 23:59:59.9999999|True|93834|"9-octadecenamide,n,n-bis(2-hydroxyethyl)-, (9z)"|"NO CAS MATCH FOUND"||Disclosed|||||
5145|2016-07-01 13:34:25.1001891|1900-01-01 00:00:00.0000000|9999-12-31 23:59:59.9999999|True|93834|"9-octadecenamide,n,n-bis-2(hydroxy-ethyl)-,(z)""|"NO CAS MATCH FOUND"||Disclosed|||||
Omitting the empty line in your dample data, I get a different error message with 9.6, to wit:
ERROR: unterminated CSV quoted field
CONTEXT: COPY dimingredient, line 3: "5145|2016-07-01 13:34:25.1001891|1900-01-01 00:00:00.0000000|9999-12-31 23:59:59.9999999|True|93834|..."
Strangely enough, that error message has been there since CSV COPY was introduced in version 8.0, so I wonder how your data are different from the data you show above.
The error message is easily explained: There is an odd number of quotation characters (") in the second line.
Since two doubled quotes in a quoted string are interpreted as a single double quote (" is escaped as ""), the fields in the second line are:
5145
2016-07-01 13:34:25.1001891
1900-01-01 00:00:00.0000000
9999-12-31 23:59:59.9999999
True
93834
9-octadecenamide,n,n-bis-2(hydroxy-ethyl)-,(z)"|NO CAS MATCH FOUND||Disclosed|||||
... and then COPY hits the end of file while parsing a quoted string. Hence the error.
The solution is to use an even number of " characters per field.
If you need a " character in a field, either choose a different QUOTE or quote the field and double the ".

PostgreSQL COPY from CSV with delimiter "|"

please, can anyone help me to solve this problem?
I'd like to create a table in Postgres database with data from CSV file with delimiter "|", while trying to use the command COPY (or Import) I get this error:
ERROR: extra data after last expected column
CONTEXT: COPY twitter, line 2: ""Sono da Via Martignacco
http://t.co/NUC6MP0z|"<a href=""http://foursquare.com"" rel=""nofollow"">f..."
The first 2 lines of CSV:
txt|"source"|"ulang"|"coords"|"tweettime_wtz"|"country"|"id"|"userid"|"in_reply_user_id"|"in_reply_status_id"|"uname"|"ucreationdate"|"utimezone"|"followers_count"|"friends_count"|"x_coords"|"y_coords"
Sono da Via Martignacco http://t.co/NUC6MP0z|"foursquare"|"it"|"0101000020E6100000191CA9E7726F2A4026C1E1269F094740"|"2012-05-13 10:00:45+02"|112|201582743333777411|35445264|""|""|"toffo93"|"2009-04-26 11:00:03"|"Rome"|1044|198|13.21767353|46.07516943
For this data I have created in Postgres a table "Twitter"
CREATE TABLE public.twitter
(
txt character varying(255),
source character varying(255),
ulang character varying(255),
coords geometry(Point,4326),
tweettime_wtz character varying(255),
country integer,
userid integer NOT NULL,
in_reply_user_id character varying(255),
in_reply_status_id character varying(255),
uname character varying(255),
ucreationdate character varying(255),
utimezone character varying(255),
followers_count integer,
friends_count integer,
x_coords numeric,
y_coords numeric,
CONSTRAINT id PRIMARY KEY (userid)
)
WITH (
OIDS=FALSE
);
ALTER TABLE public.twitter
OWNER TO postgres;
Any ideas, guys?
The destination table contain 16 column, but your file contain have 17 column.
It seems to be the id field who is missing.
try to set you table as:
CREATE TABLE public.twitter
(
txt character varying(255),
source character varying(255),
ulang character varying(255),
coords geometry(Point,4326),
tweettime_wtz character varying(255),
country integer,
id character varying,
userid integer NOT NULL,
in_reply_user_id character varying(255),
in_reply_status_id character varying(255),
uname character varying(255),
ucreationdate character varying(255),
utimezone character varying(255),
followers_count integer,
friends_count integer,
x_coords numeric,
y_coords numeric,
CONSTRAINT twitter_pk PRIMARY KEY (userid)
)
WITH (
OIDS=FALSE
);
Change the data type of the id field as you need it.
My solution:
So the problem was in my CSV file: it has had invisible signs of quotes. I haven't seen them when I opened CSV in Excel, I saw the lines in this way:
txt|"source"|"ulang"|"coords"|"tweettime_wtz"|"country"|"id"|"userid"|"in_reply_user_id"|"in_reply_status_id"|"uname"|"ucreationdate"|"utimezone"|"followers_count"|"friends_count"|"x_coords"|"y_coords"
Sono da Via Martignacco http://t.co/NUC6MP0z|"foursquare"|"it"|"0101000020E6100000191CA9E7726F2A4026C1E1269F094740"|"2012-05-13 10:00:45+02"|112|201582743333777411|35445264|""|""|"toffo93"|"2009-04-26 11:00:03"|"Rome"|1044|198|13.21767353|46.07516943
But when I opened CSV in notepad I saw it differently:
"txt"|"source"|"ulang"|"coords"|"tweettime_wtz"|"country"|"id"|"userid"|"in_reply_user_id"|"in_reply_status_id"|"uname"|"ucreationdate"|"utimezone"|"followers_count"|"friends_count"|"x_coords"|"y_coords"
"Sono da Via Martignacco http://t.co/NUC6MP0z"|"foursquare"|"it"|"0101000020E6100000191CA9E7726F2A4026C1E1269F094740"|"2012-05-13 10:00:45+02"|112|201582743333777411|35445264|""|""|"toffo93"|"2009-04-26 11:00:03"|"Rome"|1044|198|13.21767353|46.07516943
"
So i should delete all quotes (in Notepad and saving the file as CSV), so that the text became:
txt|source|ulang|coords|tweettime_wtz|country|id|userid|in_reply_user_id|in_reply_status_id|uname|ucreationdate|utimezone|followers_count|friends_count|x_coords|y_coords
Sono da Via Martignacco http://t.co/NUC6MP0z|<a href=http://foursquare.com rel=nofollow>foursquare</a>|it|0101000020E6100000191CA9E7726F2A4026C1E1269F094740|2012-05-13 10:00:45+02|112|201582743333777411|35445264|||toffo93|2009-04-26 11:00:03|Rome|1044|198|13.21767353|46.07516943
Only after this I was able to use Import tool in pgAdmin without any problem!

PostgreSQL create table syntax

I'm more a mysql person, but I have to do a db in pg and the following CREATE TABLE keeps generating syntax errors... I just get an error: ERROR: syntax error at or near "(" and error: ERROR: syntax error at or near ")" Googling around didn't give me much help... I'm sure that I'm doing something mysql-esque and that's causing problems... (Note: I did already create the mfseq successfully...)
CREATE TABLE master_file (
mfid INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('mfseq'),
prefix VARCHAR(4),
fname VARCHAR(30) NOT NULL,
lname VARCHAR(80) NOT NULL,
MI varchar(1) NULL,
address1 VARCHAR(200) NOT NULL,
address2 VARCHAR(200),
city VARCHAR(28),
state VARCHAR(2),
zip INT(5),
zip_plus4 INT(4),
mrn VARCHAR(30),
aID INT,
iID INT,
gID VARCHAR(1),
pphone VARCHAR(10);
);
Maybe int -> integer and without size (or numeric) and delete the delimiter at pphone field.
It should not be a semi-colon here: pphone VARCHAR(10);