MySql: Why foreign key is null? - mysql

I have 2 tables. users and post. I want to use users(id) column (which is pk) as foreign key in post(user_id) column. I used:
ALTER TABLE post ADD FOREIGN KEY (user_id) REFERENCES users(id);
and that action succeeded without any errors but I see only null in (user_id) column. Do I miss something or what? Shouldn't it copy the id values from users table?

Q: Why foreign key is null?
A: Whether or not a column can contain a NULL value is determined by the presence or absence of a NOT NULL constraint. This is entirely independent of whether the column is referenced in a foreign key constraint.
The value in the column is NULL because that's the value that was assigned when the row was inserted. The value was assigned, whether it was explicitly set, or whether it was derived from the default value for the column. (If the column was added to an existing table, then the values in the new column was the default value for the column.)
--
Q: Do I miss something or what?
A: The behavior and results you observe are exactly as we expect.
Q: Shouldn't it copy the id values from users table?
A: If you're asking if MySQL should automatically populate the user_id column in the post table, the answer to that question is no, it shouldn't.
I think maybe you've clued in on a key idea:
The "relationship" between a row in one table to a row in another table is represented in the relational database by storing a common value.
But the database doesn't know which row is related to which row. You have to tell it. You have to provide that information.
When you insert a row into the post table, you can provide a value for the user_id column. You would provide a value that's equal to the id value of some row in user.
The idea with a FOREIGN KEY constraint is that it's restriction. It only allows valid values. It prevents an invalid value from being stored. (That's true with InnoDB if FOREIGN_KEY_CHECKS=1, that's not true for MyISAM, because MyISAM doesn't enforce foreign key constraints.)
The foreign key is saying that you want to "constrain" the values that can be stored. It's saying that it's not going to allow rows in post to have have user_id values that point to a "missing" row in the users table.
It's perfectly acceptable to store a NULL in a foreign key column. When a NULL value is stored, that's saying that the row is not related to a row in the users table.
Disallowing NULL values in a column is done with a different kind of constraint, a NOT NULL constraint.
It's possible to define both a foreign key constraint and a NOT NULL constraint on the same column. That's a design decision, whether you want to allow NULL values or not. In some cases, we may want to disallow NULL values in a foreign key. For example, if we were to add a NOT NULL constraint on the user_id column of post, that would effectively be saying that a row cannot exist in post if it's not related to a row in users. And that's a very common pattern.

Adding foreign key to any column in MySQL does not copy any values.

Related

MSQL unique constraint check only onward insert records Not already existing records

The table already has duplicates entries. I want to create a unique constraint in MQSL DB without deleting the existing duplicates. If any duplicate entries coming onwards then it will show an error. Given blow queries not working in MYSQL.
ALTER TABLE presence
ADD CONSTRAINT present uniqueness UNIQUE (employee_id,roll_number) where id >10000;
or
ALTER TABLE presence
ADD CONSTRAINT present uniqueness UNIQUE (employee_id,roll_number) where id <> (343,34534,34534)
Do we have something like that solution in SQL?
Add an additional column to the table that indicates the existing values.
Set it to NULL for the existing values. And give it a constant value, say 1, for the new rows. Then create a unique index or constraint on this column:
alter table t add constraint unique (employee_id, is_old)
Actually, I realize that you probably don't want duplicates with singleton old values and new values. That is just an issue of setting the value to NULL only for duplicates in the history. So, one row would have a constant value (say 1) in the historical data.
MySQL allows duplicate values on NULL, which is why this works.

How to prevent duplicate row insert in MemSQL?

I have AUTO_INCREMENT PRIMARY KEY and another column that I can't set UNIQUE because unlike standard RDBMS like MySQL or PostgreSQL, MemSQL only allow only one of them, not both.
Is there workaround to prevent duplicate rows without sacrificing the auto_increment column?
I can use unique as primary key and use atomic counter in other product/service like Redis/atomic variable, but when I need to update the unique column I have to delete it first then reinsert, which is bad/unpreferred way for me..
MemSQL does support multiple unique keys together with a primary key. However, MemSQL requires that the columns in each unique or primary key must be a superset of the columns in the shard key - i.e. that all values that would be considered duplicate under each unique key have the same shard key, so that they get mapped to the same partition. This further implies that all the unique/primary keys must share at least one column in common.
For your case, it is not possible to have both a unique/primary key on the autoincrement column and the other column. But you can have a unique/primary key on the other column, without a unique key on the auto_increment column - just define it as a non-unique key. The automatically generated values will still be unique. Do note that then the table won't be able to enforce uniqueness if you manually insert values that are duplicate with other auto_increment values.

KEY `ix_deleted` (`deleted`) create table [duplicate]

