Weird syntax error in PSQL while creating table - postgresql

I am trying to create a table in a PSQL database with VSCode, but I receive syntax error. INT is underlined by vscode, if I delete it then TEXT and so on...
Could you please give me any idea what is the issue?
CREATE TABLE nfl_week_three (
rank INT,
team TEXT,
games INT,
points_scored INT,
total_yards INT,
offensive_plays INT,
yards_per_play DOUBLE PRECISION,
turnover_lost INT,
fumbles_lost INT,
1st_downs INT,
passes_completed INT,
passes_attempted INT,
passing_yards INT,
passing_touchdowns INT,
passing_interceptions INT,
net_yards_per_passing_attempt DOUBLE PRECISION,
passing_1st_downs INT,
rushing_attempts INT,
rushing_yards INT,
rushing_touchdowns INT,
rushing_yards_per_attempt DOUBLE PRECISION,
rushing_1st_downs INT,
penalties INT,
penalty_yards INT,
1st_down_penalties INT,
percetage_scoring_drives INT,
percentage_turnover_drives INT,
expected_points INT
);

https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS says:
SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).
This means your column name 1st_downs and others that start with a digit are a problem.
You can either change the column names, or else delimit such names in double-quotes.

You just had some extra 1's in there as typo.
CREATE TABLE nfl_week_three
(
rank INT,
team TEXT,
games INT,
points_scored INT,
total_yards INT,
offensive_plays INT,
yards_per_play DOUBLE PRECISION,
turnover_lost INT,
fumbles_lost INT,
st_downs INT,
passes_completed INT,
passes_attempted INT,
passing_yards INT,
passing_touchdowns INT,
passing_interceptions INT,
net_yards_per_passing_attempt DOUBLE PRECISION,
passing_1st_downs INT,
rushing_attempts INT,
rushing_yards INT,
rushing_touchdowns INT,
rushing_yards_per_attempt DOUBLE PRECISION,
rushing_1st_downs INT,
penalties INT,
penalty_yards INT,
st_down_penalties INT,
percetage_scoring_drives INT,
percentage_turnover_drives INT,
expected_points INT
);

Related

Naming convention for parameters in stored procedures in postgresql

Is there a naming convention for parameters for stored procedures in postgres? I wanted to distinguish my parameters from my column names to make it easier to read, so student_id (column) = s_id(parameter), period (column) = per (parameter name), assignment (column) = asgmt (parameter), ect..
CREATE PROCEDURE
insert_assignment(s_id INT, per INT, cl VARCHAR(50), ln VARCHAR(50), sp_id INT, asgmt VARCHAR(500))
LANGUAGE SQL
AS $$
INSERT INTO
assignment(sped_id, assignment)
VALUES
(sp_id, asgmt);
UPDATE assignment ss
SET student_schedule_id=
(SELECT
ss.student_schedule_id
FROM
student_schedule ss
LEFT JOIN
class_teacher ct on ct.class_teacher_id=ss.class_teacher_id
LEFT JOIN
teacher t on t.teacher_id=ct.teacher_id
LEFT JOIN
class c on c.class_id=ct.class_id
WHERE
ss.student_id=s_id AND ss.period=per
)
WHERE assignment=asgmt
$$
There is nothing established conventions but there are 2 common themes I seen. But first on either do not truncate parameter names this actually makes reading and understanding them harder; also allign them instead of just stringing them out. The most common is to preference the parameter as p_ . The other is to suffix parameter with its usage an _in or _ot Examples:
CREATE PROCEDURE
insert_assignment(p_student_id INT, p_period INT, p_cl VARCHAR(50), p_ln VARCHAR(50), p_sped_id INT, p_assignment VARCHAR(500))
LANGUAGE SQL ...
or
CREATE PROCEDURE
insert_assignment(student_id_in INT,
period_in INT,
cl_in VARCHAR(50),
ln_in VARCHAR(50),
sped_id_in INT,
assignment_in VARCHAR(500)
)
LANGUAGE SQL ...
Not sure about cl,ln as you did not use them. As for sepd if it is in common use in your organization it is fine otherwise (IMHO) it is a poor name. Make understanding your primary goal, not less typing. (and this from a very poor typist)

Cannot read CSV file with pgAdmin,

I want to read CSV file thats on my desktop named "tripdata". I wrote a code but I always get this error:
ERROR: invalid input syntax for integer: "NULL"
CONTEXT: COPY tripdata, line 4, column birth_year: "NULL"
SQL state: 22P02
I do not know whats the problem. I read at the same way other CSV files.
CREATE TABLE public."tripdata" (tripduration integer,
starttime timestamp,
stoptime timestamp,
start_station_id integer,
start_station_name varchar(100),
start_station_latitude float,
start_station_longituder float,
end_station_id integer,
end_station_name varchar(100),
end_station_latitude float,
end_station_longituder float,
bikeid integer,
usertime varchar(100),
birth_year integer,
gender varchar(100));
SELECT * FROM public."tripdata";
COPY public."tripdata" FROM 'C:\Users\Pc\Desktop\tripdata.csv' DELIMITER ',' CSV HEADER;
select * from tripdata;
I believe you will have to tell COPY what NULL is.
https://www.postgresql.org/docs/10/sql-copy.html
NULL
Specifies the string that represents a null value. The default is \N (backslash-N) in text format, and an unquoted empty string in CSV
format.
So in your case:
COPY ... NULL AS 'NULL';

