00:00

What Is SQL?

Last updated:

SQL is the language used to work with relational databases. Developers, analysts and administrators use it every day to create tables, add and change data, and ask questions about that data. Even if you plan to use MongoDB, knowing SQL helps you understand where document databases differ and why.

This tutorial explains what SQL is, where it came from, the five groups of SQL commands, and the most important query features, all using one small bookstore example.

1. What Is SQL?

SQL (Structured Query Language) is a standard language for defining, querying and changing data in a relational database, where data lives in tables of rows and columns. It is usually pronounced "S-Q-L" or "sequel".

SQL is declarative: you describe what result you want, and the database's query optimizer decides how to get it, for example which index to use or in which order to join tables.

SQL
-- "Give me the titles of Java books under 600, cheapest first"
SELECT title, price
FROM   books
WHERE  category = 'Java' AND price < 600
ORDER  BY price;

2. A Short History

  • 1970: Edgar F. Codd at IBM publishes the relational model of data.
  • Mid-1970s: IBM researchers build a language for it, first called SEQUEL, later renamed SQL.
  • 1979: the first commercial SQL database (later known as Oracle) is released.
  • 1986–1987: SQL becomes an ANSI and ISO standard.
  • Since then: the standard has been revised many times, adding features such as window functions, JSON support and property-graph queries.

Every major relational database speaks SQL, but each adds its own extensions, called a dialect: MySQL, PostgreSQL, Oracle (PL/SQL), SQL Server (T-SQL) and SQLite differ in details such as date functions and procedural code.

3. The Sample Tables

The examples below use three related tables for an online bookstore:

schema.sql
CREATE TABLE customers (
  customer_id  INT          PRIMARY KEY,
  name         VARCHAR(100) NOT NULL,
  email        VARCHAR(150) NOT NULL UNIQUE,
  city         VARCHAR(60)
);

CREATE TABLE books (
  book_id   INT           PRIMARY KEY,
  title     VARCHAR(200)  NOT NULL,
  category  VARCHAR(50),
  price     DECIMAL(8,2)  NOT NULL CHECK (price > 0)
);

CREATE TABLE orders (
  order_id     INT           PRIMARY KEY,
  customer_id  INT           NOT NULL REFERENCES customers(customer_id),
  total        DECIMAL(10,2) NOT NULL,
  status       VARCHAR(20)   NOT NULL DEFAULT 'PENDING',
  created_at   TIMESTAMP     NOT NULL
);

4. The Five Groups of SQL Commands

SQL statements are usually grouped by what they do:

GroupPurposeMain commands
DDL – Data Definition LanguageCreate and change the structureCREATE, ALTER, DROP, TRUNCATE
DML – Data Manipulation LanguageAdd, change and remove rowsINSERT, UPDATE, DELETE
DQL – Data Query LanguageRead dataSELECT
DCL – Data Control LanguageManage permissionsGRANT, REVOKE
TCL – Transaction Control LanguageGroup changes into transactionsBEGIN, COMMIT, ROLLBACK, SAVEPOINT

DDL: define the structure

DDL
ALTER TABLE customers ADD COLUMN phone VARCHAR(20);
CREATE INDEX idx_orders_customer ON orders (customer_id);
DROP TABLE IF EXISTS old_reports;

DML: change the data

DML
INSERT INTO customers (customer_id, name, email, city)
VALUES (1, 'Aditi Rao', 'aditi@example.com', 'Pune');

UPDATE books SET price = price * 0.9 WHERE category = 'Java';

DELETE FROM orders WHERE status = 'CANCELLED';
An UPDATE or DELETE without a WHERE clause affects every row in the table. Run the matching SELECT first to see which rows will change.

DQL: read the data

DQL
SELECT name, city FROM customers WHERE city IN ('Pune', 'Lisbon');

DCL: control access

DCL
GRANT SELECT, INSERT ON orders TO reporting_app;
REVOKE INSERT ON orders FROM reporting_app;

TCL: transactions

A transaction groups statements so that either all of them succeed or none do. Moving money between accounts is the classic example:

TCL
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE account_id = 'A';
UPDATE accounts SET balance = balance + 500 WHERE account_id = 'B';
COMMIT;   -- or ROLLBACK; to undo both changes

5. Joining Tables

Because related data is split across tables, a JOIN brings it back together using matching keys:

JOIN
-- Every shipped order with the customer's name
SELECT c.name, o.order_id, o.total
FROM   orders o
INNER  JOIN customers c ON c.customer_id = o.customer_id
WHERE  o.status = 'SHIPPED';

-- Every customer, including those with no orders yet
SELECT c.name, o.order_id
FROM   customers c
LEFT   JOIN orders o ON o.customer_id = c.customer_id;
Join typeReturns
INNER JOINOnly rows that match in both tables
LEFT JOINAll rows from the left table, plus matches from the right (or NULL)
RIGHT JOINAll rows from the right table, plus matches from the left
FULL OUTER JOINAll rows from both tables, matched where possible
CROSS JOINEvery combination of rows (rarely what you want)

6. Grouping and Aggregation

Aggregate functions such as COUNT, SUM, AVG, MIN and MAX summarize many rows. GROUP BY splits rows into groups, and HAVING filters the groups:

GROUP BY
-- Revenue per city, only for cities above 10,000
SELECT   c.city, COUNT(*) AS orders, SUM(o.total) AS revenue
FROM     orders o
JOIN     customers c ON c.customer_id = o.customer_id
WHERE    o.status = 'SHIPPED'
GROUP BY c.city
HAVING   SUM(o.total) > 10000
ORDER BY revenue DESC;

SQL evaluates the clauses of a query in a logical order that differs from the written order: FROM and JOIN, then WHERE, GROUP BY, HAVING, SELECT, ORDER BY and finally LIMIT. That is why you cannot use a SELECT alias inside WHERE.

7. Constraints Keep Data Correct

ConstraintGuarantees
PRIMARY KEYEach row has a unique, non-null identifier
FOREIGN KEY / REFERENCESA value must exist in the referenced table
UNIQUENo two rows share the value
NOT NULLThe column must have a value
CHECKThe value satisfies a condition, such as price > 0
DEFAULTA value is filled in when none is given

8. SQL and MongoDB

MongoDB does not use SQL. It uses the MongoDB Query API, where queries are themselves documents. The ideas map closely, which makes moving between the two easier:

SQLMongoDB (mongosh)
SELECT * FROM books WHERE price < 500db.books.find({ price: { $lt: 500 } })
INSERT INTO books VALUES (…)db.books.insertOne({ … })
UPDATE books SET stock = 0 WHERE _id = 103db.books.updateOne({ _id: 103 }, { $set: { stock: 0 } })
DELETE FROM orders WHERE status = 'CANCELLED'db.orders.deleteMany({ status: "CANCELLED" })
GROUP BY with SUMAggregation pipeline with $group and $sum
JOIN$lookup stage, or embedding related data in one document

9. Summary

  • SQL is the standard, declarative language for relational databases.
  • Its commands fall into five groups: DDL, DML, DQL, DCL and TCL.
  • Joins combine related tables; GROUP BY and aggregate functions summarize data; constraints protect data quality.
  • Each database has its own SQL dialect on top of the standard.
  • MongoDB uses its own query API instead of SQL, but most SQL ideas have a direct MongoDB equivalent.