Database Basics for Next.js Developers
Database, structured గా data store చేసి, efficient గా retrieve చేయడానికి design చేయబడిన system. Next.js apps లో, users, courses, orders లాంటి persistent data ni database లోనే store చేస్తారు (files లో కాదు).
Relational database (PostgreSQL, MySQL) లో, data tables గా organize అవుతుంది — spreadsheet లాంటిదే, rows and columns తో:
| Term | Meaning |
|---|---|
| Table | Related data collection (e.g., "users", "courses") |
| Row | ఒక్క record (e.g., ఒక్క user) |
| Column | ఒక్క field (e.g., "email", "name") |
| Primary Key | Prathi row ki unique identifier (usually "id") |
| Foreign Key | ఒక table నుండి వేరే table row ని reference చేసే column |
Real apps లో, tables ఒకదానితో ఒకటి connect అయ్యి ఉంటాయి:
- One-to-Many: ఒక్క User, chాలా Orders కలిగి ఉండొచ్చు.
- Many-to-Many: ఒక్క Course, chాలా Students కి; ఒక్క Student, chాలా Courses కి enroll అవ్వొచ్చు.
- One-to-One: ఒక్క User, ఒక్కటే Profile కలిగి ఉంటుంది.
| Feature | Relational (PostgreSQL, MySQL) | NoSQL (MongoDB) |
|---|---|---|
| Structure | Fixed tables, columns, strict schema | Flexible documents (JSON-like) |
| Relationships | Strong (foreign keys, joins) | Weaker, often duplicated data |
| Best For | Structured data, complex queries (e-commerce, SaaS) | Rapidly changing schemas, large-scale unstructured data |
| Next.js Popular Choice | PostgreSQL + Prisma | MongoDB + Mongoose |
Database (PostgreSQL, MySQL) actual data store చేసే system. ORM (Prisma, next chapter) database తో మాట్లాడటానికి oka developer-friendly layer — SQL raw గా రాయకుండా, TypeScript code తో queries రాయడానికి సహాయపడుతుంది. రెండూ వేర్వేరు layers.
Design (on paper/text) a simple database schema for a blog: a 'posts' table and an 'authors' table, with the correct foreign key relationship.
authors table:
id (Primary Key)
name
email
posts table:
id (Primary Key)
title
content
author_id (Foreign Key → authors.id)
Q Next.js కి ఏ database best?
Nirdishta answer లేదు — depends on the project. Structured, relational data (users, orders, courses) కి PostgreSQL popular. Rapid prototyping, flexible schema కి MongoDB popular.
Q Primary key ఎప్పుడూ number గానే ఉండాలా?
Ledు, UUID (string) కూడా వాడొచ్చు — distributed systems లో UUIDs common, ఎందుకంటే multiple servers ఒకేసారి unique IDs generate చేయగలవు, collision లేకుండా.
Q Foreign key లేకపోతే ఏమవుతుంది?
Foreign key లేకపోతే, database referential integrity enforce చేయదు — orphaned records (a course_id that doesn't exist) create అయ్యే chance ఉంటుంది. Prisma వాటిని schema level లో enforce చేయడానికి సహాయపడుతుంది.