How to add composite primary key to table - sql

create table d(id numeric(1), code varchar(2))
After I create the above table how can I add a composite primary key on both fields and also a foreign key?

In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);

alter table d add constraint pkc_Name primary key (id, code)
should do it. There's lots of options to a basic primary key/index depending on what DB your working with.

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:
This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.
CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)
If you don't have a table that we can reference, add one like this so that the example will work:
CREATE TABLE Codes (
Code [varchar](2) PRIMARY KEY
)
NOTE: you must have a table to reference before creating the foreign key.

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

Related

Sql creating table consisting of keys from other tables

this is probably a simple question but I am quite new to SQL and databases, so I have been following this site: https://www.postgresqltutorial.com/postgresql-foreign-key/ to try and create a table that consist of primary keys from other tables.
Here I have the structure of the database in an excel overview. With colors showing the relations. i am having problems with the One-To-Many tables. As I get the same error every time "ERROR: column "id" referenced in foreign key constraint does not exist
SQL state: 42703".
The SQL query:
DROP TABLE IF EXISTS ingredient_to_unit_relations;
DROP TABLE IF EXISTS ingrediens;
CREATE TABLE ingrediens (
id serial,
name_of_ingredient varchar(255),
price_per_unit int,
PRIMARY KEY (id)
);
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY,
PRIMARY KEY (ingredient_relation_id),
constraint Fk_ingredient_id
FOREIGN KEY (id)
REFERENCES ingrediens (id)
);
You need to define the column in order to declare it as a foreign key:
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY,
ingredient_id int,
PRIMARY KEY (ingredient_relation_id),
constraint Fk_ingredient_id FOREIGN KEY (ingredient_id) REFERENCES ingrediens (id)
);
I might recommend some somewhat different naming conventions (I changed the name id in the table above):
CREATE TABLE ingredients (
ingredient_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name varchar(255),
price_per_unit int
);
CREATE TABLE ingredient_to_unit_relations (
ingredient_relation_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ingredient_id int,
CONSTRAINT Fk_ingredient_id FOREIGN KEY (ingredient_id) REFERENCES ingredients (ingredient_id)
);
Notes:
I am a fan of naming primary keys after the table they are in. That way, foreign keys and primary keys usually have the same name (and you can use using if you choose).
Avoid SERIAL. GENERATED ALWAYS AS IDENTITY is now recommended.
You can inline primary key constraints (as well as other constraints).
There is not generally a need to repeat the table name in a column (other than the primary key). So, name instead of name_of_ingredient.
Using int for a monetary column is suspicious. It doesn't allow smaller units. That might work for some currencies but in general I would expect a numeric/decimal type.

Cannot find primary key column in table

I added a constraint primary key to my table and the query ran successfully. The dilemma I am facing is I cannot locate the primary key column in my table.
ALTER TABLE salesdata
ADD CONSTRAINT pk_salesdata PRIMARY KEY( "Address_of_New_Home","Sq_Ft","Build_Spec", "Realtor_Sale","Can","Actual_Sale_Date")
When I do:
select * from salesdata
It shows all the columns from before and no primary key column (pk_salesdata).
And even more baffling is when:
select pk_salesdata from salesdata
Database shows:
ERROR: column "pk_salesdata" does not exist
I want to add primary key column to the table. I humbly request assistance of databasers.
You create PRIMARY KEY, but...
you create composed primary key from columns "Address_of_New_Home", "Sq_Ft", "Build_Spec", "Realtor_Sale", "Can", "Actual_Sale_Date" - it is not good idea
your primary key have an alias name pk_salesdata, but it's only constraint name
you didn't create new column
If you would like new synthetic primary key column you have to use command:
ALTER TABLE salesdata ADD COLUMN mynewautoincrementid SERIAL PRIMARY KEY;
Primary Kay it's constraint in table when you add a primary key to any column you can select column name to show data
It looks like you've wrapped the columns you want to include in your primary keys in double quotes. That's not how this command works. Drop the quotes re-run the command and see what happens.
ALTER TABLE salesdata
ADD CONSTRAINT pk_salesdata PRIMARY KEY( Address_of_New_Home,Sq_Ft,Build_Spec, Realtor_Sale,Can,Actual_Sale_Date)
It might be easier to add a primary index through the SQL GUI.
Here's the MS documentation page for creating a primary key.
https://msdn.microsoft.com/en-us/library/ms189039.aspx
Note: Since your adding a primary key don't expect it to be available as a column.

Is there any way to make the following sql query work?

