I am trying to create a foreign key called 'user_id' for a 'transactions' table where the user_id references the 'user_accounts' table 'id' column. I keep getting an error when I execute the script that says:
SQL Error [42P01]: ERROR: relation "user_accounts" does not exist
The table clearly exists as I have been populating the user_accounts table with data that can be viewed in dbeaver. I am using Postgres and I am aware that quotes/capitalization can really make things difficult but I have executed my entire script without capitalizing or using quotes on any of the table or column names. Although, I did capitalize some of my column data types and I am wondering if that is the issue here? If so, what direction should I take to get my foreign key to work?
My script:
create table if not exists user_accounts (
id serial primary key,
first_name VARCHAR(30),
last_name VARCHAR(30),
username VARCHAR(20),
password VARCHAR(20),
deposit INT,
creditScore INT
)
create table if not exists transactions (
transaction_id serial primary key,
user_id INT references user_accounts(id) not null,
transaction_type VARCHAR(20),
amount INT
)
Related
I created this first table named 'bookstore' where Primary Key is book_name:
create table bookstore (book_name varchar primary key, author varchar, price decimal);
I am trying to create a second table named 'name' where name is primary key. I want to make this primary key- author.name as a foreign key of bookstore.author.
create table author (name varchar primary key, place varchar,
constraint fk_author_bookstore foreign key(name) references bookstore(author));
But the error is: ERROR: there is no unique constraint matching given keys for referenced table "bookstore"
SQL state: 42830
I am new to SQL, so, hoping to get some help. If you can, please write the correct code.
Thanks
Name column in author table is primary key and it's referenced as foreign key in bookstore table.
-- PostgreSQL (v11)
create table author (name varchar primary key, place varchar);
create table bookstore (book_name varchar primary key, author varchar, price decimal
, CONSTRAINT fk_author_bookstore
FOREIGN KEY(author)
REFERENCES author(name));
Please check from url https://dbfiddle.uk/?rdbms=postgres_11&fiddle=8394f796433ed8bc170c2889286b3fc2
Add foreign key after table creation
-- PostgreSQL(v11)
ALTER TABLE bookstore
ADD CONSTRAINT fk_author_bookstore FOREIGN KEY (author)
REFERENCES author (name);
Please check from url https://dbfiddle.uk/?rdbms=postgres_11&fiddle=d93cf071bfd0e3940dfd256861be813c
Im trying to make these two tables however the users and photo table both have a foreign key that refers to the other table and they come up with errors. How would I change this code so that there's no error.
create table people (
id serial,
family_names text,
given_names text,
displayed_names text,
email_address text,
primary key (id)
);
create table users (
userid integer,
website text,
date_registered date,
gender GenderValue,
birthday date,
password text,
portrait integer,
primary key (userid),
foreign key (userid) references people(id),
foreign key (portrait) references photos(photoid)
);
create table photos (
photoid serial,
title TitleValue,
date_uploaded date,
date_taken date,
description text,
technical_details text,
safety_level safetyLevel,
visibility visibilityLevel,
owns integer,
primary key (photoid),
foreign key (owns) references users(userid)
);
ER Diagram
Remove the "forward" reference from the table definition and add it as an alter table statement after all tables have been created:
alter table users add constraint fk_users_photos
foreign key (portrait) references photos(photoid);
In fact, one style of table creation is simply to create all tables with no foreign key references, and then to use alter table for all of them after the table definitions. This prevents any errors and allows circular references.
Here is a db<>fiddle. Note that your code has custom types which I changed to base types in the fiddle.
I have placed a file in my docker-entrypoint-initdb.d/ directory. Here is what is in the file:
CREATE TABLE user_test (
user_id INTEGER,
name VARCHAR(100),
email VARCHAR(128),
active_flg BOOLEAN,
type VARCHAR(20),
CONSTRAINT pk_user PRIMARY KEY (user_id)
);
The error I am getting is psql:/docker-entrypoint-initdb.d/0001-initial-database-design.sql:8: ERROR: syntax error at or near "CREATE".
What am I missing in being able to run a file? How do I change this file to work?
USER is a reserved keyword in Postgres, see the documentation. In general, you should avoid naming your tables and columns using reserved SQL keywords. If you really wanted to proceed as is, then place user into double quotes:
CREATE TABLE "user" (
user_id INTEGER,
name VARCHAR(100),
email VARCHAR(128),
active_flg BOOLEAN,
type VARCHAR(20),
CONSTRAINT pk_user PRIMARY KEY (user_id)
);
But, keep in mind that if you choose to name your table user, then you will forever have to escape it with double quotes.
How do I make both the columns sid and ccode in the table below a super key when creating the table?:
Enrolled (sid integer, ccode varchar(6))
Here's what I've tried with but obviously SQL does not allow multiple primary keys to be declared this way:
CREATE TABLE Enrolled
(
sid integer,
ccode varchar(6),
CONSTRAINT enrolled_pkey1 PRIMARY KEY (sid),
CONSTRAINT enrolled_pkey2 PRIMARY KEY (ccode)
);
I'm using pgAdmin3 - Postgres.
You need to create one primary key over both columns:
CREATE TABLE Enrolled
(
sid integer,
ccode varchar(6),
CONSTRAINT enrolled_pkey PRIMARY KEY (sid, code)
);
However, it is usually a good idea to keep a simple serial-type primary key and just use e.g. UNIQUE constraints for field or combination of fields that need to be unique.
I wanted to use timetravel function (F.39. spi, PostgreSQL 9.1 Documentation) in my application, however it doesn't seem to work properly for me. With inserting rows into table everything works just fine, I get start and stop date properly, but when I'm trying to update those rows postgres gives me error about violating of PRIMARY KEY constraint. He's trying to insert a tuple with the same primary id as previous tuple...
It's insane to remove primary key constraints from all tables in the database but it's the functionality I need. So maybe you have some expierience with timetravel?
Any sort of help will be appreciated. Thanks in advance.
DDL:
CREATE TABLE cities
(
city_id serial NOT NULL,
state_id integer,
name character varying(80) NOT NULL,
start_date abstime,
stop_date abstime,
CONSTRAINT pk_cities PRIMARY KEY (city_id ),
CONSTRAINT fk_cities_states FOREIGN KEY (state_id)
REFERENCES states (state_id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
-- Trigger: time_travel on cities
-- DROP TRIGGER time_travel ON cities;
CREATE TRIGGER time_travel
BEFORE INSERT OR UPDATE OR DELETE
ON cities
FOR EACH ROW
EXECUTE PROCEDURE timetravel('start_date', 'stop_date');
STATEMENT GIVEN:
INSERT INTO cities(
state_id, name)
VALUES (20,'Paris');
and that's ok. I get start_date and stop_date.
But by:
UPDATE cities SET name='Rome' WHERE name='Paris'
I get error- described earlier.
Schema of states
-- Table: states
-- DROP TABLE states;
CREATE TABLE states
(
state_id serial NOT NULL, -- unikatowy numer wojewodztwa
country_id integer, -- identyfikator panstwa, w ktorym znajduje sie wojewodztwo
name character varying(50), -- nazwa wojewodztwa
CONSTRAINT pk_states PRIMARY KEY (state_id ),
CONSTRAINT uq_states_state_id UNIQUE (state_id )
)
WITH (
OIDS=FALSE
);
Unfortunately,as a new user I'm not allowed to post images here.
You can see them there:
Sample data from table cities: korpusvictifrew.cba.pl/postgres_cities.png
Sample data from table states: korpusvictifrew.cba.pl/states_data.png
Time travel converts an UPDATE into an UPDATE of the old record's stop_date and an INSERT of a new one with the changed data plus an infinity stop_date. You can't have more than one record for city_id due to pk_cities. The time travel triggers do not allow you to break that requirement.
You cannot use this:
CONSTRAINT pk_cities PRIMARY KEY (city_id )
You must use this
CONSTRAINT pk_cities PRIMARY KEY (city_id, stop_date)