Beginner15 min read

What is a Database?

Learn why applications need databases, the difference between SQL and NoSQL, and when to use each.

Why Databases?

Every real web application needs to remember things. User accounts, blog posts, product listings, order histories, messages, settings — all of this is data, and it needs to live somewhere permanent. Without a database, your data exists only in memory — in JavaScript variables, arrays, and objects. The moment the server restarts, crashes, or redeploys, everything is gone. Every user account vanishes. Every blog post disappears. Every order is lost.

This is obviously unacceptable for any real application. Imagine if Amazon lost all orders every time they updated their website, or if your bank forgot your balance after a server restart. Databases solve this problem by persisting data to disk. When you write data to a database, it is saved permanently (or until you explicitly delete it). When the server restarts, the database still has all the data.

But databases do much more than just save data to a file. You could technically write data to a JSON file, but that falls apart quickly. Databases are specifically optimized for:

  • Storing massive amounts of data — millions or billions of records, far more than could fit in memory
  • Fast querying — finding specific records among millions in milliseconds using indexes
  • Concurrent access — handling thousands of users reading and writing data simultaneously without corruption
  • Data integrity — enforcing rules (this field must be unique, this field cannot be empty, this number must be positive)
  • Relationships — connecting related data (this comment belongs to this post, which was written by this user)
  • Backup and recovery — protecting against data loss with automated backups and point-in-time recovery
  • Transactions — ensuring that multi-step operations either complete fully or roll back entirely (transferring money between accounts should either complete both the debit and credit, or neither)

Every backend developer needs to understand databases. They are the foundation that every other feature is built on.

SQL Databases

SQL (Structured Query Language) databases — also called relational databases — are the oldest and most established type of database. They store data in tables with rows and columns, similar to a spreadsheet. Each table represents a type of data (users, posts, comments), each row is a single record, and each column is a specific piece of information (name, email, created_at).

The key characteristic of SQL databases is their strict schema. Before you can store any data, you must define the exact structure of your table: what columns it has, what type of data each column holds (text, integer, boolean, date), and what constraints apply (required, unique, references another table). This rigidity is actually a strength — it guarantees that your data is always clean and consistent. You can never accidentally store a string where a number should be, or forget to include a required field.

SQL databases are built around relationships between tables. A user has many posts. A post belongs to a user. A post has many comments. You connect tables using foreign keys — a column in one table that references the primary key of another table. To combine related data, you use JOINs in your SQL queries.

The most popular SQL databases are:

  • PostgreSQL — the most feature-rich and powerful open-source SQL database. Supports JSON, full-text search, and advanced data types. The go-to choice for most new projects.
  • MySQL — the most widely deployed SQL database in the world. Powers WordPress, Facebook, and millions of websites.
  • SQLite — a lightweight database that stores everything in a single file. Perfect for mobile apps, small projects, and prototyping.

All SQL databases are ACID compliant: Atomicity (operations complete fully or not at all), Consistency (data always follows the rules), Isolation (concurrent operations don't interfere), Durability (committed data survives crashes). This makes SQL databases the trusted choice for financial systems, inventory management, and any application where data accuracy is critical.

NoSQL Databases

NoSQL (Not Only SQL) databases emerged as an alternative to traditional relational databases. Instead of organizing data into rigid tables with fixed schemas, NoSQL databases offer flexible data models that can adapt to different types of data and use cases. The term "NoSQL" is a bit misleading — it does not mean "no SQL at all," but rather "not only SQL." Many NoSQL databases support their own query languages.

There are four main types of NoSQL databases:

Document Stores — The most popular type. Data is stored as documents, which are essentially JSON-like objects. Each document can have a completely different structure from other documents in the same collection. MongoDB is the dominant document database. Example: one user document might have a hobbies array while another has a socialLinks object — both coexist in the same collection without any schema changes.

Key-Value Stores — The simplest type. Every piece of data is stored as a key-value pair, like a giant JavaScript object or a dictionary. Extremely fast for simple lookups. Redis is the most popular key-value store, often used for caching, session storage, and real-time leaderboards.

Graph Databases — Designed for data with complex relationships. Data is stored as nodes (entities) and edges (relationships). Perfect for social networks (who follows whom), recommendation engines, and fraud detection. Neo4j is the leading graph database.

Column Stores (Wide-Column) — Store data in columns rather than rows. Optimized for queries over huge datasets where you only need specific columns. Cassandra and HBase are used by companies like Netflix and Instagram for handling billions of rows of data.

NoSQL databases excel when you need: flexible schemas that evolve over time, horizontal scaling across many servers (sharding), high write throughput for real-time applications, and when your data is naturally hierarchical or document-shaped (like JSON from APIs).

SQL vs NoSQL — When to Use Which?

Choosing between SQL and NoSQL is one of the most important architectural decisions in a project. There is no universal "better" option — each excels in different situations.

Choose SQL when:

  • Your data has clear, well-defined relationships (users have orders, orders have items)
  • Data consistency is critical (banking, inventory, healthcare)
  • You need complex queries with JOINs, aggregations, and filters
  • Your schema is unlikely to change frequently
  • You need ACID transactions (all-or-nothing operations)
  • You are building: e-commerce platforms, financial systems, CRM tools, content management systems with structured content

Choose NoSQL when:

  • Your data structure varies between records or evolves frequently
  • You need to scale horizontally across many servers
  • You are dealing with very high write throughput (IoT sensors, logging)
  • Your data is naturally document-shaped (user profiles, product catalogs with varying attributes)
  • Rapid prototyping where schema changes are constant
  • You are building: real-time analytics, content management with flexible content, social media feeds, gaming leaderboards, IoT data collection

Here is a quick comparison:

FeatureSQLNoSQL (Document)
StructureTables, rows, columnsCollections, documents
SchemaStrict, predefinedFlexible, dynamic
RelationshipsJOINs between tablesEmbedded/nested data
ScalingVertical (bigger server)Horizontal (more servers)
Query LanguageSQLDatabase-specific
Best forComplex relations, consistencyFlexibility, scale, speed

Many modern applications actually use both. For example, you might use PostgreSQL for user accounts and financial data (where consistency matters) and Redis for caching and session storage (where speed matters). This is called polyglot persistence — using the right database for each job.

SQL Table vs MongoDB Document

javascript
// ========================================
// The SAME data represented two ways
// ========================================

// --- SQL: Users Table ---
// Strict schema: every row has the same columns
// Relationships use foreign keys to link tables
//
// CREATE TABLE users (
//   id       SERIAL PRIMARY KEY,
//   name     VARCHAR(100) NOT NULL,
//   email    VARCHAR(255) UNIQUE NOT NULL,
//   age      INTEGER
// );
//
// | id | name  | email           | age |
// |----|-------|-----------------|-----|
// | 1  | Alice | alice@test.com  | 28  |
// | 2  | Bob   | bob@test.com    | 32  |
//
// To get Alice's hobbies, you'd need a SEPARATE table:
// CREATE TABLE hobbies (
//   id      SERIAL PRIMARY KEY,
//   user_id INTEGER REFERENCES users(id),
//   hobby   VARCHAR(100)
// );


// --- MongoDB: Users Collection ---
// Flexible schema: each document can have different fields
// Related data is embedded directly in the document

const usersCollection = [
  {
    _id: "64a1b2c3d4e5f6",
    name: "Alice",
    email: "alice@test.com",
    age: 28,
    hobbies: ["coding", "hiking", "reading"],  // embedded array!
    address: {                                   // embedded object!
      city: "Paris",
      country: "France"
    }
  },
  {
    _id: "64a1b2c3d4e5f7",
    name: "Bob",
    email: "bob@test.com",
    // No age field — that's OK in NoSQL!
    social: {                        // Different structure than Alice
      twitter: "@bob",
      github: "bobdev"
    }
  }
];

// Key difference: In SQL, you'd need 3 tables (users, hobbies, addresses)
// In MongoDB, everything is in one document — no JOINs needed

Which type of database stores data as JSON-like documents?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.