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.
Related
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.
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
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'.
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 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