Skip to content

SQL-145 How to Fix Error 1064 When Using ALTER TABLE ADD CONSTRAINT in MySQL #358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Drop the constraint so that we can add it back
ALTER TABLE specification
DROP FOREIGN KEY specification_program_id_fkey;
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Correct syntax
ALTER TABLE specification
ADD CONSTRAINT specification_program_id_fkey
FOREIGN KEY (program_id)
REFERENCES program (id);

# Incorrect syntax; jumbled syntax
ALTER TABLE specification
ADD FOREIGN KEY specification_program_id_fkey
CONSTRAINT(program_id)
REFERENCES program(id);

# Incorrect syntax; wrong punctuation
ALTER TABLE specification (
ADD CONSTRAINT
specification_program_id_fkey
FOREIGN KEY(program_id)
REFERENCES program (id)
);

# Incorrect syntax; a reserved word
ALTER TABLE specification
ADD CONSTRAINT foreign
FOREIGN KEY (program_id)
REFERENCES program (id);

# Incorrect syntax, misspelled keyword REFERENCES
ALTER TABLE specification
ADD CONSTRAINT specification_program_id_fkey
FOREIGN KEY(program_id)
REFERENCE program (id);

# Incorrect syntax, missing closing parenthesis
ALTER TABLE specification
ADD CONSTRAINT specification_program_id_fkey
FOREIGN KEY(program_id
REFERENCES program (id);

# Incorrect syntax; quotes
ALTER TABLE "specification"
ADD CONSTRAINT specification_program_id_fkey
FOREIGN KEY("program_id")
REFERENCES program ("id");

# Correct syntax; backticks
ALTER TABLE `specification`
ADD CONSTRAINT specification_program_id_fkey
FOREIGN KEY(`program_id`)
REFERENCES program (`id`);

# Incorrect syntax, missing required elements
ALTER TABLE specification
ADD CONSTRAINT specification_program_id_fkey
FOREIGN KEY(program_id);
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# List the FK constraints that reference the PROGRAM table
SELECT
TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = (SELECT DATABASE()) AND
REFERENCED_TABLE_NAME = 'PROGRAM' \G