Database Tutorial

Database Tutorial

A beginner-friendly guide to databases, SQL, NoSQL, CRUD, relationships, backend integration and security.

28th August, 2026

1. What is a Database?

A database is a system for storing and organizing information so that an application can efficiently save, find, update, and delete data.

Example: A shopping website may need to store users, products, orders, payments and reviews.
Example Users Table
IDNameEmail
1Rahulrahul@gmail.com
2Priyapriya@gmail.com
3Amanaman@gmail.com

For example, the backend can ask:

Give me the user whose ID is 2.

The database can return:

Priya | priya@gmail.com

Why not just use files?

You could store data in JSON, but as an application grows:

  • Finding data becomes slower.
  • Multiple users may modify data simultaneously.
  • Relationships become difficult to manage.
  • Security becomes harder.
  • Data consistency becomes a problem.
  • Large amounts of data are difficult to handle.
Key idea: Databases solve these problems.

2. Database Fundamentals

SQL / Relational

Uses tables and relationships.

Examples: MySQL, PostgreSQL, Microsoft SQL Server.

NoSQL

Uses flexible data structures such as documents.

Example: MongoDB.

Important: A database stores data; a database management system (DBMS) provides the tools to work with that data.

3. SQL vs NoSQL

SQL

SQL stands for Structured Query Language. SQL databases generally organize information into tables.

UsersNameEmail
1Rahulrahul@gmail.com
2Priyapriya@gmail.com
3Amanaman@gmail.com

Creating a table

CREATE TABLE users (
                                                    id INT PRIMARY KEY,
                                                    name VARCHAR(100),
                                                    email VARCHAR(255)
                                                );

SQL is particularly useful when:

  • Data has a clear structure.
  • Relationships between data are important.
  • You need complex queries.
  • Data consistency is critical.

Popular SQL databases

MySQL
PostgreSQL
Microsoft SQL Server
Oracle Database
Remember: SQL = old and NoSQL = new is incorrect. Both are useful; choose based on application requirements.

4. NoSQL

NoSQL databases do not necessarily organize data into traditional tables. MongoDB, for example, stores documents.

{
                                                "_id": 1,
                                                "name": "Rahul",
                                                "email": "rahul@gmail.com",
                                                "age": 22
                                                }

Another document can contain different fields:

{
                                                "_id": 2,
                                                "name": "Priya",
                                                "email": "priya@gmail.com",
                                                "skills": ["JavaScript", "React"]
                                                }
SQL NoSQL
TablesDocuments / collections
Fixed / defined schemaFlexible schema
SQL queriesDatabase-specific query APIs/languages
Strong relational modelOften optimized for flexible/document data
Great for complex relationshipsGreat for flexible structures
MySQL, PostgreSQLMongoDB

5. Tables, Records, and Relationships

These concepts are extremely important for SQL databases.

IDNameEmail
1Rahulrahul@gmail.com
2Priyapriya@gmail.com

Table

A table organizes related data into rows and columns.

Record / Row

Each individual entry is a record, commonly called a row.

Column

A column represents a particular type of information such as id, name or email.

6. Primary Keys

A primary key uniquely identifies a record. For example, id might be the primary key.

CREATE TABLE users (
                                                    id INT PRIMARY KEY,
                                                    name VARCHAR(100),
                                                    email VARCHAR(255)
                                                );
Two users should not have the same ID.

7. Relationships

One user can make many orders. This is a One-to-Many relationship.

Rahul | |---- Order #101 | |---- Order #102 | |---- Order #103

Foreign Keys

IDUser IDTotal
10115000
10213000
10327000

user_id points to the user's ID and is called a foreign key.

users.id ↑ | orders.user_id

8. Types of Relationships

One-to-One

One person has one passport.

Person ---- Passport

One-to-Many

One customer has many orders.

Customer ----< Orders

Many-to-Many

Students can enroll in many courses, and courses can have many students.

Students >----< Courses

Junction / Link Table

A many-to-many relationship is usually implemented using a junction table.

Student IDCourse ID
1101
1102
2101

9. CRUD Operations

C
Create
R
Read
U
Update
D
Delete

Create

INSERT INTO users (name, email)
                                                VALUES ('Rahul', 'rahul@gmail.com');

Read

SELECT * FROM users;

                                                SELECT * FROM users
                                                WHERE id = 1;

Update

UPDATE users
                                                SET email = 'newemail@gmail.com'
                                                WHERE id = 1;

Delete

DELETE FROM users
                                                WHERE id = 1;
HTTPDatabase Operation
POSTCREATE
GETREAD
PUT / PATCHUPDATE
DELETEDELETE

10–13. MySQL, PostgreSQL and MongoDB

MySQL

MySQL is one of the most widely used relational databases.

Frontend | | HTTP request ↓ Backend | | SQL query ↓ MySQL

PostgreSQL

PostgreSQL is another major relational database.

