How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Here you go: USE information_schema; SELECT * FROM KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = ‘X’ AND REFERENCED_COLUMN_NAME = ‘X_id’; If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database: SELECT * FROM KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = ‘X’ AND REFERENCED_COLUMN_NAME = ‘X_id’ AND TABLE_SCHEMA = ‘your_database_name’;

What’s wrong with foreign keys?

Reasons to use Foreign Keys: you won’t get Orphaned Rows you can get nice “on delete cascade” behavior, automatically cleaning up tables knowing about the relationships between tables in the database helps the Optimizer plan your queries for most efficient execution, since it is able to get better estimates on join cardinality. FKs give a … Read more

MySQL Cannot Add Foreign Key Constraint

To find the specific error run this: SHOW ENGINE INNODB STATUS; And look in the LATEST FOREIGN KEY ERROR section. The data type for the child column must match the parent column exactly. For example, since medicalhistory.MedicalHistoryID is an INT, Patient.MedicalHistory also needs to be an INT, not a SMALLINT. Also, you should run the … Read more

How do I see all foreign keys to a table or column?

For a Table: SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = ‘<database>’ AND REFERENCED_TABLE_NAME = ‘<table>’; For a Column: SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = ‘<database>’ AND REFERENCED_TABLE_NAME = ‘<table>’ AND REFERENCED_COLUMN_NAME = ‘<column>’; Basically, we changed REFERENCED_TABLE_NAME with REFERENCED_COLUMN_NAME in the where clause.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-one: Use a foreign key to the referenced table: student: student_id, first_name, last_name, address_id address: address_id, address, city, zipcode, student_id # you can have a # “link back” if you need You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating … Read more

How can foreign key constraints be temporarily disabled using T-SQL?

If you want to disable all constraints in the database just run this code: — disable all constraints EXEC sp_MSforeachtable “ALTER TABLE ? NOCHECK CONSTRAINT all” To switch them back on, run: (the print is optional of course and it is just listing the tables) — enable all constraints exec sp_MSforeachtable @command1=”print ‘?'”, @command2=”ALTER TABLE … Read more