nova / databases.txt
crazysanthosh's picture
Upload 25 files
7fde9b9 verified
Raw History Blame Contribute Delete
5.59 kB
## SQL Fundamentals
Definition: SQL (Structured Query Language) is the standard language for managing relational databases — querying, inserting, updating, and deleting data.
Explanation: Relational databases store data in tables with rows and columns. SQL operations: SELECT (query data), INSERT (add rows), UPDATE (modify rows), DELETE (remove rows), CREATE/DROP (DDL). JOINs combine data from multiple tables. Indexes speed up queries. Transactions ensure data integrity with ACID properties.
Example: Query all orders from the last 30 days with customer information.
Code Example:
```sql
-- Create tables
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
customer_id INT REFERENCES customers(id),
total DECIMAL(10, 2),
status VARCHAR(20) DEFAULT 'pending',
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Query with JOIN, filtering, and aggregation
SELECT
c.name,
c.email,
COUNT(o.id) AS order_count,
SUM(o.total) AS total_spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= NOW() - INTERVAL '30 days'
GROUP BY c.id, c.name, c.email
HAVING SUM(o.total) > 100
ORDER BY total_spent DESC
LIMIT 10;
```
Best Practices: Index columns used in WHERE, JOIN, and ORDER BY. Use parameterized queries to prevent SQL injection. Use EXPLAIN ANALYZE to debug slow queries. Normalize your schema (3NF) to avoid data duplication.
Common Errors: N+1 query problem — fetching related data in a loop instead of a JOIN. Missing indexes on foreign keys. Using SELECT * instead of selecting specific columns. Not using transactions for multi-step operations.
Interview Questions: What is the difference between INNER JOIN, LEFT JOIN, and FULL OUTER JOIN? Explain database normalization. What is an index and how does it work?
## NoSQL Databases (MongoDB)
Definition: NoSQL databases store data in non-tabular formats (documents, key-value, column-family, graph) and are designed for flexible schemas and horizontal scalability.
Explanation: MongoDB stores data as BSON documents (like JSON). Collections are like tables; documents are like rows but can have different fields. No schema enforcement by default. Supports complex nested data naturally. Horizontal scaling via sharding. Aggregation pipeline for complex queries. Best for flexible schemas, high write throughput, and hierarchical data.
Example: Storing and querying blog posts with embedded comments.
Code Example:
```javascript
// Insert a document
await db.collection('posts').insertOne({
title: "Getting Started with MongoDB",
author: { name: "Alice", id: "user_123" },
tags: ["mongodb", "nosql", "database"],
views: 0,
comments: [],
createdAt: new Date()
});
// Aggregation pipeline
const topPosts = await db.collection('posts').aggregate([
{ $match: { tags: "mongodb" } },
{ $addFields: { commentCount: { $size: "$comments" } } },
{ $sort: { views: -1, commentCount: -1 } },
{ $limit: 5 },
{ $project: { title: 1, views: 1, commentCount: 1 } }
]).toArray();
```
Best Practices: Design documents around your query patterns (embed for reads, reference for writes). Create indexes on frequently queried fields. Use the aggregation pipeline for analytics. Use MongoDB Atlas for managed cloud deployment.
Common Errors: Embedding unbounded arrays in documents (they can grow without limit). Not creating indexes (full collection scans are slow). Storing relational data that needs complex JOINs in MongoDB.
Interview Questions: When would you choose MongoDB over PostgreSQL? What is the aggregation pipeline? How does MongoDB handle transactions?
## Database Indexing
Definition: An index is a data structure (usually a B-tree) that allows the database to find data quickly without scanning every row in a table.
Explanation: Without an index, queries do a full table scan O(n). With a B-tree index, lookup is O(log n). Types: B-tree (default, great for range queries), Hash (exact match only), GIN (full-text, JSON), BRIN (sorted data like timestamps), Partial indexes (index a subset of rows). Indexes speed up reads but slow down writes (index must be updated on insert/update/delete).
Example: Adding an index to speed up user lookups by email.
Code Example:
```sql
-- See query plan BEFORE index
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';
-- Seq Scan... cost=0..4500 rows=1 width=50 (slow!)
-- Create index
CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
-- Check plan AFTER index
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';
-- Index Scan... cost=0..8 rows=1 width=50 (fast!)
-- Composite index (for queries on multiple columns)
CREATE INDEX idx_orders_customer_date ON orders(customer_id, created_at DESC);
-- Partial index (only active users)
CREATE INDEX idx_active_users ON users(last_login) WHERE status = 'active';
```
Best Practices: Index columns in WHERE, JOIN ON, and ORDER BY. Use CONCURRENTLY to create indexes without locking. Don't over-index — each index costs write performance. Remove unused indexes.
Common Errors: Not indexing foreign key columns (joins become slow). Indexing low-cardinality columns (boolean — the optimizer may not use the index). Index on expression not being used because query doesn't match the expression.
Interview Questions: What is a covering index? Explain the difference between clustered and non-clustered indexes. When would you NOT want to add an index?