I am trying to create two tables using the following SQL:
create table student(sid char(20) primary key,name char(20),age int,hours char(10) references courses(cid));
create table courses(cid char(10),cname char(10),grader char(20) references student(sid));
However I get the following error:
1: ERROR: relation "courses" does not exist
3: ERROR: relation "student" does not exist
Is there any way or syntax which can solve this problem?
You would need to create the tables first (without REFERENCES clause). After that create your foreign keys manually by statement ALTER TABLE mytable ADD CONSTRAINT mytablefk FOREIGN KEY... But first I'd consider if there really is a relationship from table courses to table student!
Rather than creating the Foreign Key constraints at the same time as the tables with the References short-hand, you can add one or both of them afterwards with an Alter Table Add Constraint command. See the Alter Table page in the PostgrSQL manual here.
As mu pointed out, the target of a foreign key has to have a Unique or Primary Key constraint defined, so I've added that on the cid column in the example below.
In your case, it could look something like this:
create table student(sid char(20) primary key,name char(20),age int,hours char(10));
create table courses(cid char(10) primary key,cname char(10),grader char(20));
Alter Table student Add Constraint fk_student_hours_cid Foreign Key (hours) References courses(cid);
Alter Table courses Add Constraint fk_courses_grader_sid Foreign Key (grader) References student(sid);

How to create composite primary key in SQL Server 2008

I want to create tables in SQL Server 2008, but I don't know how to create composite primary key. How can I achieve this?
create table my_table (
column_a integer not null,
column_b integer not null,
column_c varchar(50),
primary key (column_a, column_b)
);
CREATE TABLE UserGroup
(
[User_Id] INT NOT NULL,
[Group_Id] INT NOT NULL
CONSTRAINT PK_UserGroup PRIMARY KEY NONCLUSTERED ([User_Id], [Group_Id])
)
Via Enterprise Manager (SSMS)...
Right Click on the Table you wish to create the composite key on and select Design.
Highlight the columns you wish to form as a composite key
Right Click over those columns and Set Primary Key
To see the SQL you can then right click on the Table > Script Table As > Create To
I know I'm late to this party, but for an existing table, try:
ALTER table TABLE_NAME
ADD CONSTRAINT [name of your PK, e.g. PK_TableName] PRIMARY KEY CLUSTERED (column1, column2, etc.)
For MSSQL Server 2012
CREATE TABLE usrgroup(
usr_id int FOREIGN KEY REFERENCES users(id),
grp_id int FOREIGN KEY REFERENCES groups(id),
PRIMARY KEY (usr_id, grp_id)
)
UPDATE
I should add !
If you want to add foreign / primary keys altering, firstly you should create the keys with constraints or you can not make changes. Like this below:
CREATE TABLE usrgroup(
usr_id int,
grp_id int,
CONSTRAINT FK_usrgroup_usrid FOREIGN KEY (usr_id) REFERENCES users(id),
CONSTRAINT FK_usrgroup_groupid FOREIGN KEY (grp_id) REFERENCES groups(id),
CONSTRAINT PK_usrgroup PRIMARY KEY (usr_id,grp_id)
)
Actually last way is healthier and serial. You can look the FK/PK Constraint names (dbo.dbname > Keys > ..) but if you do not use a constraint, MSSQL auto-creates random FK/PK names. You will need to look at every change (alter table) you need.
I recommend that you set a standard for yourself; the constraint should be defined according to the your standard. You will not have to memorize and you will not have to think too long. In short, you work faster.
First create the database and table, manually adding the columns. In which column to be primary key. You should right click this column and set primary key and set the seed value of the primary key.
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)

How Can I Reference Multiple Primary Keys For A Vector Type Primary Key

I have the following scenario: a table of projects and a table of persons, working on one or several projects. Also, I have a project id column (of type int), in the first table, which is a primary key there and I have a vector of project ids, as a column of type int, in my second table (persons), that references primary keys from the first table.
What is the correct syntax for referencing multiple primary keys, from a vector foreign key.
This is the way I am trying to create the table, but I am not sure what to place at the indicated line:
CREATE TABLE Persons(
Person_Id int,
...,
ProjectsList int[],
FOREIGN KEY (ProjectsList) REFERENCES Projects(Project_id) -- not sure what how to define the link here
);
I hope my explanations are not over-complicated. Thank you in advance for helping!
I assume you're using PostgreSQL, since that's one of the rare databases that supports array data types.
There is no syntax for declaring a foreign key that applies to the elements of an array.
You could write a trigger or a CHECK constraint as mentioned here.
But the better solution is to add a table to implement the many-to-many relationship between Projects and Persons, as Lukáš Lalinský shows. This supports First Normal Form.
No database I know can do that (using real foreign keys, not some custom triggers). You might want to normalize the tables:
CREATE TABLE Persons (
Person_ID int,
...
PRIMARY KEY (Person_ID)
);
CREATE TABLE PersonProjects (
Person_ID int,
Project_ID int,
PRIMARY KEY (Person_ID, Project_id),
FOREIGN KEY (Person_ID) REFERENCES Persons(Person_ID),
FOREIGN KEY (Project_ID) REFERENCES Projects(Project_ID)
);