I want to create a table in a PostgreSQL database to store user data (Account info, contact info, geographical info). I have typed out the following SQL and I am wondering is it acceptable for PostgreSQL (in terms of best practices, data types, and lengths)?
CREATE TABLE users (
userID SERIAL,
username VARCHAR(255) NOT NULL,
password VARCHAR(60) NOT NULL,
email VARCHAR(255) NOT NULL,
active VARCHAR(255) NOT NULL,
lenderAcct BOOLEAN NOT NULL DEFAULT FALSE,
resetToken VARCHAR(255) DEFAULT NULL,
resetComplete VARCHAR(3) DEFAULT 'No',
CONSTRAINT users_pk PRIMARY KEY (userID),
firstName VARCHAR(20) NOT NULL,
middleName VARCHAR(20),
lastName VARCHAR(20) NOT NULL,
primaryPhone VARCHAR(50) NOT NULL,
primaryPhoneExt VARCHAR(10),
altPhone VARCHAR(50),
altPhoneExt VARCHAR(10),
fax VARCHAR(50),
legalAddress1 VARCHAR(25) NOT NULL,
legalAddress2 VARCHAR(25),
legalCity VARCHAR(25) NOT NULL,
legalState VARCHAR(25) NOT NULL,
legalZip VARCHAR(16) NOT NULL,
legalCountry VARCHAR(25) NOT NULL,
mailAddress1 VARCHAR(25) NOT NULL,
mailAddress2 VARCHAR(25),
mailCity VARCHAR(25) NOT NULL,
mailState VARCHAR(25) NOT NULL,
mailZip VARCHAR(16) NOT NULL,
mailCountry VARCHAR(25) NOT NULL
);
The PostgreSQL side of the table looks ok. You could consider changing the varchar(x) types to text (check out this answer). The PRIMARY KEY can be introduced as userID SERIAL PRIMARY KEY, ... although this has no effect on the table structure.
Best practises cannot be commented on more without knowing your full table structure but those considerations are mostly not PostgreSQL specific anyway.
Related
Here are my tables CREATE Statements:
CREATE TABLE `User` (
`UserId` int NOT NULL AUTO_INCREMENT,
`CompanyId` int NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL,
`UserName` varchar(100) NOT NULL,
PRIMARY KEY (`UserId`),
KEY `FK_Company_User_idx` (`CompanyId`),
CONSTRAINT `FK_Company_User` FOREIGN KEY (`CompanyId`) REFERENCES `Company` (`CompanyId`)
) ENGINE=InnoDB AUTO_INCREMENT=256 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE `Notification` (
`NotificationId` int NOT NULL AUTO_INCREMENT,
`Email` varchar(100) DEFAULT NULL,
`Message` text,
`Subject` varchar(100) DEFAULT NULL,
`UserId` int NOT NULL,
PRIMARY KEY (`NotificationId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I am trying to create a FK between UserId in Notification and UserId in User but the dropdown for selecting the field is not populating.
Any help is appreciated.
These are tables before referances
CREATE TABLE olap.time (
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees (
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers (
idcustomer varchar(10) SERIAL PRIMARY KEY autoincrement,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
After creating this tables I want to create this table
CREATE TABLE olap.fact(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES time(idtime)
));
But I get error as
"ERROR: syntax error at or near "REFERENCES"
LINE 9: FOREIGN KEY (idcustomer REFERENCES olap.customers(idcustom..."
Thanks in advance
The idcustomer from olap.fact and idcustomer from olap.customers has different datatype SERIAL and Varchar(10),
I have corrected the datatypes and validated the code below
CREATE TABLE olap.time (
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees (
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers (
idcustomer varchar(10) PRIMARY KEY ,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
CREATE TABLE olap.fact(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer) REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES olap.time(idtime)
);
My question is similar to the one posted earlier in the Community. questions/62936399/error-sql-state-42703-while-trying-to-insert-data-into-my-table
In PostgreSQL, I'm trying to run CREATE Table Statement so that I can continue with inserting values. Although my CREATE statement fails so I can't get on with INSERT statement. The error message that keeps coming up ERROR: relation "eventrequest" does not exist
SQL state: 42P01
I have re-did the entire CREATE Statement twice although the error message does not change.
CREATE TABLE CUSTOMER
(CustNo VARCHAR(8) CONSTRAINT CustNoNotNull NOT NULL,
CustName VARCHAR(30) CONSTRAINT CustNameNotNull NOT NULL,
Address VARCHAR(50) CONSTRAINT AddressNotNull NOT NULL,
Internal CHAR(1) CONSTRAINT InternalNotNull NOT NULL,
Contact VARCHAR(35) CONSTRAINT ContractNotNull NOT NULL,
Phone VARCHAR(11) CONSTRAINT CPhoneNotNull NOT NULL,
City VARCHAR(30) CONSTRAINT CityNotNull NOT NULL,
State VARCHAR(2) CONSTRAINT StateNotNull NOT NULL,
Zip VARCHAR(10) CONSTRAINT ZipNotNull NOT NULL,
CONSTRAINT PK_CUSTOMER PRIMARY KEY (CustNo)
);
CREATE TABLE FACILITY
(FacNo VARCHAR(8) CONSTRAINT FacNoNotNull NOT NULL,
FacName VARCHAR(30) CONSTRAINT FacNameNotNull NOT NULL,
CONSTRAINT PK_FACILITY PRIMARY KEY (FacNo),
CONSTRAINT Unique_FacName UNIQUE(FacName)
);
CREATE TABLE LOCATION
(LocNo VARCHAR(8) CONSTRAINT LocNoNotNull NOT NULL,
FacNo VARCHAR(8),
LocName VARCHAR(30) CONSTRAINT LocNameNotNull NOT NULL,
CONSTRAINT PK_LOCATION PRIMARY KEY (LocNo),
CONSTRAINT FK_FACNO FOREIGN KEY (FacNo) REFERENCES FACILITY (FacNo)
);
CREATE TABLE EMPLOYEE
(
EmpNo CHAR(11) CONSTRAINT EmpNoNotNull NOT NULL,
EmpName VARCHAR(30) CONSTRAINT EmpNameNotNull NOT NULL,
Department VARCHAR(30) CONSTRAINT DepartmentNotNull NOT NULL,
Email VARCHAR(255) CONSTRAINT EmailNotNull NOT NULL,
Phone VARCHAR(30) CONSTRAINT PhoneNotNull NOT NULL,
CONSTRAINT PK_EMPLOYEE PRIMARY KEY (EmpNo)
);
CREATE TABLE EVENTPLAN
(
PlanNo VARCHAR(8) NOT NULL,
EventNo VARCHAR(8) NOT NULL,
workdate DATE NOT NULL,
notes VARCHAR(40),
activity VARCHAR(20) NOT NULL,
empno VARCHAR(8),
CONSTRAINT PK_PLANNO PRIMARY KEY (PlanNo),
CONSTRAINT FK_EVENTNO FOREIGN KEY (EventNo) REFERENCES EventRequest (EventNo)
);
CREATE TABLE EVENTREQUEST
(
EventNo VARCHAR(8) NOT NULL,
DateHeld DATE NOT NULL,
DateReq DATE NOT NULL,
FacNo VARCHAR(8) NOT NULL,
CustNo VARCHAR(8) NOT NULL,
DateAuth DATE,
Status VARCHAR(8) NOT NULL CHECK (Status IN ('Pending', 'Denied', 'Approved')),
EstCost DECIMAL(10, 2) NOT NULL,
EstAudience INT NOT NULL CHECK (EstAudience > 0),
BudNo VARCHAR(8),
CONSTRAINT PK_EVENTNO PRIMARY KEY (EventNo),
CONSTRAINT FK_FACILITYNOEVENTREQ FOREIGN KEY (FacNo) REFERENCES Facility (FacNo),
CONSTRAINT FK_CUSTOMERNO FOREIGN KEY (CustNo) REFERENCES Customer (CustNo)
);
CREATE TABLE EVENTPLANLINE
(
PlanNo CHAR(8) NOT NULL,
LineNo CHAR(8) NOT NULL,
LocNo CHAR(8) NOT NULL,
ResNo CHAR(8) NOT NULL,
TimeStart TIMESTAMP NOT NULL,
TimeEnd TIMESTAMP NOT NULL,
NumberFLD INTEGER NOT NULL,
CONSTRAINT PK_EVENTPLANLINE PRIMARY KEY (PlanNo, LineNo),
CONSTRAINT FK_EVENTPLAN FOREIGN KEY (PlanNo) REFERENCES EventPlan (PlanNo),
CONSTRAINT FK_LOCATION FOREIGN KEY (LocNo) REFERENCES Location (LocNo),
CONSTRAINT FK_RESOURCETBL FOREIGN KEY (ResNo) REFERENCES ResourceTbl (ResNo)
);
CREATE TABLE RESOURCETBL
(
ResNo CHAR(8) NOT NULL,
ResName VARCHAR(30) NOT NULL,
Rate DECIMAL(8, 2) NOT NULL,
CONSTRAINT PK_RESOURCETBL PRIMARY KEY (ResNo)
);
In postgresql I have a table which I need to add a new column. the original table ddl is belowing:
CREATE TABLE survey.survey_response (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
survey_id uuid NOT NULL,
survey_question_id uuid NULL,
user_id varchar(256) NULL,
device_id varchar(256) NULL,
user_country varchar(100) NULL,
client_type varchar(100) NULL,
product_version varchar(100) NULL,
answer text NULL,
response_date timestamptz NOT NULL DEFAULT now(),
survey_category varchar(100) NULL,
tags varchar(250) NULL,
tracking_id uuid NULL,
CONSTRAINT survey_response_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
) ;
Then I alter the table to add a new column:
alter table survey.survey_response add column system_tags varchar(30) ;
But after that I found my instert statement cannot make change to this new column, for all the original columns it works fine:
INSERT INTO survey.survey_response
(id, survey_id, user_id, tags, system_tags)
VALUES(uuid_generate_v4(), uuid_generate_v4(),'1123','dsfsd', 'dsfsd');
select * from survey.survey_response where user_id = '1123';
The "tags" columns contains inserted value, however, system_tags keeps null.
I tested the above scenario in my local postgreSQL 9.6, any ideas about this strange behavior? Thanks a lot
-----------------update----------
I found this survey.survey_response table has been partitioning based on month, So my inserted record will also be displayed in survey.survey_response_y2017m12. but the new system_tags column is also NULL
CREATE TABLE survey.survey_response_y2017m12 (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
survey_id uuid NOT NULL,
survey_question_id uuid NULL,
user_id varchar(256) NULL,
device_id varchar(256) NULL,
user_country varchar(100) NULL,
client_type varchar(100) NULL,
product_version varchar(100) NULL,
answer text NULL,
response_date timestamptz NOT NULL DEFAULT now(),
survey_category varchar(100) NULL,
tags varchar(250) NULL,
tracking_id uuid NULL,
system_tags varchar(30) NULL,
CONSTRAINT survey_response_y2017m12_response_date_check CHECK (((response_date >= '2017-12-01'::date) AND (response_date < '2018-01-01'::date)))
)
INHERITS (survey.survey_response)
WITH (
OIDS=FALSE
) ;
If I run the same scenario in a non-partition table then the insert works fine.
So do I need any special settings for alter table for partition table?
Old thread but you need to drop and create again the RULE to fix the issue.
Hello I have an issue with line 8 something to do with decimal.
any suggestions?
CREATE TABLE car (
cid CHAR(8) PRIMARY KEY,
reg_no VARCHAR(9) NOT NULL,
colour VARCHAR(15) NOT NULL,
maker VARCHAR(20) NOT NULL,
model VARCHAR(20) NOT NULL,
fuel_type CHAR(6) CHECK((fuel_type IN ('petrol', 'diesel'),
eng_size DECIMAL(2,1) NOT NULL,
owner CHAR(6) NOT NULL,
FOREIGN KEY (owner) REFERENCES client (client_no)
ON DELETE CASCADE
ON UPDATE CASCADE,
);
your '))' were missing at the end of 8th line, and you had an extra ',' at the end before ).
This is fixed version
CREATE TABLE car (
cid CHAR(8) PRIMARY KEY,
reg_no VARCHAR(9) NOT NULL,
colour VARCHAR(15) NOT NULL,
maker VARCHAR(20) NOT NULL,
model VARCHAR(20) NOT NULL,
fuel_type CHAR(6) CHECK((fuel_type IN ('petrol', 'diesel'))),
eng_size DECIMAL(20,15) NOT NULL,
owner CHAR(6) NOT NULL,
FOREIGN KEY (owner) REFERENCES client (client_no)
ON DELETE CASCADE
ON UPDATE CASCADE
);
The line before eng_size field declaration missing closing parenthesis )
Change it from
fuel_type CHAR(6) CHECK((fuel_type IN ('petrol', 'diesel'),
To
fuel_type CHAR(6) CHECK(fuel_type IN ('petrol', 'diesel')),
Also, remove the , from the last line
FOREIGN KEY (owner) REFERENCES client (client_no)
ON DELETE CASCADE ON UPDATE CASCADE
See a successful fiddle here
http://sqlfiddle.com/#!15/841fd