1

I'm still learning how Foreign Keys work and wanted to know if a column can be null, can it be linked to a primary key?

Table Schema
users    dmca-takedown
id------->user_id (can be null)

Before you ask, user_id can be null because it's a form that can be filled out both by users and non-users. Also, I'm sure by the name of the form, you understand it's purpose as well.

Let me clarify my question: I understand the Foreign Key "can" be linked to a primary key, but will it cause constraint issues if data is null when the main table's data must not be null?

1 Answers1

1

You can declare a foreign key column as nullable. It has no effect on the referenced table.

NULLs don't match anything. So a NULL in a foreign key does not require the referenced primary key of the users table contain a row with NULL.

I feel like I have answered this before... ah yes, here it is, from January 2009 (nearly 10 years ago):

MySQL foreign key to allow NULL?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • what's SQL Antipattern? – Donald Faulknor Jan 02 '20 at 19:31
  • It's the subject of a book I authored: https://pragprog.com/book/bksqla/sql-antipatterns – Bill Karwin Jan 02 '20 at 19:35
  • Yes, I saw that. Just wondering what antipatterns are. Maybe I'll consider buying the book after I get paid. – Donald Faulknor Jan 02 '20 at 21:07
  • From the [Introduction](https://media.pragprog.com/titles/bksqla/introduction.pdf): "What is an antipattern? An antipattern is a technique that is intended to solve a problem but that often leads to other problems. An antipattern is practiced widely in different ways, but with a thread of commonality." "SQL Antipatterns describes the most frequently made missteps I’ve seen people naively make while using SQL as I’ve talked to them in technical support and training sessions, worked alongside them developing software, and answered their questions on Internet forums." – Bill Karwin Jan 02 '20 at 21:15