My use-case is to delete a row from the table only with the unique key (or Primary key) to assure that the right data is getting deleted.
I want to prevent delete queries if there are fields other than the Primary key or unique key.
Let's say 'id' is the auto-incremented primary key in my table than,
delete from my_table where id = 10
This should work but,
delete from my_table where first_name = "John"
this should be blocked for all users of MySQL. can we achieve this just with MySQL? I know, I can add multiple checks with my backend language in my logic part but I want to check if it is possible to handle on MySQL part?
Your approach is flawed because I can trick MySQL into thinking that I am using a primary key like so --
DELETE FROM table WHERE id <> 0;
In fact, MySQL does almost have such a mode. It is implemented using sql_safe_updates. Specifically:
If this variable is enabled, UPDATE and DELETE statements that do not use a key in the WHERE clause or a LIMIT clause produce an error.
The definition of "key" here may not match your definition of a key.
You can refer to the documentation for more information.
You can set this when you start the MySQL client using --safe_updates or by running:
set sql_safe_updates=1;
I have referenced a foreign key to a primary key. Whenever I click on create new project, I am storing the project Id in the reference key but I want to store multiple projects.
Can anyone please help?
Even your query is not much clear that what issue you are getting but you can understand foreign key concept as per below-
If you create a foreign key in any child table and referenced it with master table means you are saying that child table can contain a value only its reference exists in parent table.
Normally in mostly cases we want to use normalization and basic concept is that we keep unique value in master table (mostly primary key) and its child rows (multiple) in its child table.
Suppose we have two tables customer and order then customer table contains unique customer but as same customer can order multiple times, so order tables may contains multiple customers.
In your case whenever you will create a new project then a new project_id will insert in master i.e. project table and its multiple sub-attributes in its child tables. Now whats the issue you are facing. Please explain.
Is this the correct code to link two tables in a way that one-to-one Relationship in MySQL?
Table1
CREATE TABLE employees (id INT PRIMARY KEY AUTO_INCREMENT,FullName VARCHAR(50))
Table2
CREATE TABLE salary (id INT PRIMARY KEY AUTO_INCREMENT,SalaryNumber VARCHAR(6))
ALTER TABLE salary
ADD FOREIGN KEY (id) REFERENCES employees (id)
ON DELETE CASCADE
ON UPDATE CASCADE
Your example has a number of problems, first of which is that you're linking two non-related auto-incrementing ids. This is a nightmare waiting to happen. If anything happens to get those two ids out of sync, you're dead in the water.
In your example, the 'employees' record would be considered the parent record, upon which the 'salary' record is dependent (i.e. - you might have an employee record without a corresponding salary record, but you wouldn't want a salary record that's not associated with an employee).
Foreign key constraints belong in the child table, as stated in the MySql documentation. As such, what you need in the 'salary' table is a column that looks like this:
EmployeeId INT NOT NULL
Your foreign key would be
ALTER TABLE salary
ADD FOREIGN KEY (EmployeeId) REFERENCES employee (id)
ON DELETE CASCADE
ON UPDATE CASCADE
At this point, you still have a many-to-one relationship, as there is nothing to prevent you from inserting multiple entries into the salary table with the same EmployeeId.
To make this relationship one-to-one, you have to create a unique index on the salary.EmployeeId column.
With this type of relationship, it's important to note that:
you are prevented from inserting a row into salary that doesn't have valid EmployeeId
you are prevented from inserting a row into salary that has a duplicate EmployeeId
when you delete a salary record, the employee record remains untouched.
deleting the employee record results in the deletion of the salary record it is referencing (if you don't want this behavior, change ON DELETE CASCADE to something else)
you are prevented from dropping the employee table until the salary table is empty and dropped.
No, that's a one-to-many relationship. You can have any number of salary rows (including none) linking to a single employee row.
Since the salary is very much an attribute dependent on the employee, I would consider placing it in the employee table itself (unless you have some extra knowledge you haven't shared with us which makes this problematic).
There are ways to enforce one-to-one across separate tables.
For example, you can use triggers to stop duplicates, though some people are adverse to triggers, and this still won't prevent one-to-zero mappings from appearing.
Alternatively, you can use bidirectional foreign keys with a dummy row in both tables (pointing to each other) to allow you to insert in one table at a time.
The way this is done is to insert a row in employees pointing to the dummy salary row.
Then insert the salary row pointing to the newly inserted employee.
Then update the employee row to pint to the newly inserted salary row. All this should happen as a single transaction of course, to maintain referential integrity at the application level.
In order to get the dummy rows in, they'll need to be inserted before the foreign key constraints are added to the schema, otherwise you have a chicken-and-egg situation.
Whether that level of work is actually necessary is debatable, especially when you can enforce one-to-one simply by combining the data into a single table as suggested :-)
I may have either misunderstood how to use the ON DUPLICATE KEY syntax, alternatively my database structure needs some work but here goes.
I have a table (bookings-meta) which represents meta data associated with another table (bookings) , different rows in the bookings table may or may not have specific meta data associated with them in the other table.
The bookings-meta table has the following columns, meta_id (primary key), booking_id, key and value.
From my understanding, to use ON DUPLICATE KEY I need to know what in this case is the meta_id, often this isn't the case, I'm trying to simply push a key, value pair to the table using the booking_id, so if the particular key exists then its replaced otherwise its inserted.
At the moment I have a seperate query to try to select the row, if its found then I UPDATE, if not then its an INSERT.
Is there a way of doing an insert/update in one query without using ON DUPLICATE KEY or have I missed a trick with this one?
If possible, I'd drop the meta_id column entirely and turn booking_id and key into a composite primary key. That'll save space in your table, allow use of ON DUPLICATE KEY, and be cleaner in general.
I'm setting up a database using phpMyAdmin. I have two tables (foo and bar), indexed on their primary keys. I am trying to create a relational table (foo_bar) between them, using their primary keys as foreign keys.
I created these tables as MyISAM, but have since changed all three to InnoDB, because I read that MyISAM doesn't support foreign keys. All id fields are INT(11).
When I choose the foo_bar table, click the "relation view" link, and try to set the FK columns to be database.foo.id and database.bar.id, it says "No index defined!" beside each column.
What am I missing?
Clarification/Update
For the sake of simplicity, I want to keep using phpMyAdmin. I am currently using XAMPP, which is easy enough to let me focus on the PHP/CSS/Javascript, and it comes with phpMyAdmin.
Also, although I haven't been able to set up explicit foreign keys yet, I do have a relational table and can perform joins like this:
SELECT *
FROM foo
INNER JOIN foo_bar
ON foo.id = foo_bar.foo_id
INNER JOIN bar
ON foo_bar.bar_id = bar.id;
It just makes me uncomfortable not to have the FKs explicitly defined in the database.
If you want to use phpMyAdmin to set up relations, you have to do 2 things. First of all, you have to define an index on the foreign key column in the referring table (so foo_bar.foo_id, in your case). Then, go to relation view (in the referring table) and select the referred column (so in your case foo.id) and the on update and on delete actions.
I think foreign keys are useful if you have multiple tables linked to one another, in particular, your delete scripts will become very short if you set the referencing options correctly.
EDIT: Make sure both of the tables have the InnoDB engine selected.
phpMyAdmin lets you define foreign keys using their "relations" view. But since, MySQL only supports foreign constraints on "INNO DB" tables, the first step is to make sure the tables you are using are of that type.
To setup a foreign key so that the PID column in a table named CHILD references the ID column in a table named PARENT, you can do the following:
For both tables, go to the operations tab and change their type to "INNO DB"
Make sure ID is the primary key (or at least an indexed column) of the PARENT table.
In the CHILD table, define an index for the PID column.
While viewing the structure tab of the CHILD table, click the "relation view" link just above the "add fields" section.
You will be given a table where each row corresponds to an indexed column in your CLIENT table. The first dropdown in each row lets you choose which TABLE->COLUMN the indexed column references. In the row for PID, choose PARENT->ID from the dropdown and click GO.
By doing an export on the CHILD table, you should see a foreign key constraint has been created for the PID column.
This is a summary of a Wikipedia article. It specifies the different types of relationships you can stipulate in PHPmyadmin. I am putting it here because it is relevant to #Nathan's comment on setting the foreign keys options for "on update/delete" but is too large for a comment.
CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).
RESTRICT
A value cannot be updated or deleted when a row exists in a foreign key table that references the value in the referenced table. Similarly, a row cannot be deleted as long as there is a reference to it from a foreign key table.
NO ACTION
NO ACTION and RESTRICT are very much alike. The main difference between NO ACTION and RESTRICT is that with NO ACTION the referential integrity check is done after trying to alter the table. RESTRICT does the check before trying to execute the UPDATE or DELETE statement. Both referential actions act the same if the referential integrity check fails: the UPDATE or DELETE statement will result in an error.
SET NULL
The foreign key values in the referencing row are set to NULL when the referenced row is updated or deleted. This is only possible if the respective columns in the referencing table are nullable. Due to the semantics of NULL, a referencing row with NULLs in the foreign key columns does not require a referenced row.
SET DEFAULT
Similar to SET NULL, the foreign key values in the referencing row are set to the column default when the referenced row is updated or deleted.
In phpmyadmin, you can assign Foreign key simply by its GUI. Click on the table and go to Structure tab. find the Relation View on just bellow of table (shown in below image).
You can assign the forging key from the list box near by the primary key.(See image below). and save
corresponding SQL query automatically generated and executed.
For those new to database .... and need to ALTER an existing table. A lot things seem to be pretty straightforward, but there is always something ... between A and B.
Before anything else, take a look at this.
Make sure you have P_ID (parent ID on both parent and child table).
Of course it will be already filled in the parent. Not necessarily in the child in a true and final way. So for instance P_ID #3 (maybe many times in the child table will be pointing to original P_ID at parent table).
Go to SQL tab (I am using phpMyAdmin, should be similar in other ones) and do this command:
ALTER TABLE child_table_name
ADD FOREIGN KEY (P_ID)
REFERENCES parent_table_name (P_ID)
Click on child table, than structure, finally on relational view. Finish your DB planning there. There was a nice answer before this one about cascade, restrict, etc.
Of course it could be done by commands...
Foreign key means a non prime attribute of a table referes the prime attribute of another
*in phpMyAdmin* first set the column you want to set foreign key as an index
then click on RELATION VIEW
there u can find the options to set foreign key
InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:
ALTER TABLE tbl_name
ADD [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!
Don't forget that the two columns should have the same data type.
for example if one column is of type INT and the other is of type tinyint you'll get the following error:
Error creating foreign key on [PID column] (check data types)
This is old thread but answer because if useful to anyone.
Step 1. Your Db Storage Engine set to InnoDB
Step 2. Create Primary Table
here customer is primary table and customer_id is primary key
Step 3. create foreign key table and give index
here we have customer_addresses as related table and store customer addresses, so here customer_id relation with customer table
we can select index directly when create table as below
If you forgot to give index when create a table, then you can give index from the structure tab of table as below.
Step 4. Once index give to the field, Go to structure tab and click on Relation View as shown in below pic
Step 5. Now select the ON DELETE and ON UPDATE what you want to do, Select column from current table, select DB (SAME DB), select relation table and primary key from that table as shown in below pic and Save it
Now check if relation are give successfully, go to foreign table data list and click on foreign key value, you will redirect to primary table record, then relation made successfully.
Make sure you have selected your mysql storage engine as Innodb and not MYISAM as Innodb storage engine supports foreign keys in Mysql.
Steps to create foreign keys in phpmyadmin:
Tap on structure for the table which will have the foreign key.
Create INDEX for the column you want to use as foreign key.
Tap on Relation view, placed below the table structure
In the Relation view page, you can see select options in front of the field (which was made an INDEX).
UPDATE CASCADE specifies that the column will be updated when the referenced column is updated,
DELETE CASCADE specified rows will be deleted when the referenced rows are deleted.
Alternatively, you can also trigger sql query for the same
ALTER TABLE table_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (foreign_key_name)
REFERENCES target_table(target_key_name);
Step 1:
You have to add the line:
default-storage-engine = InnoDB
under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service.
Step 2:
Now when you create the table you will see the type of table is: InnoDB
Step 3:
Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key:
Select the Index Key from Action Label as shown below.
Step 4:
Now open the Relation View in the same child table from bottom near the Print View as shown below.
Step 5:
Select the column U like to have the Foreign key as Select the Parent column from the drop down.
dbName.TableName.ColumnName
Select appropriate Values for ON DELETE and ON UPDATE
First set Storage Engine as InnoDB
then the relation view option enable in structure menu
You can also do it with a SQL command, like so.
ALTER TABLE employees
ADD CONSTRAINT fk_companyid FOREIGN KEY (companyid)
REFERENCES companies (id)
ON DELETE CASCADE;
In this example, if a row from companies is deleted, all employees with that companyid are also deleted.
From the official MySQL documentation at https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan.