Railway reservation system database: ER diagram and SQL

A railway reservation system database in 9 tables: stations, trains and their stops, coaches and seats, the journeys a train runs, passengers, bookings by PNR and tickets. The ER diagram, what each table holds, and the SQL Server script, ready for a DBMS project or a real app and open to change in ERDsmith.

  • SQL Server
  • 9 tables
  • 11 relationships
ER diagram of the railway database: dbo.Train with dbo.TrainStop, dbo.Coach and dbo.Journey, dbo.Seat in a coach, dbo.Station, dbo.Passenger, dbo.Booking, and dbo.Ticket linked to the booking, passenger, journey, seat and two stations, with their keys and relationships.
Drawn by ERDsmith from the script below. Open it to move tables, add columns or pick the IDEF1X look preset.

The tables

Four groups hold the nine tables: the network, the trains’ coaches and seats, the runs, and the bookings.

  • dbo.StationStations by code, such as NDLS for New Delhi.
  • dbo.TrainTrains by number, such as 12002, with their name.
  • dbo.TrainStopA train's route: stop 1, 2, 3 and on, each at one station, with arrival and departure times.
  • dbo.CoachA train's coaches by code, each with its travel class.
  • dbo.SeatThe seats of a coach, each number once per coach.
  • dbo.JourneyOne run of a train on one date.
  • dbo.PassengerThe person who travels, with their birth date.
  • dbo.BookingOne reservation, found by its PNR, with a contact email.
  • dbo.TicketA passenger's seat on a journey from one station to another, with the fare and the cancellation time.

How the tables relate

  • A train has zero or more coaches , stops and journeys, and each of those belongs to exactly one train: its TrainId is NOT NULL, so the line has nothing at the train’s end .
  • A stop is keyed by (TrainId, StopNumber), a composite key, so its line from dbo.Train is solid and its box has round corners .
  • A coach has zero or more seats; a seat is in one coach.
  • A booking has zero or more tickets, so one PNR can carry a family. Each ticket names one passenger, one journey and one seat.
  • A ticket references dbo.Station twice, through FromStationId and ToStationId: two dashed lines between the same pair of tables.

Why it is built this way

A seat is sold once per journey

A filtered unique index on dbo.Ticket (JourneyId, SeatId) WHERE CancelledAt IS NULL lets a seat have many cancelled tickets and one live one on each journey. Selling seat 1 again on the same journey fails with Msg 2601; once the first ticket is cancelled, the seat sells again. The free seats of a journey are the seats of its train’s coaches with no live ticket:

SELECT c.CoachCode, s.SeatNumber
FROM dbo.Journey AS j
JOIN dbo.Coach AS c ON c.TrainId = j.TrainId
JOIN dbo.Seat AS s ON s.CoachId = c.CoachId
WHERE j.JourneyId = @JourneyId
  AND NOT EXISTS (
    SELECT 1 FROM dbo.Ticket AS t
    WHERE t.JourneyId = j.JourneyId
      AND t.SeatId = s.SeatId
      AND t.CancelledAt IS NULL
  );

The seat is held for the whole journey, not per segment: a passenger from New Delhi to Agra blocks the seat on to Bhopal as well. Selling one seat to two passengers on different legs needs the stop numbers on the ticket and a check across them.

The seat’s train is the application’s check

dbo.Ticket carries JourneyId and SeatId with a foreign key each, and nothing in the schema checks that the seat is in a coach of that journey’s train. The application checks it when it sells the ticket. The same goes for the two stations: the foreign keys’ referential integrity checks that they exist, not that they are stops of that train in that order.

One run per train per day, one stop per station

The alternate key (TrainId, DepartsOn) on dbo.Journey refuses a second run of train 12002 on the same date with Msg 2627. On dbo.TrainStop, the alternate key (TrainId, StationId) keeps a station on a train’s route once, and a repeat fails with Msg 2627 as well.

A ticket goes somewhere

The check CK_Ticket_ToStationId refuses a ticket from a station to itself with Msg 547. The PNR is an alternate key, the number the passenger quotes; BookingId is a surrogate key the tickets carry.

The SQL Server script