SELECT * FROM users;

                                                INSERT INTO users (name, email)
                                                VALUES ('Rahul', 'rahul@gmail.com');

                                                UPDATE users
                                                SET name = 'Rahul Sharma'
                                                WHERE id = 1;

MongoDB

MongoDB stores data as documents in collections.

{
                                                "_id": "123",
                                                "name": "Rahul",
                                                "email": "rahul@gmail.com",
                                                "skills": [
                                                    "JavaScript",
                                                    "Node.js",
                                                    "React"
                                                ]
                                                }

MongoDB CRUD

// Create
                                                db.users.insertOne({
                                                    name: "Rahul",
                                                    email: "rahul@gmail.com"
                                                });

                                                // Read
                                                db.users.find();

                                                // Find one
                                                db.users.findOne({
                                                    name: "Rahul"
                                                });

                                                // Update
                                                db.users.updateOne(
                                                    { name: "Rahul" },
                                                    { $set: { age: 22 } }
                                                );

                                                // Delete
                                                db.users.deleteOne({
                                                    name: "Rahul"
                                                });

14–15. Connecting a Database to a Backend

The frontend should normally communicate with a backend rather than connecting directly to the database.

Internet | ↓ Frontend | | HTTP / API ↓ Backend Server | | Database Driver ↓ Database
Why? Putting database credentials in frontend code would expose them to users.

Example Backend Flow

POST /users

                                                {
                                                "name": "Rahul",
                                                "email": "rahul@gmail.com"
                                                }
app.post("/users", async (req, res) => {
                                                    const { name, email } = req.body;

                                                    // Save user to database

                                                    res.json({
                                                        message: "User created"
                                                    });
                                                });

The backend can then execute:

INSERT INTO users (name, email)
                                                VALUES ('Rahul', 'rahul@gmail.com');
User ↓ Frontend ↓ HTTP request ↓ Backend ↓ SQL / MongoDB query ↓ Database ↓ Backend ↓ JSON response ↓ Frontend ↓ User

16–20. Database Security

1. Never expose database credentials

Keep credentials on the server.

DATABASE_URL=...
                                                DATABASE_PASSWORD=...

2. Hash passwords

Never store plain-text passwords.

password = "rahul123"

Store a secure password hash instead. Common tools include bcrypt and Argon2.

3. Prevent SQL Injection

Do not blindly concatenate user input into SQL.

const result = await db.query(
                                                    "SELECT * FROM users WHERE email = $1",
                                                    [email]
                                                );

4. Validate Input

  • Is age a number?
  • Is email actually an email?
  • Is name present?
  • Is the string too long?
  • Is the value allowed?

Authentication vs Authorization

Authentication

Who are you?

Example: email + password → You're Rahul.

Authorization

What are you allowed to do?

Example: a regular user may view products but not delete another user's account.

Other Important Security Practices

Encryption: Use encrypted connections such as TLS/HTTPS.
Least privilege: Give database accounts only the permissions they need.
Backups: Maintain backups and test restoration.
Indexes: Improve query performance, but use them carefully.
Transactions: Allow related operations to succeed or fail together.

Example Index

CREATE INDEX idx_users_email
                                                ON users(email);

Example Transaction

Subtract ₹100 from A + Add ₹100 to B → Both should succeed or fail together.

21. Putting Everything Together

Imagine building an e-commerce application.

E-Commerce App | +-------------------+ | | Frontend Backend React/etc. Node/Express | +-------+-------+ | | Auth Database | +-----+------+ | | PostgreSQL Redis/etc.

Possible Database Tables

users

id, name, email, password_hash

products

id, name, price, stock

orders

id, user_id, total, status

order_items

id, order_id, product_id, quantity, price

Example API

POST   /users
                                                GET    /users/:id
                                                PATCH  /users/:id
                                                DELETE /users/:id

                                                GET    /products
                                                POST   /products

                                                POST   /orders
                                                GET    /orders/:id

22. What You Should Learn in Order

Database, Table, Row / Record, Column, Primary Key, Foreign Key and Schema.

SELECT, INSERT, UPDATE, DELETE, WHERE, ORDER BY, GROUP BY, HAVING, JOIN, INNER JOIN, LEFT JOIN, COUNT, SUM, AVG, MAX and MIN.

Relationships, normalization, constraints, indexes and transactions.

Build real databases and practice writing queries.

Collections, documents, embedding, references, queries, indexes and aggregation.

Node.js, Express, database drivers, ORMs, environment variables, connection pools and REST APIs.

Password hashing, authentication, authorization, SQL injection prevention, input validation, HTTPS, secrets management, backups, transactions and database permissions.

23. The Big Picture

USER | ↓ FRONTEND | | HTTP ↓ BACKEND | +----------------------+ | | Business Logic Authentication / Authorization | ↓ DATABASE | +----------------+ | | Data Relationships

Remember These Five Ideas

1. Database → stores application data.
2. SQL → lets you work with relational data.
3. Tables / Records / Relationships → organize relational data.
4. CRUD → Create, Read, Update, Delete.
5. Backend → acts as the secure middle layer between your frontend and database.