LESSON 14 OF 14

Hands-On Project: Building and Querying a Sales Database

In this final hands-on lesson, learners design a relational sales database with customer, product, order, and order-detail tables, define constraints, insert sample data, and build multi-table reports.

120 dk 106

Introduction

This lesson brings together the database design and T-SQL skills covered throughout the course in one practical project. We will create a relational sales database that stores customers, products, orders, and the individual product lines belonging to each order. We will then insert sample data, verify data integrity, and write reporting queries that could support everyday business decisions.

The purpose of the project is not simply to create several tables. You will also translate a business requirement into a relational model, define relationships correctly, choose suitable data types, prevent invalid values with constraints, and produce useful results with queries that combine several tables.

Project data model

The database contains four core tables:

  • Customers: Stores customer names, email addresses, and cities.
  • Products: Stores product names, categories, unit prices, and stock quantities.
  • Orders: Stores the customer associated with an order, its date, and its status.
  • OrderDetails: Stores the products, quantities, and selling prices included in each order.

A customer can place many orders, so Customers and Orders have a one-to-many relationship. An order can contain many products, and a product can appear in many orders. This many-to-many relationship is resolved through the OrderDetails bridge table, which separates the order header from its line items.

1. Create the database

Open a new query window in SSMS and run the following statements. If the database already exists, choose another name or execute only the sections beginning with USE.

CREATE DATABASE SalesProject14;
GO

USE SalesProject14;
GO

GO is not a Transact-SQL statement. It is a batch separator recognized by tools such as SSMS. If you do not have permission to create a database, ask a database administrator to provide the required permission or create the database for you.

2. Create tables and constraints

When tables have dependencies, create independent tables first and dependent tables afterward. Therefore, customers and products are created before orders and order details.

CREATE TABLE dbo.Customers
(
    CustomerID INT IDENTITY(1,1) NOT NULL,
    FullName NVARCHAR(100) NOT NULL,
    Email NVARCHAR(150) NOT NULL,
    City NVARCHAR(60) NULL,
    CreatedAt DATETIME2(0) NOT NULL
        CONSTRAINT DF_Customers_CreatedAt DEFAULT SYSDATETIME(),

    CONSTRAINT PK_Customers PRIMARY KEY (CustomerID),
    CONSTRAINT UQ_Customers_Email UNIQUE (Email)
);
GO

CREATE TABLE dbo.Products
(
    ProductID INT IDENTITY(1,1) NOT NULL,
    ProductName NVARCHAR(120) NOT NULL,
    Category NVARCHAR(60) NOT NULL,
    UnitPrice DECIMAL(10,2) NOT NULL,
    StockQuantity INT NOT NULL,
    IsActive BIT NOT NULL
        CONSTRAINT DF_Products_IsActive DEFAULT (1),

    CONSTRAINT PK_Products PRIMARY KEY (ProductID),
    CONSTRAINT CK_Products_UnitPrice CHECK (UnitPrice >= 0),
    CONSTRAINT CK_Products_StockQuantity CHECK (StockQuantity >= 0)
);
GO

CREATE TABLE dbo.Orders
(
    OrderID INT IDENTITY(1,1) NOT NULL,
    CustomerID INT NOT NULL,
    OrderDate DATE NOT NULL
        CONSTRAINT DF_Orders_OrderDate DEFAULT CAST(SYSDATETIME() AS DATE),
    OrderStatus NVARCHAR(20) NOT NULL
        CONSTRAINT DF_Orders_OrderStatus DEFAULT (N'New'),

    CONSTRAINT PK_Orders PRIMARY KEY (OrderID),
    CONSTRAINT FK_Orders_Customers
        FOREIGN KEY (CustomerID) REFERENCES dbo.Customers(CustomerID),
    CONSTRAINT CK_Orders_Status
        CHECK (OrderStatus IN (N'New', N'Preparing', N'Shipped', N'Completed', N'Cancelled'))
);
GO

CREATE TABLE dbo.OrderDetails
(
    OrderID INT NOT NULL,
    ProductID INT NOT NULL,
    Quantity INT NOT NULL,
    SaleUnitPrice DECIMAL(10,2) NOT NULL,

    CONSTRAINT PK_OrderDetails PRIMARY KEY (OrderID, ProductID),
    CONSTRAINT FK_OrderDetails_Orders
        FOREIGN KEY (OrderID) REFERENCES dbo.Orders(OrderID),
    CONSTRAINT FK_OrderDetails_Products
        FOREIGN KEY (ProductID) REFERENCES dbo.Products(ProductID),
    CONSTRAINT CK_OrderDetails_Quantity CHECK (Quantity > 0),
    CONSTRAINT CK_OrderDetails_SaleUnitPrice CHECK (SaleUnitPrice >= 0)
);
GO