railway.sql · 136 linesDownload
-- Table [dbo].[Booking]
CREATE TABLE [dbo].[Booking] (
    [BookingId]    INT            IDENTITY (1, 1) NOT NULL,
    [Pnr]          CHAR (10)      NOT NULL,
    [BookedAt]     DATETIME2 (0)  NOT NULL,
    [ContactEmail] NVARCHAR (254) NOT NULL,
    CONSTRAINT [PK_Booking] PRIMARY KEY CLUSTERED ([BookingId] ASC),
    CONSTRAINT [AK_Booking_Pnr] UNIQUE NONCLUSTERED ([Pnr] ASC)
);


GO

-- Table [dbo].[Passenger]
CREATE TABLE [dbo].[Passenger] (
    [PassengerId] INT            IDENTITY (1, 1) NOT NULL,
    [FullName]    NVARCHAR (200) NOT NULL,
    [BirthDate]   DATE           NOT NULL,
    [Phone]       VARCHAR (20)   NULL,
    CONSTRAINT [PK_Passenger] PRIMARY KEY CLUSTERED ([PassengerId] ASC)
);


GO

-- Table [dbo].[Station]
CREATE TABLE [dbo].[Station] (
    [StationId] INT            IDENTITY (1, 1) NOT NULL,
    [Code]      VARCHAR (5)    NOT NULL,
    [Name]      NVARCHAR (100) NOT NULL,
    CONSTRAINT [PK_Station] PRIMARY KEY CLUSTERED ([StationId] ASC),
    CONSTRAINT [AK_Station_Code] UNIQUE NONCLUSTERED ([Code] ASC)
);


GO

-- Table [dbo].[Train]
CREATE TABLE [dbo].[Train] (
    [TrainId]     INT            IDENTITY (1, 1) NOT NULL,
    [TrainNumber] VARCHAR (10)   NOT NULL,
    [Name]        NVARCHAR (100) NOT NULL,
    CONSTRAINT [PK_Train] PRIMARY KEY CLUSTERED ([TrainId] ASC),
    CONSTRAINT [AK_Train_TrainNumber] UNIQUE NONCLUSTERED ([TrainNumber] ASC)
);


GO

-- Table [dbo].[Coach]
CREATE TABLE [dbo].[Coach] (
    [CoachId]     INT          IDENTITY (1, 1) NOT NULL,
    [TrainId]     INT          NOT NULL,
    [CoachCode]   VARCHAR (5)  NOT NULL,
    [TravelClass] VARCHAR (10) NOT NULL,
    CONSTRAINT [PK_Coach] PRIMARY KEY CLUSTERED ([CoachId] ASC),
    CONSTRAINT [CK_Coach_TravelClass] CHECK (TravelClass IN ('First', 'Second', 'Sleeper')),
    CONSTRAINT [FK_Coach_Train_TrainId] FOREIGN KEY ([TrainId]) REFERENCES [dbo].[Train] ([TrainId]),
    CONSTRAINT [AK_Coach_TrainId_CoachCode] UNIQUE NONCLUSTERED ([TrainId] ASC, [CoachCode] ASC)
);


GO

-- Table [dbo].[Journey]
CREATE TABLE [dbo].[Journey] (
    [JourneyId] INT  IDENTITY (1, 1) NOT NULL,
    [TrainId]   INT  NOT NULL,
    [DepartsOn] DATE NOT NULL,
    CONSTRAINT [PK_Journey] PRIMARY KEY CLUSTERED ([JourneyId] ASC),
    CONSTRAINT [FK_Journey_Train_TrainId] FOREIGN KEY ([TrainId]) REFERENCES [dbo].[Train] ([TrainId]),
    CONSTRAINT [AK_Journey_TrainId_DepartsOn] UNIQUE NONCLUSTERED ([TrainId] ASC, [DepartsOn] ASC)
);


GO

-- Table [dbo].[TrainStop]
CREATE TABLE [dbo].[TrainStop] (
    [TrainId]    INT      NOT NULL,
    [StopNumber] TINYINT  NOT NULL,
    [StationId]  INT      NOT NULL,
    [ArrivesAt]  TIME (0) NULL,
    [DepartsAt]  TIME (0) NULL,
    CONSTRAINT [PK_TrainStop] PRIMARY KEY CLUSTERED ([TrainId] ASC, [StopNumber] ASC),
    CONSTRAINT [FK_TrainStop_Station_StationId] FOREIGN KEY ([StationId]) REFERENCES [dbo].[Station] ([StationId]),
    CONSTRAINT [FK_TrainStop_Train_TrainId] FOREIGN KEY ([TrainId]) REFERENCES [dbo].[Train] ([TrainId]),
    CONSTRAINT [AK_TrainStop_TrainId_StationId] UNIQUE NONCLUSTERED ([TrainId] ASC, [StationId] ASC)
);


