dev.rean.me
database

09 - Create a Database and Link Customers with Orders in SQL Server

Learn how to create and select a SQL Server database, then connect customer and order tables with a foreign key and simple examples.

2026-08-28 ยท 3 min read

Share:

Hello my friend! In this lesson, we create a database in SQL Server, select it, and make two tables: Customers and Orders. A foreign key connects each order to a customer. The video is in Khmer.

1. Create and select a database

Use CREATE DATABASE to make a new database. Then select it with USE:

CREATE DATABASE ShopDB;
GO

USE ShopDB;
GO

In SQL Server Management Studio, GO tells the tool to send the statements before it as a batch.

2. Create the Customers table

Each customer needs a unique ID. We use it as the primary key:

CREATE TABLE Customers (
  CustomerID INT PRIMARY KEY,
  CustomerName NVARCHAR(100) NOT NULL,
  Email NVARCHAR(255)
);

3. Create the Orders table

Each order has its own ID and a CustomerID that refers to a customer:

CREATE TABLE Orders (
  OrderID INT PRIMARY KEY,
  CustomerID INT NOT NULL,
  OrderDate DATE NOT NULL,
  TotalAmount DECIMAL(10, 2) NOT NULL,
  FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

The foreign key helps make sure that every order belongs to a customer in the Customers table.

Add the customer first, then add an order for that customer:

INSERT INTO Customers (CustomerID, CustomerName, Email)
VALUES (1, N'Sokha', N'sokha@example.com');

INSERT INTO Orders (OrderID, CustomerID, OrderDate, TotalAmount)
VALUES (101, 1, '2026-08-28', 25.50);

Use a JOIN to show each order with its customer name:

SELECT Customers.CustomerName, Orders.OrderDate, Orders.TotalAmount
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Watch the Video

This lesson shows how to create and select a database, then make related customer and order tables.

Tips

  • Select the correct database before creating or changing tables.
  • Create the parent table (Customers) before the related table (Orders).
  • Use primary keys to identify rows and foreign keys to connect tables.
  • Insert the customer before inserting an order that refers to that customer.
  • Use sample data first, and back up important databases before making changes.