Function to insert data into different tables

I have three tables in PostgreSQL:
CREATE TABLE organization (id int, name text, parent_id int);
CREATE TABLE staff (id int, name text, family text, organization_id int);
CREATE TABLE clock(id int, staff_id int, Date date, Time time);
I need a function that gets all the fields of these tables as inputs (8 on total) and then inserts these inputs into appropriate fields of the tables
Here is my code:
CREATE FUNCTION insert_into_tables(org_name character varying(50), org_PID int, person_name character varying(50),_family character varying(50), org_id int, staff_id int,_date date, _time time without time zone)
RETURNS void AS $$
BEGIN
INSERT INTO "Org".organisation("Name", "PID")
VALUES ($1, $2);
INSERT INTO "Org".staff("Name", "Family", "Organization_id")
VALUES ($3, $4, $5);
INSERT INTO "Org"."Clock"("Staff_Id", "Date", "Time")
VALUES ($6, $7, $8);
END;
$$ LANGUAGE plpgsql;
select * from insert_into_tables('SASAD',9,'mamad','Imani',2,2,1397-10-22,'08:26:47')
But no data is inserted. I get the error:
ERROR: function insert_into_tables(unknown, integer, unknown, unknown, integer, integer, integer, unknown) does not exist
LINE 17: select * from insert_into_tables('SASAD',9,'mamad','Imani',2... ^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
Where did i go wrong?
That's because the 2nd last parameter is declared as date, not int. You forgot the single quotes:
select * from insert_into_tables('SASAD',9,'mamad','Imani',2,2,'1397-10-22','08:26:47');
Without single quotes, this is interpreted as subtraction between 3 integer constants, resulting in an integer: 1397-10-22 = 1365.
Also fix your identifiers: double-quoting preserves upper-case letters, so "Name" is distinct from name etc. See:
Are PostgreSQL column names case-sensitive?

create table with serial primary key

My question is about running CREATE TABLE with a SERIAL PRIMARY KEY, but keep getting errors. Even after I correct the code based on the errors. the errors persist. Any help is appreciated.
DROP TABLE IF EXISTS nm_land_grants;
CREATE TABLE nm_land_grants (
ID SERIAL, land_grant INT,
area REAL, perimeter REAL,
grant_name VARCHAR(255),
land_grant INT, land_gra_1 INT,
survey_app DATE, grant_conf DATE
CONSTRAINT pk_nm_land_grants
PRIMARY KEY (ID)
);
The error I'm getting is as follows:
Done.
(psycopg2.ProgrammingError) syntax error at or near "("
LINE 6: PRIMARY KEY (ID)
^
[SQL: 'CREATE TABLE nm_land_grants (\n ID SERIAL, land_grant INT, area
REAL, perimeter REAL,\n grant_name VARCHAR(255), land_grant INT,
land_gra_1 INT,\n survey_app DATE, grant_conf DATE\n CONSTRAINT
pk_nm_land_grants\n PRIMARY KEY (ID)\n);']

Postgres comparison same rows,count and match from 3 defferent tables

i have 3 tables
CREATE TABLE product (
productid int,
name varchar(80),
safetystocklevel int,
reorderpoint int,
standardcost int,
listprice numeric,
productcategoryid numeric
);
CREATE TABLE salesorderdetail (
salesorderid int,
salesorderdetailid int,
orderqty int,
productid int,
unitprice numeric,
unitpricediscount numeric,
linetotal numeric
);
CREATE TABLE salesorderheader (
salesorderid int,
orderdate date,
duedate date,
shipdate date,
onlineorderflag int,
customerid int,
creditcardid int,
subtotal numeric,
taxamt numeric,
freight numeric,
totaldue numeric
);
i want to know the clients who made an order witch contains at least 3 products from different categories
i think i should do something like :
SELECT saleorderid,productid FROM salesorderdetail WHERE lag(productid)!= productid AND lead(productid)!= productid AND lag(productid)!=lead(productid))
INTERSECT
(SELECT productid,productcategoryid FROM product WHERE lag(productcategoryid)!=productcategoryid AND lead(productcategoryid)!=productcategoryid AND lead(productcategoryid)!=lag(productcategoryid))
Something like this should do it:
select distinct sh.customerid
from salesorderdetail sd
join product p on p.productid = sd.productid
join salesorderheader sh on sd.salesorderid = sh.salesorderid
group by sh.customerid, sh.salesorderid
having count(distinct p.productcategoryid) >= 3