GO

-- Table [dbo].[Seat]
CREATE TABLE [dbo].[Seat] (
    [SeatId]     INT      IDENTITY (1, 1) NOT NULL,
    [CoachId]    INT      NOT NULL,
    [SeatNumber] SMALLINT NOT NULL,
    CONSTRAINT [PK_Seat] PRIMARY KEY CLUSTERED ([SeatId] ASC),
    CONSTRAINT [FK_Seat_Coach_CoachId] FOREIGN KEY ([CoachId]) REFERENCES [dbo].[Coach] ([CoachId]),
    CONSTRAINT [AK_Seat_CoachId_SeatNumber] UNIQUE NONCLUSTERED ([CoachId] ASC, [SeatNumber] ASC)
);


GO

-- Table [dbo].[Ticket]
CREATE TABLE [dbo].[Ticket] (
    [TicketId]      INT            IDENTITY (1, 1) NOT NULL,
    [BookingId]     INT            NOT NULL,
    [PassengerId]   INT            NOT NULL,
    [JourneyId]     INT            NOT NULL,
    [SeatId]        INT            NOT NULL,
    [FromStationId] INT            NOT NULL,
    [ToStationId]   INT            NOT NULL,
    [Fare]          DECIMAL (8, 2) NOT NULL,
    [CancelledAt]   DATETIME2 (0)  NULL,
    CONSTRAINT [PK_Ticket] PRIMARY KEY CLUSTERED ([TicketId] ASC),
    CONSTRAINT [CK_Ticket_Fare] CHECK (Fare >= 0),
    CONSTRAINT [CK_Ticket_ToStationId] CHECK (ToStationId <> FromStationId),
    CONSTRAINT [FK_Ticket_Booking_BookingId] FOREIGN KEY ([BookingId]) REFERENCES [dbo].[Booking] ([BookingId]),
    CONSTRAINT [FK_Ticket_Journey_JourneyId] FOREIGN KEY ([JourneyId]) REFERENCES [dbo].[Journey] ([JourneyId]),
    CONSTRAINT [FK_Ticket_Passenger_PassengerId] FOREIGN KEY ([PassengerId]) REFERENCES [dbo].[Passenger] ([PassengerId]),
    CONSTRAINT [FK_Ticket_Seat_SeatId] FOREIGN KEY ([SeatId]) REFERENCES [dbo].[Seat] ([SeatId]),
    CONSTRAINT [FK_Ticket_Station_FromStationId] FOREIGN KEY ([FromStationId]) REFERENCES [dbo].[Station] ([StationId]),
    CONSTRAINT [FK_Ticket_Station_ToStationId] FOREIGN KEY ([ToStationId]) REFERENCES [dbo].[Station] ([StationId])
);


GO

CREATE UNIQUE NONCLUSTERED INDEX [UX_Ticket_JourneyId_SeatId_Active]
    ON [dbo].[Ticket]([JourneyId] ASC, [SeatId] ASC) WHERE (CancelledAt IS NULL);


GO

Questions

What tables does a railway reservation system need?

Trains, stations, passengers and tickets at the least. The train's stops, coaches and seats, its runs by date, and bookings by PNR come next. This design has all nine.

How do I find the free seats on a train?

Take the seats of the train's coaches and keep those with no ticket on that journey where CancelledAt is NULL. The full query is under "Why it is built this way".

Why is a journey a table of its own?

Train 12002 runs every day. A ticket is for one run, so dbo.Journey holds the train and the date, and the seat's sale is unique per journey, not per train.

Can I change the design?

Yes. Open it in ERDsmith, free in the browser: add a table, rename a column, and the keys and lines follow.

Does it work with MySQL or PostgreSQL?

The script is written for SQL Server. The tables, keys and relationships carry over to other databases; the types and the filtered index need that database's own syntax.

More templates and reading