Skip to content

Instantly share code, notes, and snippets.

@abonello
Last active March 17, 2026 17:47
Show Gist options
  • Select an option

  • Save abonello/7dea1c666af2bd606b014b48fcfe6dc4 to your computer and use it in GitHub Desktop.

Select an option

Save abonello/7dea1c666af2bd606b014b48fcfe6dc4 to your computer and use it in GitHub Desktop.
Simple database

You’re on the right track — let’s clarify these points.


1️⃣ Customer Table: Identity Column

Yes, setting Id as Identity is correct. That means SQL Server will automatically generate unique IDs when you insert new customers.

USE MyFullStackDB;  -- replace with your database name
GO

CREATE TABLE Customers (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    Name NVARCHAR(100) NOT NULL,
    Region NVARCHAR(50)
);
  • IDENTITY(1,1) → starts at 1, increments by 1
  • PRIMARY KEY → ensures uniqueness

You don’t need to do anything else for IDs; the DB will handle it automatically.


2️⃣ Orders Table: Foreign Key

To link Orders.CustomerId to Customers.Id, you create a foreign key. This is not just for querying; it enforces referential integrity in the database.

USE MyFullStackDB;  -- replace with your database name
GO

CREATE TABLE Orders (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    CustomerId INT NOT NULL,
    Product NVARCHAR(100) NOT NULL,
    Amount DECIMAL(10,2) NOT NULL,
    Status BIT NOT NULL, -- 1 = Completed, 0 = Pending
    CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerId)
        REFERENCES Customers(Id)
);
  • CustomerId INT NOT NULL → must refer to a valid customer
  • FOREIGN KEY (CustomerId) REFERENCES Customers(Id) → enforces that each order’s customer exists

Note: This is the database-level relationship. In C# EF or other ORMs, you’d define navigation properties to make it easier to query, but in raw SQL this foreign key is enough.


3️⃣ Common Gotchas

  • Make sure to create Customers table first, then Orders. Foreign key constraints require the referenced table to exist.
  • If you want to allow deletion of a customer and also delete their orders automatically, you can add ON DELETE CASCADE:
CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerId)
    REFERENCES Customers(Id)
    ON DELETE CASCADE
  • Otherwise, SQL Server will prevent deleting a customer if they have orders.

4️⃣ Querying

Once the tables are set up:

SELECT o.Id, c.Name AS CustomerName, o.Product, o.Amount, o.Status
FROM Orders o
JOIN Customers c ON o.CustomerId = c.Id;
  • This JOIN shows you the customer’s name alongside each order.
  • No ORM needed for this — it’s standard SQL.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment