00:00
Free Database Course

Database Tutorial

A database is an organised collection of data that software called a database management system (DBMS) stores, protects and lets you query. This database tutorial explains how databases work, when to choose SQL or NoSQL, and how to use MySQL, PostgreSQL, Oracle, MongoDB and Cassandra from Java.

  • SQL and NoSQL
  • 6 databases covered
  • Java and Spring examples
  • Beginner to interview level

What Is a Database?

Think of a parcel-tracking service. Every scan at a depot, every change of address and every delivery photo has to be saved, found again in milliseconds and never lost, even if a server crashes halfway through an update. Writing that logic yourself on top of plain files would take years. A DBMS gives it to you: it decides how the data sits on disk, keeps indexes so lookups stay fast, runs many users' changes safely at the same time, and answers questions written in a query language.

Databases fall into two broad families. Relational (SQL) databases such as MySQL, PostgreSQL and Oracle store data in tables with a fixed structure and link them with keys. NoSQL databases such as MongoDB, Cassandra and Redis use documents, wide columns or key-value pairs, trading some of that structure for flexibility or scale.

SoftwareA DBMS
Two familiesRelational and NoSQL
Talks inSQL or native APIs
From JavaJDBC and Spring Data

What You Will Learn

  • What a database and a DBMS are, and the main types of database
  • How SQL works and how NoSQL databases differ from relational ones
  • Tables, keys, joins and constraints in MySQL
  • Documents, collections and CRUD in MongoDB
  • Where PostgreSQL, Oracle and Cassandra fit, and why
  • ACID transactions, isolation levels and indexes
  • Replication, sharding and the CAP theorem
  • Connecting to a database from Java with JDBC and Spring Data

Who this is for

Beginners meeting their first database, Java and Spring Boot developers who want to know what happens below the ORM, and engineers preparing for backend and system design interviews.

Prerequisites

None for the fundamentals. The Java examples assume you can write a small class; if not, start with the Core Java tutorial.

How an Application Uses a Database

Your code never touches the data files directly. It sends a query through a driver; the DBMS plans the cheapest way to answer it, reads or writes through its storage engine, and records every change in a log first so it can recover after a crash.

One Question, Three Ways

The parcel service needs "the five most recently updated parcels for customer 42". Here is that question in SQL, in MongoDB, and from Java.

In a relational database such as MySQL or PostgreSQL, you describe the result and the database works out how to get it:

recent-parcels.sql
SELECT tracking_no, status, updated_at
FROM parcels
WHERE customer_id = 42
ORDER BY updated_at DESC
LIMIT 5;

In MongoDB, each parcel is a document, and the same question is a filter, a projection, a sort and a limit:

mongosh
db.parcels.find(
  { customerId: 42 },
  { trackingNo: 1, status: 1, updatedAt: 1, _id: 0 }
).sort({ updatedAt: -1 }).limit(5)

From Java, plain JDBC sends the SQL with a PreparedStatement, which keeps the customer id out of the SQL text and so prevents SQL injection. The example uses a text block, so it needs Java 15 or later, and the MySQL Connector/J driver on the classpath:

RecentParcels.java
import java.sql.DriverManager;
import java.sql.SQLException;

public class RecentParcels {

    private static final String SQL = """
            SELECT tracking_no, status
            FROM parcels
            WHERE customer_id = ?
            ORDER BY updated_at DESC
            LIMIT 5""";

    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/logistics";
        try (var con = DriverManager.getConnection(url, "app", "pw");
             var ps = con.prepareStatement(SQL)) {
            ps.setLong(1, 42L);
            try (var rs = ps.executeQuery()) {
                while (rs.next()) {
                    String parcel = rs.getString("tracking_no");
                    String status = rs.getString("status");
                    System.out.println(parcel + "  " + status);
                }
            }
        }
    }
}

In a Spring Boot application you would usually let Spring Data JPA generate this query from a repository method instead. Either way, an index on (customer_id, updated_at) lets the database answer without scanning every parcel.

SQL vs NoSQL at a Glance

Neither family is better in general. The right choice depends on the shape of your data and the guarantees you need.

AspectRelational (SQL)NoSQL
Data modelTables of rows and columns, linked by keysDocuments, key-value pairs, wide columns or graphs
SchemaDefined up front and enforced by the databaseFlexible; each record can differ (optional validation in some products)
Query languageSQL, standardised across productsEach product's own API or language, such as MongoDB queries or CQL
TransactionsMulti-row ACID transactions are the normVaries: MongoDB supports multi-document ACID transactions (since 4.0); Cassandra offers lightweight transactions within one partition
ScalingUsually a bigger server plus read replicas; sharding needs extra workMany are designed to spread data across servers from the start
Good fitOrders, payments, accounts: data with clear relationshipsCatalogues, events, sessions, caches: varied or very high-volume data
ExamplesMySQL, PostgreSQL, OracleMongoDB, Cassandra, Redis, CouchDB

Read the full SQL vs NoSQL comparison

Database Concepts Interviewers Ask About

ACID

Atomicity, consistency, isolation and durability: a transaction applies fully or not at all, and survives a crash once committed.

Isolation Levels

Read uncommitted, read committed, repeatable read and serializable. MySQL's InnoDB defaults to repeatable read; PostgreSQL and Oracle default to read committed.

Indexes

Usually B-tree or B+ tree structures that turn a full scan into a few page reads, at the cost of slower writes and extra storage.

Normalisation

Splitting data so each fact is stored once, which avoids update anomalies; denormalising trades that for faster reads.

CAP Theorem

When the network splits a distributed database, it must choose between staying consistent and staying available.

Replication vs Sharding

Replication copies the same data to more servers for safety and reads; sharding splits different data across servers for scale.

Database Comparisons

Choosing between two databases? These side-by-side guides help.

Start the Database Tutorial

Every Java application eventually comes down to how well it stores and reads its data. Work through this database tutorial in order: learn the fundamentals, go deep on one relational database and one NoSQL database, then study the concepts that matter at scale. You will choose databases with confidence, write queries that stay fast as data grows, and explain your decisions clearly in interviews.