Difference between using or not using CONSTRAINT keyword on SQL Server - sql

What is the difference between using or not using the CONSTRAINT keyword when working with Foreign Keys on SQL Server?
I noticed that apparently both worked the same in this specific case, without CONSTRAINT:
CREATE TABLE ClientsPhones
(
ClientPhone varchar(10) NOT NULL,
ClientID smallint NOT NULL,
PRIMARY KEY (ClientPhone),
FOREIGN KEY (ClientID) REFERENCES Clients(ClientID)
);
And with CONSTRAINT:
CREATE TABLE ClientsPhones
(
ClientPhone varchar(10) NOT NULL,
ClientID smallint NOT NULL,
PRIMARY KEY (ClientPhone),
CONSTRAINT fk_ClientID
FOREIGN KEY (ClientID) REFERENCES Clients(ClientID)
);
Both didn't let me add records to the table unless the ClientID already existed on the Clients table, and the same ClientID and ClientPhone weren't already on the ClientsPhones table.
Is there any real difference between the two besides the fact that I'm able to name the constraint?

If you don't create constraint.it will automatically create own constraint name
the foreign key index name is generated using the name of the referencing foreign key column Automatically.
So there is no way to see difference of using and not using Constraint keyword. by default constraint name will be defined.

I did some research and don't believe Hell Boy's answer was as clear as it could be and had some misinformation.
Every constraint you add to a database has a name set by default. This includes PRIMARY KEY, FOREIGN KEY, DEFAULT, NOT NULL. It isn't necessarily the name of the column(s) used.
You can imagine that when you don't use the CONSTRAINT keyword SQL Server puts it there as well as generates a name for you.
If you want to remove or change a constrain you would either have to delete the entire table and recreate it with the correct constraints or you can reference the constraint by name and then alter it somewhat like a column using the ALTER keyword. This can be useful for when you need to delete a table with a foreign key. If you name the foreign key constraint you can delete it and then the table instead of having to delete the table the foreign key points to.

Related

ALTER TABLE query for foreign key constraint does not work