The IDENTITY property automatically generates key values for CustomerID, ProductID, and OrderID. The OrderDetails table uses a two-column composite primary key. This prevents the same product from being inserted twice as separate lines in the same order.

The foreign key constraints prevent an order from referring to a nonexistent customer and prevent an order detail from referring to a nonexistent product. The CHECK constraints reject values that violate business rules, such as negative prices, negative stock, or zero quantities. Naming constraints clearly makes error messages and future maintenance easier.

3. Insert sample data

Insert customers and products before inserting orders. Because the identity columns begin at one, the sample order rows can refer to the generated identifiers shown by the insertion sequence.

INSERT INTO dbo.Customers (FullName, Email, City)
VALUES
    (N'Ayşe Demir', N'ayse.demir@example.com', N'Istanbul'),
    (N'Mehmet Kaya', N'mehmet.kaya@example.com', N'Ankara'),
    (N'Elif Yılmaz', N'elif.yilmaz@example.com', N'Izmir'),
    (N'Can Arslan', N'can.arslan@example.com', N'Bursa');
GO

INSERT INTO dbo.Products (ProductName, Category, UnitPrice, StockQuantity)
VALUES
    (N'Mechanical Keyboard', N'Peripherals', 1850.00, 25),
    (N'Wireless Mouse', N'Peripherals', 650.00, 60),
    (N'USB-C Dock', N'Accessories', 2400.00, 15),
    (N'27-inch Monitor', N'Monitors', 7200.00, 10),
    (N'Laptop Stand', N'Accessories', 900.00, 30);
GO

INSERT INTO dbo.Orders (CustomerID, OrderDate, OrderStatus)
VALUES
    (1, '2026-08-01', N'Completed'),
    (1, '2026-08-12', N'Shipped'),
    (2, '2026-08-03', N'Completed'),
    (3, '2026-08-18', N'New'),
    (4, '2026-08-20', N'Preparing');
GO

INSERT INTO dbo.OrderDetails (OrderID, ProductID, Quantity, SaleUnitPrice)
VALUES
    (1, 1, 1, 1850.00),
    (1, 2, 2, 650.00),
    (2, 3, 1, 2400.00),
    (2, 5, 1, 900.00),
    (3, 4, 1, 7200.00),
    (4, 2, 1, 650.00),
    (4, 5, 2, 900.00),
    (5, 1, 1, 1850.00),
    (5, 3, 1, 2400.00);
GO

It is important to store the selling price in OrderDetails.SaleUnitPrice rather than calculating every historical report from the current product price. If the product price changes later, past order totals should remain unchanged.

4. Validate the data and create reports

Display the order list

SELECT
    o.OrderID,
    c.FullName AS CustomerName,
    o.OrderDate,
    o.OrderStatus
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c
    ON c.CustomerID = o.CustomerID
ORDER BY o.OrderDate, o.OrderID;

This query replaces the customer identifier stored in the order with the customer’s readable name. Table aliases make queries easier to read, especially when several tables contain columns with similar names.

Calculate order totals

SELECT
    o.OrderID,
    c.FullName AS CustomerName,
    o.OrderDate,
    SUM(od.Quantity * od.SaleUnitPrice) AS OrderTotal
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c
    ON c.CustomerID = o.CustomerID
INNER JOIN dbo.OrderDetails AS od
    ON od.OrderID = o.OrderID
GROUP BY o.OrderID, c.FullName, o.OrderDate
ORDER BY OrderTotal DESC;

The line total is calculated as Quantity * SaleUnitPrice. SUM then adds the line totals for each order. When a query contains nonaggregate columns in the select list, those columns normally must also appear in the GROUP BY clause.

Analyze product performance

SELECT
    p.ProductName,
    SUM(od.Quantity) AS TotalQuantity,
    SUM(od.Quantity * od.SaleUnitPrice) AS Revenue
FROM dbo.Products AS p
INNER JOIN dbo.OrderDetails AS od
    ON od.ProductID = p.ProductID
