sql single primary key - sql

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.

Related

Why we need a primary key?

I am reading about primary keys and at a lot of tutorials, technical blogs etc., and I found that a primary key cannot be null. I think it's totally wrong because I was able to insert null value in the column.
I suppose a primary key can have a not null value only if the column is declared as not null. But again this is not a feature of primary keys.
My question is why do we have a concept of primary key because I find only one difference between primary key and unique key is that "Primary key can be declared only on one column whereas unique key can be declared on multiple columns". So my understanding is that why can't we also declare the primary key as a unique key if we don't have any other difference.
I suppose a primary key can have a not null value only if the column
is declared as not null.But again this is not a feature of primary
key.
Primary key can't have a null values. By definition of primary key, it is UNIQUE and NOT NULL.
My another question is that why do we have a concept of primary key
because I find only one difference between primary key and unique key
is that "Primary key can be declared only on one column whereas unique
key can be declared on multiple columns"
This is completely wrong. You can create primary key on multiple columns also, the difference between Primary Key and Unique Key is Primary Key is not null and Unique key can have null values.
The main purpose of primary key is to identify the uniqueness of a row, where as unique key is to prevent the duplicates, following are the main difference between primary key and unique key.
Primary Key :
There can only be one primary key for a table.
The primary key consists of one or more columns.
The primary key enforces the entity integrity of the table.
All columns defined must be defined as NOT NULL.
The primary key uniquely identifies a row.
Primary keys result in CLUSTERED unique indexes by default.
Unique Key :
There can be multiple unique keys defined on a table.
Unique Keys result in NONCLUSTERED Unique Indexes by default.
One or more columns make up a unique key.
Column may be NULL, but on one NULL per column is allowed.
A unique constraint can be referenced by a Foreign Key Constraint.
I suggest you read this primary key and unique key
You forgot Indexing. When it comes to large data to find particular data raw it need to travel through memory record by record. To overcome that the concept of indexing is there. Primary key helps in this. So it will help to get your data access faster. After that there is concept of binary search which will helps further in that task.
A primary key is a special relational database table column (or combination of columns) designated to uniquely identify all table records.
A primary key’s main features are:
It must contain a unique value for each row of data.
It cannot contain null values.
A primary key is either an existing table column or a column that is specifically generated by the database according to a defined sequence.
The primary key concept is critical to an efficient relational database. Without the primary key and closely related foreign key concepts, relational databases would not work.
A primary key, also called a primary keyword, is a key in a relational database that is unique for each record.
One Table Have Only One Primary Key.

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

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)

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) ....

Primary Key In SQL

I want to know if it is possible to create more than one primary key in standard SQL. I mean something like that:
CREATE TABLE(Surname CHAR(100) PRIMARY KEY, Name CHAR(100) PRIMARY KEY)
Is that legal in SQL? If not, please link me a reference to the standard that says that is not possible...
Edit after the question has been clarified.
The definition of a primary key is that there is one and only one. So, no you cannot create two primary keys on two different columm.
You can however create a primary key on one column and a unique constraint on another:
create table person
(
surname varchar(100) not null primary key,
name varchar(100) not null,
constraint only_one_name unique (name)
);
The above is standard SQL for all I know.
Here is a link to the book "SQL-99, Complete" which re-states the SQL standard in a more pragmatic way: https://mariadb.com/kb/en/constraint_type-primary-key-constraint/
Quote from the book:
A Base table may be constrained by no more than one PRIMARY KEY Constraint
The original wording from the SQL standard (which is not free, so no one can give you a link to that):
A <table definition> shall specify at most one implicit or explicit <unique constraint definition> that specifies PRIMARY KEY.
(Emphasis mine)
Note that you almost never want char - especially not with a length greater than just two or three characters. The CHAR datatype pads all values to the defined length. So if you inserted the value 'FOO' into a CHAR(10) column it will (has to) be stored as 'FOO '
No, It's not legal to create two primary keys in SQL, If you are able to create two separate primary keys then it's not a primary key anymore.
You can create a composite primary keys, like primary key(surname, name) for e.g. but this will be never applicable not good pratice, primary key on name and surname.
No - but you can have a single primary key that is a combination of multiple columns:
From MSDN:
A table typically has a column or combination of columns that contain values that uniquely identify each row in the table. This column, or columns, is called the primary key (PK) of the table and enforces the entity integrity of the table. You can create a primary key by defining a PRIMARY KEY constraint when you create or modify a table.
A table can have only one PRIMARY KEY constraint, and a column that participates in the PRIMARY KEY constraint cannot accept null values. Because PRIMARY KEY constraints guarantee unique data, they are frequently defined on an identity column.
This is a bit pedantic, but of course you cannot create more than one primary key, just like there cannot be more than one tallest person in the room. But you can, (and many times should), create more than one unique key. and, except for one minor distinction there is no functional difference between them. A unique key can be used as the target of a FK constraint, or in joins just like a primary key can.
you can only have one primary key, but this primary key can be made by N columns.
example:
create table "TABLE NAME"(
"Surname" CHAR(100),
"Name" CHAR(100),
primary key ("Surname", "Name")
);
You can have a primary key containing multiple columns. This is often done in attributive tables, where one part of the key contains the id of the record in the table you're attributing to.
You can't have more than one primary key simply because it is ranked as 'the most important'. There can't be two things 'most important'.