I'm a beginner and creating my own simple blockchain app for fun. The blockchain itself is fully functional. Now I'm trying to implement a database to store the data of the blockchain (right now I'm writing it to a .txt file). So I want to create the following database schema in sqlite:
CREATE TABLE `Blockchain`
(
`previous_hash` string NOT NULL ,
`timestamp` float NOT NULL ,
`signature_of_transactions` string NOT NULL ,
`index` bigint NOT NULL ,
PRIMARY KEY (`previous_hash`)
);
CREATE TABLE `Wallet`
(
`public_key` string NOT NULL ,
PRIMARY KEY (`public_key`)
);
CREATE TABLE `Transactions`
(
`signature` string NOT NULL ,
`sender` string NOT NULL ,
`recipient` string NOT NULL ,
`amount` float NOT NULL ,
PRIMARY KEY (`signature`)
);
CREATE TABLE `Peer_nodes`
(
`id` string NOT NULL ,
`public_key` string NOT NULL ,
PRIMARY KEY (`id`)
);
ALTER TABLE `Wallet`
ADD CONSTRAINT `fk_Wallet_public_key`
FOREIGN KEY(`public_key`) REFERENCES `Peer_nodes` (`public_key`);
ALTER TABLE `Transactions`
ADD CONSTRAINT `fk_Transactions_signature`
FOREIGN KEY(`signature`) REFERENCES `Blockchain` (`signature_of_transactions`);
ALTER TABLE `Transactions`
ADD CONSTRAINT `fk_Transactions_sender`
FOREIGN KEY(`sender`) REFERENCES `Wallet` (`public_key`);
ALTER TABLE `Transactions`
ADD CONSTRAINT `fk_Transactions_recipient`
FOREIGN KEY(`recipient`) REFERENCES `Wallet` (`public_key`);
Creating the tables with the columns etc. works fine with the script above. The ALTER TABLE queries do not work somehow. This is the following error message I receive:
ALTER TABLE Wallet ADD CONSTRAINT fk_Wallet_public_key FOREIGN KEY(public_key) REFERENCES Peer_nodes (public_key)
ERROR:
As you can see, it has no real error message. I haven't found a possible error in the queries themselves after searching a lot on the internet. What am I doing wrong? I try to do this via phpLitedmin, so maybe the problem is there?
SQLite's ALTER TABLE does not support adding constraints.
You have to include the constraints into the CREATE TABLE statements.
And as already noted by Gordon, foreign key constraints require the target to be a primary or candidate key.
Your foreign key reference is to the wrong column. It should be to the primary key, although it can be to a unique key.
As explained in the documentation:
Usually, the parent key of a foreign key constraint is the primary key
of the parent table. If they are not the primary key, then the parent
key columns must be collectively subject to a UNIQUE constraint or
have a UNIQUE index. If the parent key columns have a UNIQUE index,
then that index must use the collation sequences that are specified in
the CREATE TABLE statement for the parent table.
You should fix the table definition and add the foreign key to use the primary key.

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

create foreign key in oracle

is there anyone who can help me to create a foreign key for my Status table. I need to PLACE a foreign key constraint on the code in the status table, referring to the id in the Building table.
TABLE building
(
build_name VARCHAR2(50,0) NOT NULL,
id NUMBER (38,0) NOT NULL,
mapid NUMBER (10,0) NOT NULL
);
TABLE STATUS
(
code VARCHAR(2 BYTE) NOT NULL,
status_name VARCHAR2(40 BYTE) NOT NULL,
);
Bulding table has constraint building_gmidx with id as primary key.
Here is a quick syntax for your current requirement, however I recommend you to go through the oracle documentation for a proper understanding of what this means.
ALTER TABLE STATUS ADD (
CONSTRAINT status_fk_building FOREIGN KEY (code)
REFERENCES building (id)
ENABLE VALIDATE);
Did you leave out CREATE TABLE *name* to save time when writing the question? The first thing I see is that your Foreign key has to have the same data type and size as your Primary key. If the Tables already exist the code would be:
ALTER TABLE status MODIFY (code NUMBER(38));
From there you would need to
ALTER TABLE status ADD FOREIGN KEY (code) REFERENCES (building_gmidx)
Why is the constraint for building Primary key named building_gmidx and the column plain id?? All Normalized table attributes should be Unique. Wouldn't it be better if you just named the column "id" building_gmidx instead. Just in case there are other types of id's added later you do not have to think about which table "id" pertains to. Let me know if this works.

Why use named key constraint (Eg: Foreign Key) [duplicate]

This question already has answers here:
Differences between "foreign key" and "constraint foreign key"
(3 answers)
Closed 9 years ago.
I am not much familiar with the SQL and please explain me the difference of following two and what is the best way to use. Is there any advantage using one over a another.
CREATE TABLE Employee
(
Emp_Id int NOT NULL,
Dep_Id int NOT NULL,
...
FOREIGN KEY (Dep_Id) REFERENCES Department(Dep_Id)
);
And
CREATE TABLE Employee
(
Emp_Id int NOT NULL,
Dep_Id int NOT NULL,
...
CONSTRAINT fk_EmpDept FOREIGN KEY (Dep_Id) REFERENCES Department(Dep_Id)
);
I always name my keys and constraints, generally with enough information that anybody looking at the key name will be able to understand what the key does.
Foreign keys I name FK_FieldName#TableName.
Primary keys I name PKC_TableName or PKN_TableName ("c" for "clustered" and "n" for "nonclustered", although this is not critical).
For indexes, I name them based upon their uniqueness, their clusteredness, and an "I" for index, e.g., UNI_FieldName#TableName.
The reason for naming is for the convenience both if you ever need to drop the object and, more importantly, if something in your code attempts to violate the relationship / constraint. It's immediately apparent where the problem is, if you get a message back saying that you've had a key violation of key FK_FieldName#TableName but not so clear if the name doesn't make sense.
The only difference is in naming. If you don't explicitly set a name for constraint, it will has auto generated name. For example: FK_Employee_Dep_Id__164452B1 . And you'll see this name in description of table keys, in different exceptions and so on.
If you do not name a foreign key, the db implicitly assign a foreign key name for the field.
And if you name a foreign key, the db uses that as foreign key constant name.
You can use drop FOREIGN KEY foreign_key_name for dropping the constraint (for MySql).
You can use drop constraint foreign_key_name for dropping the constraint (for Oracle, MS Sql etc).
You can use
ALTER TABLE TableName
ADD CONSTRAINT foreign_key_name
FOREIGN KEY (field)
REFERENCES foreign_key_table(Foreign_key_field)
First example with FOREIGN KEY (Dep_Id) REFERENCES Department(Dep_Id) is used in MySQL and it does not allow you to give this constraint specific name.
In the second example with CONSTRAINT fk_EmpDept FOREIGN KEY (Dep_Id) REFERENCES Department(Dep_Id) you can change fk_EmpDept to basically any name you want.
It can be used in MySQL, SQL Server, Oracle, MS Access.
Using second version you can also created Foreign Key constraint on several columns.

Trouble understanding SQL (Oracle) create table code

I am aware of Oracle's create table syntax
CREATE TABLE MyTable(
id int primary key,
...
);
This will create a table called MyTable with an int primary key. So, nothing new here.
but I am having difficulties understanding the following query:
CREATE TABLE departament (
cod_dept INTEGER CONSTRAINT dept_key PRIMARY KEY,
dept_name CHAR(15) NOT NULL,
admission DATE NOT NULL,
localization CHAR(20))
When I look up on Oracle's SQL Developer software on departement's table, I can see 4 columns: cod_dept, dept_name, admission and localization. On the constraints tab, I can also see dept_key, but I am confused as to what this might mean. What is dept_key purpose here?
Edit
Ok, seems it is a way to define the name of the constraint you're adding to the table. My next question is why don't you just call it the same name as the primary key column? From what I've seen it seems Oracle by default just creates a random name for the constraint!
Thanks
When you write id int primary key, Oracle will create a primary key constraint to ensure uniqueness of primary key values. All constraints have names, so in this case Oracle assigns an autogenerated name to this constraint. But you can set a name of this constraint explicitly using the CONSTRAINT syntax:
cod_dept INTEGER CONSTRAINT dept_key PRIMARY KEY
This name may be used later to refer to the constraint, for example, to delete or modify it:
ALTER TABLE department DROP CONSTRAINT dept_key;
EDIT:
Constraint names are unique across the schema, so Oracle can't just use the name of primary key column as a constraint name.
Primary keys can be explicitly be named. dept_key is just a name.
dept_key is the name of the primary key constraint. That means cod_dept is the unique identifier for your table, the mechanism for identifying a row, and so it can only have one occurrence of any given value.
That is the constraint you created representing the primary key.
A table is made up of:
Columns (where the data lives)
Indexes (indexed copies of the data used for faster searching)
Constraints (rules about what data can be in the table, including PK, FK, and check constraints).
dept_key is the name of the constraint. You specified the name here : "INTEGER CONSTRAINT dept_key PRIMARY KEY," so it will create a constraint with the name dept_key.
Another syntax for the same would be to write the following after your CREATE TABLE instruction.
ALTER TABLE department
ADD CONSTRAINT dept_key PRIMARY KEY (cod_dept)
dept_key is then the name of the constraint you created to be the primary key for this table. In order for a database engine to know the primary key, and to index it for fastest results and so forth, it needs to create a known constraint that is indexed. Here, it is you who has given the name which is dept_key.
For you kind information, it is often seen to write PK_[table name] for primary keys constraints and FK_[current_table_name]_[foreign_table_name] for foreign keys constraints.
Hope this helps! =)
I think whenever we create a Primary Key value then by default Oracle will crate constraint for it with the same name but it looks like that u are creating constraint with some other name.
Thank You