INNER JOIN dbo.Orders AS o
    ON o.OrderID = od.OrderID
WHERE o.OrderStatus <> N'Cancelled'
GROUP BY p.ProductName
HAVING SUM(od.Quantity) >= 2
ORDER BY Revenue DESC;

WHERE filters individual rows before grouping. HAVING filters the groups after they have been formed. Therefore, a condition based on an aggregate value, such as total quantity being at least two, belongs in HAVING.

Find total customer spending

SELECT
    c.CustomerID,
    c.FullName,
    COUNT(DISTINCT o.OrderID) AS OrderCount,
    COALESCE(SUM(od.Quantity * od.SaleUnitPrice), 0) AS TotalSpent
FROM dbo.Customers AS c
LEFT JOIN dbo.Orders AS o
    ON o.CustomerID = c.CustomerID
   AND o.OrderStatus <> N'Cancelled'
LEFT JOIN dbo.OrderDetails AS od
    ON od.OrderID = o.OrderID
GROUP BY c.CustomerID, c.FullName
ORDER BY TotalSpent DESC;

The LEFT JOIN ensures that customers with no orders are also returned. COALESCE displays zero when the aggregate result is NULL. Placing the order-status filter in the ON clause preserves customers who do not have a qualifying order.

5. Transaction safety and stock updates

In a real application, inserting an order and reducing stock should be treated as related work. If one operation fails, the other should not remain committed by itself. The following example checks stock before reducing it.

BEGIN TRANSACTION;

DECLARE @ProductID INT = 2;
DECLARE @RequestedQuantity INT = 3;

IF EXISTS
(
    SELECT 1
    FROM dbo.Products
    WHERE ProductID = @ProductID
      AND StockQuantity >= @RequestedQuantity
      AND IsActive = 1
)
BEGIN
    UPDATE dbo.Products
    SET StockQuantity = StockQuantity - @RequestedQuantity
    WHERE ProductID = @ProductID;

    COMMIT TRANSACTION;
END
ELSE
BEGIN
    ROLLBACK TRANSACTION;
    PRINT N'Insufficient stock or the product is inactive.';
END;

This example demonstrates the basic idea of transaction-controlled changes. Production systems usually require more extensive error handling and concurrency protection so that simultaneous users cannot consume the same stock incorrectly. The key lesson is that a transaction can keep related changes consistent.

Common mistakes

  • Incorrect creation order: A table containing a foreign key cannot be created before the table it references.
  • Using an unsuitable data type: Use an exact numeric type such as DECIMAL(10,2) for monetary values instead of relying on approximate floating-point calculations.
  • Inserting identity values unnecessarily: Do not include identity columns in a normal insert column list.
  • Ignoring the composite key: If the same product should appear twice in one order, update the existing line or reconsider the model instead of violating the key.
  • Missing a join condition: An incomplete join condition can create incorrect combinations of rows and inflated totals.
  • Confusing WHERE and HAVING: Use WHERE for row-level filters and HAVING for group-level filters.
  • Recalculating historical prices: Store the actual selling price in the order detail so later product-price changes do not alter history.
  • Running UPDATE or DELETE without checking: First run a SELECT with the same predicate, and test changes inside a transaction when possible.

Short practice exercise

Complete the following tasks using your own queries:

  1. List active products whose StockQuantity is below 15.
  2. Count customers by city and return only cities with at least two customers.
  3. Display the latest order date for every customer, including customers who have never ordered.
  4. Find non-cancelled orders whose revenue exceeds 2,000.
  5. Insert a new product, create an order detail for it, and verify that the foreign key relationships remain valid.

Check whether each query returns the rows you expect. You can also deliberately try to insert an order with a nonexistent CustomerID and observe the foreign key error. Use a transaction or remove test data carefully so that temporary experiments do not remain in the project database.

Conclusion

In this final project, we designed a relational sales database from start to finish. We created tables in dependency order, defined relationships with primary and foreign keys, strengthened data integrity with UNIQUE, DEFAULT, and CHECK constraints, and inserted sample records in the correct sequence.

We then used JOINs, calculated expressions, GROUP BY, HAVING, LEFT JOIN, and COALESCE to create reports similar to those required in real sales systems. This workflow provides a strong foundation for advanced SQL Server topics such as views, stored procedures, indexes, transaction management, security, and performance optimization.

Sources