Introduction
Writing SQL queries is the core skill every backend, full-stack, or data engineer must learn. SQL Server may look complicated initially, but once you understand a few foundational queries like:
SELECT
WHERE
ORDER BY
JOIN
GROUP BY
Aggregations (COUNT, SUM, AVG)
you can query almost any business database.
This article takes a practical approach. The examples are based on a real-world automotive service management system, similar to the database from Article 1. Every query comes with:
The problem scenario
How the query works
A working SQL script example
This is written for beginners but structured in a way that builds real production readiness.
Real-World Context
Our database has three tables:
Customer
CREATE TABLE Customer (
CustomerId INT PRIMARY KEY,
FullName NVARCHAR(100),
City NVARCHAR(100)
);
Car
CREATE TABLE Car (
CarId INT PRIMARY KEY,
CustomerId INT,
Brand NVARCHAR(50),
Model NVARCHAR(50),
FOREIGN KEY (CustomerId) REFERENCES Customer(CustomerId)
);
ServiceRecord
CREATE TABLE ServiceRecord (
ServiceId INT PRIMARY KEY,
CarId INT,
ServiceDate DATE,
Cost DECIMAL(10,2),
FOREIGN KEY (CarId) REFERENCES Car(CarId)
);
We will write SQL queries based on this data model.
SELECT: Retrieving Data
The SELECT command is used to fetch data from a table.
Example: Get all customers.
SELECT * FROM Customer;
While SELECT * is useful during development, in production always use explicit columns.
SELECT CustomerId, FullName, City FROM Customer;
WHERE: Filtering Records
Example: Customers from Mumbai.
SELECT FullName, City
FROM Customer
WHERE City = 'Mumbai';
You can use comparison operators:
=!=><BETWEENLIKE
Example: Find customers whose name starts with "P".
SELECT FullName
FROM Customer
WHERE FullName LIKE 'P%';
ORDER BY: Sorting Results
Sort customer list alphabetically.
SELECT FullName, City
FROM Customer
ORDER BY FullName ASC;
Sort by most recent service first:
SELECT CarId, ServiceDate, Cost
FROM ServiceRecord
ORDER BY ServiceDate DESC;
JOIN: Combining Data from Multiple Tables
JOINs allow you to read related data across tables.
INNER JOIN
Get all cars with customer names.
SELECT
Customer.FullName,
Car.Brand,
Car.Model
FROM Car
INNER JOIN Customer
ON Customer.CustomerId = Car.CustomerId;
LEFT JOIN
Get all customers even if they do not own a car.
SELECT
Customer.FullName,
Car.Brand,
Car.Model
FROM Customer
LEFT JOIN Car
ON Customer.CustomerId = Car.CustomerId;
RIGHT JOIN (Rarely Used)
SELECT *
FROM Customer
RIGHT JOIN Car
ON Customer.CustomerId = Car.CustomerId;
GROUP BY: Summarizing Data
GROUP BY is used with aggregate functions like COUNT, SUM, AVG.

Join the conversation! Your thoughts help the community grow.