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
Related
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)
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'.
I'm working with apache derby jdbc (in netbeans 7.2.1)
I want to create table with composite primary key (so that only the composition of these 4 columns values is unique, and value of each one of them separately is not unique)
Create table MovieScreens(
NameM varchar(255) NOT NULL UNIQUE,
DateS DATE NOT NULL UNIQUE,
Hall NUMERIC NOT NULL UNIQUE,
HourS NUMERIC NOT NULL UNIQUE,
SEATSFREE varchar (500) NOT NULL,
FOREIGN KEY (Hall) REFERENCES Halls(Hall),
FOREIGN KEY (NameM) REFERENCES MoviesDetails(NAMEM),
**primary key (NameM , DateS,Hall,HourS)**
)
But it seems each of the columns defined as primary key is primary key by itself, and not part of the composite key. When I try to insert rows that differ only by one of these values, I get error:
Error code -1, SQL state 23505: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index .
As I understand netbeans uses MySQL database, and this should be the right syntax for MySQL, or am I wrong?
Any input would be appreciated, thanks!
You set the fields composing your primary key as UNIQUE so each one of them cannot have twice the same value. Remove this constraint and just keep the primary key declaration.
By the way, your problem is only related to pure SQL.. Using JDBC has no impact on this.
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.
I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented.
A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the InnoDB storage schema that MySQL has.
What is a simple example of foreign keys implemented in MySQL?
Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example.
CREATE TABLE `posts` (
`pID` bigint(20) NOT NULL auto_increment,
`content` text NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`uID` bigint(20) NOT NULL,
`wikiptr` bigint(20) default NULL,
`cID` bigint(20) NOT NULL,
PRIMARY KEY (`pID`),
Foreign Key(`cID`) references categories,
Foreign Key(`uID`) references users
) ENGINE=InnoDB;
Assuming your categories and users table already exist and contain cID and uID respectively as primary keys, this should work:
CREATE TABLE `posts` (
`pID` bigint(20) NOT NULL auto_increment,
`content` text NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`uID` bigint(20) NOT NULL,
`wikiptr` bigint(20) default NULL,
`cID` bigint(20) NOT NULL,
PRIMARY KEY (`pID`),
Foreign Key(`cID`) references categories(`cID`),
Foreign Key(`uID`) references users(`uID`)
) ENGINE=InnoDB;
The column name is required in the references clause.
Edited: Robert and Vinko state that you need to declare the name of the referenced column in the foreign key constraint. This is necessary in InnoDB, although in standard SQL you're permitted to omit the referenced column name if it's the same name in the parent table.
One idiosyncrasy I've encountered in MySQL is that foreign key declaration will fail silently in several circumstances:
Your MySQL installation doesn't include the innodb engine
Your MySQL config file doesn't enable the innodb engine
You don't declare your table with the ENGINE=InnoDB table modifier
The foreign key column isn't exactly the same data type as the primary key column in the referenced table
Unfortunately, MySQL gives no message that it has failed to create the foreign key constraint. It simply ignores the request, and creates the table without the foreign key (if you SHOW CREATE TABLE posts, you may see no foreign key declaration). I've always thought this is a bad feature of MySQL!
Tip: the integer argument for integer data types (e.g. BIGINT(20)) is not necessary. It has nothing to do with the storage size or range of the column. BIGINT is always the same size regardless of the argument you give it. The number refers to how many digits MySQL will pad the column if you use the ZEROFILL column modifier.
This has some code showing how to create foreign keys by themselves, and in CREATE TABLE.
Here's one of the simpler examples from that:
CREATE TABLE parent (
id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (
id INT,
parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
I agree with Robert. You are missing the name of the column in the references clause (and you should be getting the error 150). I'll add that you can check how the tables got created in reality with:
SHOW CREATE TABLE posts;
The previous answers deal with the foreign key constraint. While the foreign key constraint is definitely useful to maintain referential integrity, the concept of "foreign key" itself is fundamental to the relational model of data, regardless of whether you use the constraint or not.
Whenever you do an equijoin, you are equating a foreign key to something, usually the key it references. Example:
select *
from
Students
inner join
StudentCourses
on Students.StudentId = StudentCourses.StudentId
StudentCourses.StudentId is a foreign key referencing Students.StudentId.