When should I use KEY, PRIMARY KEY, UNIQUE KEY and INDEX?
KEY and INDEX are synonyms in MySQL. They mean the same thing. In databases you would use indexes to improve the speed of data retrieval. An index is typically created on columns used in JOIN, WHERE, and ORDER BY clauses.
Imagine you have a table called users and you want to search for all the users which have the last name 'Smith'. Without an index, the database would have to go through all the records of the table: this is slow, because the more records you have in your database, the more work it has to do to find the result. On the other hand, an index will help the database skip quickly to the relevant pages where the 'Smith' records are held. This is very similar to how we, humans, go through a phone book directory to find someone by the last name: We don't start searching through the directory from cover to cover, as long we inserted the information in some order that we can use to skip quickly to the 'S' pages.
Primary keys and unique keys are similar. A primary key is a column, or a combination of columns, that can uniquely identify a row. It is a special case of unique key. A table can have at most one primary key, but more than one unique key. When you specify a unique key on a column, no two distinct rows in a table can have the same value.
Also note that columns defined as primary keys or unique keys are automatically indexed in MySQL.
KEY and INDEX are synonyms.
You should add an index when performance measurements and EXPLAIN shows you that the query is inefficient because of a missing index. Adding an index can improve the performance of queries (but it can slow down modifications to the table).
You should use UNIQUE when you want to contrain the values in that column (or columns) to be unique, so that attempts to insert duplicate values result in an error.
A PRIMARY KEY is both a unique constraint and it also implies that the column is NOT NULL. It is used to give an identity to each row. This can be useful for joining with another table via a foreign key constraint. While it is not required for a table to have a PRIMARY KEY it is usually a good idea.
Primary key does not allow NULL values, but unique key allows NULL values.
We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).
PRIMARY KEY AND UNIQUE KEY are similar except it has different functions. Primary key makes the table row unique (i.e, there cannot be 2 row with the exact same key). You can only have 1 primary key in a database table.
Unique key makes the table column in a table row unique (i.e., no 2 table row may have the same exact value). You can have more than 1 unique key table column (unlike primary key which means only 1 table column in the table is unique).
INDEX also creates uniqueness. MySQL (example) will create a indexing table for the column that is indexed. This way, it's easier to retrieve the table row value when the query is queried on that indexed table column. The disadvantage is that if you do many updating/deleting/create, MySQL has to manage the indexing tables (and that can be a performance bottleneck).
Hope this helps.
Unique Keys: The columns in which no two rows are similar
Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.
Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.
The primary key is used to work with different tables. This is the foundation of relational databases. If you have a book database it's better to create 2 tables - 1) books and 2) authors with INT primary key "id". Then you use id in books instead of authors name.
The unique key is used if you don't want to have repeated entries. For example you may have title in your book table and want to be sure there is only one entry for each title.
Primary key - we can put only one primary key on a table into a table and we can not left that column blank when we are entering the values into the table.
Unique Key - we can put more than one unique key on a table and we may left that column blank when we are entering the values into the table.
column take unique values (not same) when we applied primary & unique key.
Unique Key :
More than one value can be null.
No two tuples can have same values in unique key.
One or more unique keys can be combined to form a primary key, but not vice versa.
Primary Key
Can contain more than one unique keys.
Uniquely represents a tuple.

Can Not Insert Record with NULL Value for Constrained PK (Auto-Increment) Column

I have two tables, let's call them charts and charts_tree. The charts_tree.idDir (auto-increment, integer) column is constrained to charts.chart_tree_dir. Both tables are InnoDB based.
Now I am trying to insert a row in charts_tree with null value for idDir (due to its auto-increment nature), but I am getting a foreign constrain fails error message on this column. How is this possible, considering that both tables are blank initially and there are no interconnected columns?
Is the foreign key constraint on the idDir column and references the chart_tree_dir column ?
That's what I understood from what you said ; if that's the case, when you try to insert a row in charts_tree, the auto_incremented value generated by mysql is not present in charts at the moment of creation (since both tables are blank), thus the foreign key failing.
It should be the other way around I think.

MySQL Foreign Keybut Query

I have a column that's a foreign key. Adding rows to the column is fine as long as it the row I'm adding has data that is present in the parent table. Although, some rows don't have an entry that belongs in the parent table. I'd like to keep the column with a foreign key but even if it doesn't have a parent, the column should still store it.
Are there any ways to do this within MySQL?
Regards
A foreign key constraint enforces that the value exists in the referenced table. If you try to insert a value that doesn't exist in the referenced table then it will fail.
You have two options:
Store NULL instead of the ID that doesn't exist.
Don't use a foreign key constraint.