ALTER TABLE articles
MODIFY subcategory_id INT UNSIGNED NULL;

SET @old_fk_name := (
  SELECT CONSTRAINT_NAME
  FROM information_schema.KEY_COLUMN_USAGE
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'articles'
    AND COLUMN_NAME = 'subcategory_id'
    AND REFERENCED_TABLE_NAME = 'subcategories'
  LIMIT 1
);

SET @drop_fk_sql := IF(
  @old_fk_name IS NOT NULL,
  CONCAT('ALTER TABLE articles DROP FOREIGN KEY `', @old_fk_name, '`'),
  'SELECT 1'
);
PREPARE drop_fk_stmt FROM @drop_fk_sql;
EXECUTE drop_fk_stmt;
DEALLOCATE PREPARE drop_fk_stmt;

SET @new_fk_exists := (
  SELECT COUNT(*)
  FROM information_schema.REFERENTIAL_CONSTRAINTS
  WHERE CONSTRAINT_SCHEMA = DATABASE()
    AND CONSTRAINT_NAME = 'fk_articles_subcategory_setnull'
    AND TABLE_NAME = 'articles'
);

SET @add_fk_sql := IF(
  @new_fk_exists = 0,
  'ALTER TABLE articles ADD CONSTRAINT fk_articles_subcategory_setnull FOREIGN KEY (subcategory_id) REFERENCES subcategories(id) ON DELETE SET NULL',
  'SELECT 1'
);
PREPARE add_fk_stmt FROM @add_fk_sql;
EXECUTE add_fk_stmt;
DEALLOCATE PREPARE add_fk_stmt;
