What is the difference between a constraint primary key and normal primary key? - sql

I know Its possible to use the constraint to put multiple fields like this:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
But If we had to compare these two below, is there is any difference?
Create table client
(cod_clt int identity not null,
Nom t,
Dn datetime not null,
Credit numeric(6,2) not null,
Constraint x1 check (credit between 100 and 1456.25),
Constraint x2 primary key (cod_clt)
)
and this:
Create table client
(cod_clt int primary key,
Nom t,
Dn datetime not null,
Credit numeric(6,2) not null,
Constraint x1 check (credit between 100 and 1456.25)
)

There's 6 classes of constraints in SQL server:
NOT NULL
Unique Key
Primary Key
Foriegn Key
Check
Default
(Some, including myself, will argue that a column Data Type and Unique indexes are also types of constraints but I digress.)
In SQL Server there are two types of constraints: Column level and Table level.
NOT NULL is a column level constraint, all the others can be table or column level. Primary and foreign keys can consist of one or more columns; when they consist of more than one column they are known as a "composite key". Composite keys must be table-level.
The most notable difference between column and table level constraints is that table level allows you to give your constraints a meaningful name which is why I personally prefer them.
In your first example you have a table level primary key constraint and it is a composite key. In your last two examples don't have a composite key which is why it can be both table and column level. The key difference in your last two examples is that you are able to name the table level primary key but not the column level one. This is a big deal for people who properly manage their metadata.
Lastly, one thing that makes Primary Key & Unique constraints are special in that, when you create them, you can create an index. The default behavior for a primary key is to also create a clustered index. The decision to create a clustered index and/or unique index is a big one so I include the keywords clustered or nonclustered when I define my primary (and unique) keys so as not to depend on default system behavior for this.
Here's a couple good links about constraints:
https://technet.microsoft.com/en-us/library/ms189862(v=sql.105).aspx - (Microsoft)
https://www.w3schools.com/sql/sql_constraints.asp (W3 Schools)

Related

Why is my create table failing? - does not match primary key

