Relationships in SQL on the same table

sql, sql-server, t-sql

Solution

I would think that `ParentCategoryID` would have to be `NULL`able (unless you want a top-level parent to point to itself, and that doesn't make much sense).

ALTER TABLE dbo.Categories
  ADD CONSTRAINT FK_SelfParent
  FOREIGN KEY (ParentCategoryID)
  REFERENCES dbo.Categories(CategoryID);

True story: at a job interview at Microsoft (several years ago), a SQL Server person told me that this wasn't possible.

Problem

I haven't ever really used foreign keys in my databases, I have always just written code that would enforce things for me, but I'm looking towards shifting some of that logic to the database and learning more about foreign keys. I currently have a database which has the table `Categories`: ``` CREATE TABLE [dbo].[Categories]( [CategoryID] [bigint] IDENTITY(1,1) NOT NULL, [ParentCategoryID] [bigint] NOT NULL, [CategoryStatus] [bit] NOT NULL, [CategoryTitle] [varchar](64) NOT NULL, [CategorySlug] [varchar](64) NOT NULL, [CategoryThumbnail] [varchar](128) NULL, [CategoryHeaderImage] [varchar](128) NULL, [CategoryDescription] [text] NULL, CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED ( [CategoryID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY], CONSTRAINT [UI_Categories_Slug] UNIQUE NONCLUSTERED ( [CategorySlug] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] ``` I would like to create a foreign key that relates `ParentCategoryID` back up to `CategoryID`. When creating the FK, which would be the primary column, and which would be the foreign column in this instance?

Original source