I am creating a table in MariaDB to store "remember me"-cookie values:
CREATE TABLE u_remember_me (
u_user_common_id INT UNSIGNED NOT NULL,
lookup_key VARCHAR(30) NOT NULL,
token_hash VARCHAR(30) NOT NULL,
created DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX (u_user_common_id),
FOREIGN KEY (u_user_common_id) REFERENCES u_user_common (id) ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (lookup_key),
UNIQUE KEY (lookup_key, token_hash)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_520_ci ENGINE InnoDB;
I am always going to lookup by the lookup_key field and have therefore chosen that as a primary key (random string). The column u_user_common_id can not be set as primary key since a user can have multiple (lookup_key, token_hash) assigned because of multiple browsers or computers. Is lookup_key a bad choice for a primary key (performance, insert etc.?). Also.. Should I set the primary key to (lookup_key, token_hash) instead and drop the UNIQUE constraint? The reason why I have chosen not to have a surrogate key is because it will never be used, but I am not sure if that is a good decision either (I need lookup_key to be indexed anyway).
I think you have not figured out what depends on what.
Is the lookup_key (random string) associated with a single user? If so, PRIMARY KEY(lookup_key) and get rid of token_hash.
If the user can connect from different browsers and you want something different to happen, then you have not specified any data that will be different.
Related
I have a table in database.
CREATE TABLE `comment_sheets` (
`id` mediumint(9) NOT NULL AUTO_INCREMENT,
`doc_id` mediumint(9) NOT NULL,
`level` varchar(10) DEFAULT NULL,
`author` varchar(30) DEFAULT NULL,
`status` varchar(10) DEFAULT NULL,
`creation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `cs` (`doc_id`,`level`,`author`)
) ENGINE=InnoDB AUTO_INCREMENT=3961075 DEFAULT CHARSET=utf8 ;
My UNIQUE KEY cs (doc_id,level,author) is a problem now. I want to remove it, becouse i need duplicate values.
My question is. What should i have in my mind or what shoud I be worry about, when i want delete unique key?
Thanks.
To drop unique key
ALTER TABLE table_name
DROP INDEX index_name;
To drop primary key
ALTER TABLE table_name
DROP INDEX `PRIMARY`;
You need to alter table:
alter table comment_sheets drop INDEX `cs`
It really depends on how the key is used apart from enforcing uniqueness of data.
Check if the key is used in any foreign key relationships. If yes, you need to drop the foreign key before you can drop the unique one. (Well, mysql won't let you drop the index if the foreign key exits anyway)
Check what queries may make use of the key and how its removal would affect their performance. You may have to add a non-unique key on these fields back.
I this particular case dropping the index is relatively simple task because it is not the primary key, and it is not a fulltext index. The only thing that may take long is the removal of the index data if your table is big (judging from the auto increment value, it is not a small table)
I have a table SkillLevel created as
CREATE TABLE `sklllevel` (
`Name` varchar(20) NOT NULL,
`level` enum('No Experience','Beginner','Expert','Advisor') DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
With Values
INSERT INTO test.sklllevel (name,level) values ('No Experience','No Experience'),('Beginner','Beginner'),('Expert','Expert'),('Advisor','Advisor');
I want to refer SkillLevel.Level with testSkill.tkSkill in another table created as:
CREATE TABLE `testskill` (
`pkid` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`tkSkill` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`pkid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DO I need to have tkSkill as ENUM with same set of Values to set a foreign key? What is the best practise here?
Short answer: enums are stored as a number, so technically, you could join them with tkSkill as a tinyint.
To use it as a foreign key, you indeed need to have both tkSkill and level to be the same enum - but you need level to be a unique column to qualify as a foreign key, so add unique to it (to be really precise: for InnoDB, you can have non-unique foreign keys if you manually create the index, but non-unique foreign keys are generally a bad idea). But you should think about what your key in sklllevel should be, since now it looks as if you want Name to be the key.
And independently from having it as key you should define tkSkill as (the same) enum to make sure they both mean the same if you at one point would like to change the enums (what is a bad idea!) and e.g. add another skilllevel; or if you want to "read" (directly understand) the value when you select directly from the table testskill without the need to join sklllevel; and if you want to insert values into tkSkill by using their enum-namoe (e.g. 'Expert' instead of 3, but you can use both) without looking them up in sklllevel.
Longer answer: Best practice is: don't use enums. Depending on "belief", there is none to only a handful of cases when enums might be slightly useful, if at all. One could be that you don't want to use a reference table to skip a join to display the textvalue/description of an integer-id. In your setup, you are actually using a reference table and still want to use enums.
The closest you'll get to best practice using enums would be to define tkSkill as enum in testskill and don't have the sklllevel-table (the reference table) at all.
But again, I would urge you not to use enums. You can define your table as
CREATE TABLE `sklllevel` (
`Id` tinyint(4) primary key,
`Name` varchar(20) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and then use that id as a foreign key for tkSkill. Or even
CREATE TABLE `sklllevel` (
`Name` varchar(20) primary key
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and then define tkSkill as varchar(20) and use this as a foreign key - it will use more space, though, but you will have "readable" values in the table if that was the reason for you to use enums in the first place.
Here you can find some background to enums: 8 Reasons Why MySQL's ENUM Data Type Is Evil
Can creating a UNIQUE index on an Id as shown in the create table below be enough to make the id a Primary Key? TO be more specific, can you say that the table below has a Primary Key?
test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`role` varchar(32) NOT NULL,
`resources_name` varchar(32) NOT NULL,
`access_name` varchar(32) NOT NULL,
`allowed` int(3) NOT NULL,
UNIQUE KEY `id` (`id`),
UNIQUE KEY `roles_name` (`role`,`resources_name`,`access_name`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8
What query can you use to prove that this has or has no PK?
Logically speaking if a relational table has at least one candidate key enforced in it (minimally unique and non-nullable) then de facto it has a "primary" key. There is no absolute need to single out any one key using a special "primary" label because in principle all keys are equal (historically the term "primary key" used to be used for any and all candidate keys and not just one key per table).
There is a constraint in SQL called a PRIMARY KEY constraint. Logically speaking, the SQL PRIMARY KEY isn't much more than syntactical sugar because the NOT NULL UNIQUE syntax achieves essentially the same thing. Technically the PRIMARY KEY constraint doesn't have to refer to the same thing as the relational concept of a "primary key" but clearly if you are going to designate any one key as primary and if you feel you need a syntactical way of indicating that choice then the PRIMARY KEY constraint is the generally recognised way to do it.
So perhaps the best answer is "it depends". It depends to a large extent on your motivation for defining a primary key in the first place. If you intend to single out one key to developers and users of the database then maybe the NOT NULL UNIQUE syntax won't achieve that for you. If you don't find the need to do that using SQL syntax then maybe NOT NULL UNIQUE is just as good a way to define your keys as the PRIMARY KEY constraint is.
This is either too long or too short for a comment: No.
A primary key and a unique key -- although similar -- are not the same. So, no your table does not have a primary key. The biggest functional difference is that primary keys cannot be NULL whereas unique keys can be.
Primary keys are also typically clustered (if the underlying storage engine supports clustered indexes). This means that the data is actually physically stored on the page in the order of the primary key. Unique keys are just another index with the characteristic of having no repeated values.
EDIT:
Interesting. SHOW COLUMNS documents this behavior:
A UNIQUE index may be displayed as PRI if it cannot contain NULL
values and there is no PRIMARY KEY in the table.
I wasn't aware of this.
I have a set of users of different types, each type has individual set of fields storing user settings. My thought was to store user_id and user_type in one table with common set of fields and to move other settings to a separate tables. But the problem is how to link user from common table with his details in separate table. I see one solution is to store table name associated with certain user type in another table. But is it the best solution?
CREATE TABLE IF NOT EXISTS `mydb`.`user` (
`user_id` INT NOT NULL,
`user_name` INT NOT NULL,
`user_type` INT NULL,
PRIMARY KEY (`user_id`, `user_name`),
UNIQUE INDEX `adv_id_UNIQUE` (`user_id` ASC),
INDEX `adv_type_idx` (`user_type` ASC),
CONSTRAINT `adv_type`
FOREIGN KEY (`user_type`)
REFERENCES `mydb`.`user_type` (`type_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS `mydb`.`user_type` (
`type_id` INT NOT NULL,
`type_table` VARCHAR(45) NULL,
UNIQUE INDEX `type_id_UNIQUE` (`type_id` ASC),
PRIMARY KEY (`type_id`))
//TABLES WITH SEPARATE SET OF FIELDS
CREATE TABLE IF NOT EXISTS `mydb`.`user_details_admin` (
`user_id` INT NOT NULL,
`user_admin` VARCHAR(45) NULL,
PRIMARY KEY (`user_id`))
CREATE TABLE IF NOT EXISTS `mydb`.`user_details_moderator` (
`user_id` INT NOT NULL,
`user_moderator` VARCHAR(45) NULL,
PRIMARY KEY (`user_id`))
This appears to be a situation where you want to model inheritance in your database.
Rather than storing the user_details_ table names in the user_types table, something akin to the following may serve you better:
CREATE TABLE IF NOT EXISTS 'mydb'.'user' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'commonfield1' datatype (NOT) NULL,
'commonfield2' datatype (NOT) NULL,
'commonfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id', (other field as needed)),
UNIQUE INDEX 'adv_id_UNIQUE' ('user_id' ASC),
INDEX 'adv_type_idx' ('type_id' ASC),
CONSTRAINT 'adv_type'
FOREIGN KEY ('type_id')
REFERENCES 'mydb'.'user_type' ('type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS 'mydb'.'user_type' (
'type_id' INT NOT NULL,
'type_name' VARCHAR(45) NOT NULL,
UNIQUE INDEX 'type_id_UNIQUE' ('type_id' ASC),
UNIQUE INDEX 'type_name_UNIQUE' ('type_name' ASC),
PRIMARY KEY ('type_id'))
//TABLES WITH SEPARATE SET OF FIELDS
CREATE TABLE IF NOT EXISTS 'mydb'.'user_details_admin' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'adminfield1' datatype (NOT) NULL,
'adminfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id'))
CONSTRAINT user_type_FK
FOREIGN KEY ('user_id', 'type_id')
REFERENCES 'mydb'.'user' ('user_id', 'type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
CREATE TABLE IF NOT EXISTS 'mydb'.'user_details_moderator' (
'user_id' INT NOT NULL,
'type_id' INT NOT NULL,
'moderatorfield1' datatype (NOT) NULL,
'moderatorfield...' datatype (NOT) NULL,
PRIMARY KEY ('user_id'))
CONSTRAINT user_type_FK
FOREIGN KEY ('user_id', 'type_id')
REFERENCES 'mydb'.'user' ('user_id', 'type_id')
ON DELETE NO ACTION
ON UPDATE NO ACTION)
This design assumes that a user may be of one and only one type. You'll need to insure that, for example, a moderator is only added to the user_details_moderator table using triggers or views, and/or by handling it in your application code. MySQL doesn't implement check constraints on tables. You'll likely want to create views, anyway, in order to avoid having to write the JOIN between the user table and the sub-type tables every time you want to query a specific sub-type.
Note: The INDEX on type_id in the user table may not be useful or necessary.
This is not the only way to model your data. If you have few fields that are distinct between types and/or are willing to have fields you know will be NULL in your table, you can just add all the fields to the user table. Other than the a priori NULL fields issue, a major difference between these approaches comes with the addition of a new user_type with new distinct fields. In the example I provided, you would need to add a new table. In the single-table design, you would need to add new nullable fields to the user table. Which is easier to maintain is really up to you, but I personally prefer the table-per-type design because in my uses adding a table is relatively trivial and I dislike intentionally adding fields that I know will contain NULL 'values' without serious optimization advantages (that don't exist in my case, but might in yours).
See also How do you effectively model inheritance in a database?, and/or search for "inheritance" under the database tag for further information.
I think creating a user_type_parameters with columns user_id, parameter_key, parameter_value could be an interesting solution as it would give you more flexibility.
the parameter_key column would be the name of some parameter like one of the columns on the user_details_admin table, and on the parameter_value column you would inster its correspondent value.
Of course on the application side you would have to know what keys to expect for each user type.
please fell free to ask if you have any doubts about my explanation.
In this system, we store products, images of products (there can be many image for a product), and a default image for a product. The database:
CREATE TABLE `products` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(255) NOT NULL,
`DESCRIPTION` text NOT NULL,
`ENABLED` tinyint(1) NOT NULL DEFAULT '1',
`DATEADDED` datetime NOT NULL,
`DEFAULT_PICTURE_ID` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`ID`),
KEY `Index_2` (`DATEADDED`),
KEY `FK_products_1` (`DEFAULT_PICTURE_ID`),
CONSTRAINT `FK_products_1` FOREIGN KEY (`DEFAULT_PICTURE_ID`) REFERENCES `products_pictures` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
CREATE TABLE `products_pictures` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`IMG_PATH` varchar(255) NOT NULL,
`PRODUCT_ID` int(10) unsigned NOT NULL,
PRIMARY KEY (`ID`),
KEY `FK_products_pictures_1` (`PRODUCT_ID`),
CONSTRAINT `FK_products_pictures_1` FOREIGN KEY (`PRODUCT_ID`) REFERENCES `products` (`ID`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
as you can see, products_pictures.PRODUCT_ID -> products.ID and products.DEFAULT_PICTURE_ID -> products_pictures.ID, so a cycle reference. Is it OK?
No, it's not OK. Circular references between tables are messy. See this (decade old) article: SQL By Design: The Circular Reference
Some DBMS can handle these, and with special care, but MySQL will have issues.
Option 1
As your design, to make one of the two FKs nullable. This allows you to solve the chicken-and-egg problem (which table should I first Insert into?).
There is a problem though with your code. It will allow a product to have a default picture where that picture will be referencing another product!
To disallow such an error, your FK constraint should be:
CONSTRAINT FK_products_1
FOREIGN KEY (id, default_picture_id)
REFERENCES products_pictures (product_id, id)
ON DELETE RESTRICT --- the SET NULL options would
ON UPDATE RESTRICT --- lead to other issues
This will require a UNIQUE constraint/index in table products_pictures on (product_id, id) for the above FK to be defined and work properly.
Option 2
Another approach is to remove the Default_Picture_ID column form the product table and add an IsDefault BIT column in the picture table. The problem with this solution is how to allow only one picture per product to have that bit on and all others to have it off. In SQL-Server (and I think in Postgres) this can be done with a partial index:
CREATE UNIQUE INDEX is_DefaultPicture
ON products_pictures (Product_ID)
WHERE IsDefault = 1 ;
But MySQL has no such feature.
Option 3
This approach, allows you to even have both FK columns defined as NOT NULL is to use deferrable constraints. This works in PostgreSQL and I think in Oracle. Check this question and the answer by #Erwin: Complex foreign key constraint in SQLAlchemy (the All key columns NOT NULL Part).
Constraints in MySQL cannot be deferrable.
Option 4
The approach (which I find cleanest) is to remove the Default_Picture_ID column and add another table. No circular path in the FK constraints and all FK columns will be NOT NULL with this solution:
product_default_picture
----------------------
product_id NOT NULL
default_picture_id NOT NULL
PRIMARY KEY (product_id)
FOREIGN KEY (product_id, default_picture_id)
REFERENCES products_pictures (product_id, id)
This will also require a UNIQUE constraint/index in table products_pictures on (product_id, id) as in solution 1.
To summarize, with MySQL you have two options:
option 1 (a nullable FK column) with the correction above to enforce integrity correctly
option 4 (no nullable FK columns)
The only issue you're going to encounter is when you do inserts.
Which one do you insert first?
With this, you will have to do something like:
Insert product with null default picture
Insert picture(s) with the newly created product ID
Update the product to set the default picture to one that you just inserted.
Again, deleting will not be fun.
this is just suggestion but if possible create one join table between this table might be helpfull to tracking
product_productcat_join
------------------------
ID(PK)
ProductID(FK)- product table primary key
PictureID(FK) - category table primary key
In the other table you can just hold that field without the foreign key constraint.
it is useful in some cases where you want to process with the smaller table but connect to the bigger table with the result of the process.
For example if you add a product_location table which holds the country, district, city, address and longitude and latitude information. There might be a case that you want to show the product within a circle on the map.
John what your doing isnt anything bad but using PK-FK actually helps with normalizing your data by removing redundant repeating data. Which has some fantastic advantages from
Improved data integrity owing to the elimination of duplicate storage locations for the same data
Reduced locking contention and improved multiple-user concurrency
Smaller files
that is not a cyclic ref, that is pk-fk