This is what I am trying to create:
CREATE TABLE VEHICLEREPORT
(
DeptID char(2) not null,
Vin# char(3) not null,
Miles varchar(6) not null,
Bill# char(3) not null,
EID char(3) not null,
PRIMARY KEY (DeptID, Vin#),
FOREIGN KEY (bill#) REFERENCES billing,
FOREIGN KEY (EID) REFERENCES Employee
);
The issue is with my reference to billing. The error says:
The number of columns in the referencing column list for foreign key 'FK__VEHICLERE__Bill#__5AEE82B9' does not match those of the primary key in the referenced table 'Billing'.
but my billing table entered fine:
CREATE TABLE BILLING
(
VIN# char(3),
BILL# char(3),
PRIMARY KEY (VIN#, Bill#),
FOREIGN KEY (VIN#) REFERENCES vehicle
);
What am i missing with this?
Appreciate the help.
If you think of the foreign key as establishing a parent-child relationship between two tables, then the parent side column(s) need to be unique.
From Wikipedia:
In the context of relational databases, a foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table or the same table. ... In simpler words, the foreign key is defined in a second table, but it refers to the primary key or a unique key in the first table.
In your example, there is no guarantee that VIN# is unique in VEHICLEREPORT. Below are your options
VIN# is guaranteed to be unique in VEHICLEREPORT. In this case add a UNIQUE constraint on VIN# on the VEHICLEREPORT table. The error will go away.
VIN# is not unique in VEHICLEREPORT (doesn't seem likely). If this is the case, then likely there is a flaw in the design of your BILLING table as it could likely point to more than one row in VEHICLEREPORT. You should consider adding DeptID column to BILLING and creating a composite foreign key.
Also if VIN# is unique (case 1 above), you should think of why DeptID is present in the PK. Maybe the right fix at the end is to drop DeptID from the primary key.

Difference Between Unique And Composite Primary key In sql server

I want to know what is the difference between unique key and composite primary key in SQL Server.
According to w3c school:
The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
We can create composite primary key by using this:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
For composite primary key syntax:
CREATE TABLE Persons
(
P_Id int,
C_Id int,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Primary Key (P_Id,C_Id)
);
The UNIQUE constraint uniquely identifies each record in a database table. This provide a guarantee for uniqueness for a column or set of columns. We can define(point) a single row with this.
A PRIMARY KEY has a UNIQUE constraint by default.
While in some tables, there won't be any columns with a unique value to define a row. In such cases COMPOSITE KEYs are used. In such cases two or more columns are combined together so that this combination is unique.
As you said yourself, the only difference between a unique and a primary key is that there may only be 1 primary key on a table while it can have more unique keys.
Furthermore, the values of a primary key may not be null.
Both unique- and primary keys can be composed of multiple columns (composed key).
By the ways, in your example you had a unique key on the P_Id column and a composed primary key that includes that very same column.
This has no sense.
I would suggest to create only a simple primary key on that P_Id column.
Composite keys are formed of more than one column
Primary key prevents a second row on that table with same key column values.
A Primary key can be formed of a single column and as well as of more than one column. So primary key can be defined as a composite key too.
The primary key does not accept the any duplicate and NULL values.
A primary key of one table can be referenced by foreign key of another table. A table can have more than one unique key unlike primary key. Unique key constraints can accept only one NULL value for column. Unique constraints are also referenced by the foreign key of another table. A composite key is having two or more attributes that together can uniquely identify a tuple in a table. Such a key is also known as Compound Key, where each attribute creating a key is a foreign key in its own right.

Using a foreign key as part of a composite primary key

I have two tables in SQL Server. The first is all the 1:1 relationships that belong to individual jobs, which has the primary key declared as follows:
CREATE TABLE Jobs(
JobNumber bigint PRIMARY KEY )
The second table is the list of all of the jobs' components and their 1:1 relationships.
Each component refers to a single job by its job number, which is a foreign key, and multiple components may refer to the same job. Components are numbered within jobs as 1, 2, 3 and so on.
Is it possible and reasonable to use the column JobNumber (foreign key) within a composite primary key in the 2nd table, so that the primary key would be made up of (JobNumber, ComponentNumber) as follows:
CREATE TABLE Components(
JobNumber bigint FOREIGN KEY REFERENCES Jobs(JobNumber) NOT NULL,
ComponentNumber int NOT NULL,
PRIMARY KEY(JobNumber, ComponentNumber)
)
The other option is, of course, to use a surrogate primary key, but this would not enforce the uniqueness constraint on the combination of JobNumber and ComponentNumber (two records in the 2nd table could have JobNumber=1 and ComponentNumber=1, for example), so I would prefer to use a composite natural primary key.
Sure, why not? I don't see any reason not to use the composite primary key!
The only minor drawback is that any other table that needs to reference your Components table now also must use both columns to establish a foreign key relationship - you cannot reference only half of the primary key of a table.
Also: if you would choose to use a separate surrogate column as your PK, you can always enforce uniqueness with a unique constraint on (JobNumber, ComponentNumber) ....

MariaDB primary key vs unique key

In some ways this question follows on from this one. One of the injunctions in the MariaDB documnetation suggests that having tables on a clustered database without a primary key is not desirable. In my application I have as a rule been using one UNIQUE key (VARCHAR(8)) per table with no PRIMARY key. My understanding is that a PRIMARY key is merely a special kind of UNIQUE key. Question - is the current UNIQUE key usage adequate for keeping MariaDB Galera happy or do I explciitly need to convert my UNIQUEs to PRIMARYs? On the face of it this does not make much sense to me but perhaps there are reasons for doing so?
In the absence of a PRIMARY key, InnoDB/XtraDB will first try to use a UNIQUE index. If neither exist it will make up an internal primary key that is not reliable between galera nodes.
You are correct that a PRIMARY key is basically a UNIQUE index with the only difference being that there can only be one PRIMARY key. It is also used for the physical layout of the data but that isn't as important here.
As long as there is only one UNIQUE index, you should be fine. However, I don't think it would be reliable if you add another UNIQUE index. Because of that and for good practice, you should probably make that UNIQUE index the PRIMARY key.
a PRIMARY KEY require that the column is NOT NULL
in the table CREATE TABLE p (a INT, b INT, UNIQUE (a)); you can have 2 rows where a IS NULL.
in the table CREATE TABLE p2 (a INT, b INT, PRIMARY KEY (a)); the a column automaticly becomes a NOT NULL column.
SHOW CREATE TABLE p2;
CREATE TABLE `p2` (
`a` int(11) NOT NULL DEFAULT '0',
`b` int(11) DEFAULT NULL,
PRIMARY KEY (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

sql single primary key

While reading articles on w3schools about SQL primary keys I read the following:
Each table should have a primary key, and each table can have only ONE primary key.
http://www.w3schools.com/sql/sql_primarykey.asp
Yet I have this SQL file, for making a table, which I ran and worked:
CREATE TABLE accessLog (
memberId SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
pageUrl VARCHAR(255) NOT NULL,
numVisits MEDIUMINT NOT NULL,
lastAccess TIMESTAMP NOT NULL,
PRIMARY KEY (memberId, pageUrl)
);
Now according the the primary key quote above, the line of code: " PRIMARY KEY(memberId, pageUrl)," should not have worked.
Any help on this about how you can have more than ony primary key in a table. Note:I already know about the "UNIQUE", "UNIQUE KEY" statement.
This is a composite primary key - it's still one key, but it's comprised of multiple columns. Here's a good, short description of composite primary keys.
It is a composite primary key . When you define more than one column as your primary key on a table, it is called a composite primary key.
Your quote
"Each table should have a primary key, and each table can have only ONE primary key."
is misleading. It's equivalent to saying that each state can have only one capital city, or that each company can have only one Chief executive officer.
Of course each table can have only one PRIMARY key. But any table can have multiple Unique Keys. And, frankly, does not have to have any one of them designated as "PRIMARY". In fact designating one key as PRIMARY key does absolutely nothing at all. There is only one distinction (except as noted below) attached to the Primary Key which is not also associated with all keys.
EDIT ... except for one small distinction. If a key is designated as the Primary key, then all the fields used in that key must be non-nullable. Other Unique keys are not required to honor this rule, although rows in the table which contain nulls must still be unique, in that there cannot be more thab one row with the same values for all the non-nullable field and a null value in a nullable field.