Home Uncategorized NoSQL Databases vs Relational Databases – Trade-offs and...
Uncategorized

NoSQL Databases vs Relational Databases – Trade-offs and Use Cases: 20 Real Interview Questions

NoSQL vs Relational databases fundamentals represent two philosophies of data storage. Relational databases (SQL, tables, ACID) are like libraries: organized, structured, with strict rules. NoSQL databases (documents, key-value, eventually consistent) are like notebooks: flexible, scalable, less rigid. Understanding when to use each is critical for architects.

Understanding Database Philosophies

Relational databases organize data into normalized tables with relationships (foreign keys). Data is structured, validated via constraints, and consistent (ACID). Queries use SQL with JOINs. Scaling is vertical (bigger servers).

NoSQL databases store data in flexible formats: documents (JSON), key-value pairs, graphs, or wide columns. No schema enforcement. Queries are document-focused, not relational. Scaling is horizontal (more servers). Consistency is eventual, not immediate.

Think of relational like a spreadsheet: columns defined, data must fit types. NoSQL is like a filing cabinet: folders can hold anything.

Relational Strengths: ACID and Consistency

Relational databases guarantee ACID: transactions either fully succeed or fail, preventing partial updates. Consistency is immediate: read writes committed by others. Perfect for banking, finance, where correctness is critical. Strong schema prevents invalid data.

NoSQL Strengths: Scalability and Flexibility

NoSQL scales horizontally across servers trivially. Adding servers (nodes) increases capacity, unlike relational which struggles. No schema enforcement allows storing varied data without migrations. Documents can have different fields. Fast writes, perfect for high-volume systems (social media, IoT).

NoSQL Trade-offs: Eventual Consistency

NoSQL typically guarantees eventual consistency, not immediate. If User A writes data, User B might temporarily see old data until replication catches up. No ACID guarantees, no transactions spanning documents. Developers must handle consistency manually. Perfect for systems where slight stale data is acceptable (Twitter feed, recommendations).

CAP Theorem: Choose Two of Three

CAP theorem states databases cant guarantee Consistency, Availability, and Partition tolerance simultaneously. Relational prioritizes Consistency and Availability. NoSQL prioritizes Availability and Partition tolerance, accepting eventual consistency. Understanding this guides database selection.

5 Complete Interview Questions with Solutions

Question 1: When to Use Relational vs NoSQL

Youre building a banks account system. Should you use SQL or NoSQL, and why? What guarantees matter?

-- Banking System: Use SQL (Relational)
REASONS:
1. ACID Guarantees: Transfer $100 from A to B must be atomic
   - Debit A, Credit B both succeed or both rollback
   - NoSQL eventual consistency unacceptable (lose money)

2. Strong Consistency: Balance must be accurate immediately
   - After write, all reads see updated balance
   - NoSQL temporary stale data = invalid balances

3. Complex Transactions: Multiple accounts, cross-checks
   - SQL JOINs and multi-table transactions handle this
   - NoSQL would require manual coordination

4. Regulatory Compliance: Audits require exact records
   - SQL constraints prevent invalid states
   - NoSQL flexibility problematic for regulations

-- Example:
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- Both or nothing

-- If NoSQL used:
-- Write A updates: A -= 100
-- Write B updates: B += 100
-- Both succeed eventually, but one could fail
-- Money lost in between

Explanation: Financial systems demand immediate consistency. Eventual consistency is unacceptable. Relational databases provide ACID guarantees; NoSQL doesnt. Choose based on consistency requirements, not just scalability.

Google – Senior Database EngineerAmazon – Senior ArchitectMicrosoft – Data Architect

Question 2: NoSQL for Social Media

Building Twitter-like social media: posts, likes, followers. Millions of writes/sec. Why is NoSQL better than SQL here?

-- Social Media: Use NoSQL (Document DB like MongoDB)
REASONS:
1. Horizontal Scaling: Add servers for write capacity
   - SQL struggles with millions writes/sec on one table
   - NoSQL shards writes across 100+ servers

2. Flexible Schema: Posts vary (text, images, videos, links)
   - Document stores handle varied fields natively
   - SQL would require migrations (painful at scale)

3. Eventual Consistency Acceptable
   - Seeing a like 1 second late: OK
   - Seeing an old feed version: OK
   - Banking: Unacceptable

4. Denormalization: Store likes count in post document
   - SQL would JOIN posts + likes (slow, complex)
   - NoSQL: fetch one document (fast)

-- NoSQL Document
db.posts.insert({
  _id: "post123",
  user_id: "user456",
  text: "Hello world",
  timestamp: Date(),
  likes: 15000,
  liked_by: [...],
  media: [{type: "image", url: "..."}]
});

-- SQL would need: posts table, likes table, JOIN

Explanation: Social media prioritizes availability and scalability over immediate consistency. NoSQL scales better. Eventual consistency acceptable. Denormalization fine (duplicate data for speed).

Meta – Senior Database EngineerOracle – Data ArchitectIBM – Senior DBA

Question 3: CAP Theorem Trade-offs

CAP theorem: Consistency, Availability, Partition tolerance. Which two does SQL vs NoSQL choose, and what are the implications?

-- CAP Theorem
C: Consistency (all see same data)
A: Availability (always responsive)
P: Partition tolerance (survives network splits)

-- Relational (SQL): Consistency + Availability
- If network partitions, blocks writes to maintain consistency
- All nodes must agree (consensus protocol)
- If partition: lose availability (downtime)
- Banking: Better to be down than inconsistent

-- NoSQL: Availability + Partition tolerance
- If network partitions, both sides accept writes
- Data diverges temporarily
- Eventually consistent when healed
- Social media: Better offline than accurate

-- Example:
Network splits: Server A vs Server B disconnected

SQL: Either A works, B blocked (consistency)
Or both blocked (wait for heal)

NoSQL: Both work independently
A increments likes, B increments likes
When healed, both updates merge
(Conflicts handled with last-write-wins or merge logic)

Explanation: CAP forces trade-offs. No database has all three. SQL sacrifices partition tolerance for consistency. NoSQL sacrifices immediate consistency for availability. Choose based on failure mode tolerance.

Stripe – Senior Data EngineerLinkedIn – Database Architect

Question 4: Schema Evolution

Your SQL database has millions of rows. You need to add a new column. This requires a migration blocking writes. How does NoSQL handle this differently?

-- SQL: Schema migration required
ALTER TABLE users ADD COLUMN phone_number VARCHAR(20);
-- On 1B row table: takes hours, blocks writes
-- Risk: Migration fails, rollback needed

-- NoSQL: No migration needed!
-- Just start writing new field
db.users.updateOne({_id: 1}, {$set: {phone_number: "555-1234"}});

-- Old documents missing phone_number: OK
-- Application handles missing fields gracefully
// if (user.phone_number) { ... }

-- Flexibility
// Different documents have different fields
db.products.find() returns:
{
  _id: 1,
  name: "Laptop",
  price: 999
}
{
  _id: 2,
  name: "Service",
  monthly_fee: 50
  // No price field
}

Explanation: Relational requires schema migrations (costly, risky). NoSQL allows gradual schema evolution. Add fields to new documents, ignore missing fields in old ones. No downtime.

Google – Senior Data ArchitectAmazon – Database Engineer

Question 5: Denormalization in NoSQL

In SQL, duplicating data violates normalization. In NoSQL, denormalization is common. Whats the reasoning, and what are the risks?

-- SQL: Normalized (no duplication)
Table: orders
order_id, customer_id, total
Table: customers
customer_id, name, email
-- Query: SELECT o.order_id, c.name FROM orders o
--        JOIN customers c ON o.customer_id = c.customer_id
-- JOIN is slow on large tables

-- NoSQL: Denormalized (duplicate data)
db.orders.insert({
  _id: "order123",
  customer_id: "cust456",
  customer_name: "John",  // DUPLICATED
  customer_email: "john@ex.com",  // DUPLICATED
  items: [...],
  total: 99.99
});
-- Query: Single document fetch (fast)

-- Reasoning:
// Reads are much faster (no JOINs)
// Writes are single operation (no distributed transaction)
// Scale to 1M orders without performance hit

-- Risks:
// If customer name changes, update 100K orders
db.orders.updateMany(
  {customer_id: "cust456"},
  {$set: {customer_name: "John Smith"}}
);
// Slow, multiple writes, consistency risk

-- Mitigation: Accept eventual consistency
// Accept stale customer names temporarily
// Or use caching layer

Explanation: Denormalization trades write complexity for read speed. Acceptable when reads >> writes, or eventual consistency OK. SQL priorities consistency; NoSQL prioritizes read speed. Different trade-off philosophies.

Microsoft – Senior Database ArchitectMeta – Data Engineer

15 Practice Questions (Test Yourself)

Question 6: If you need strong consistency for user account data but eventual consistency is acceptable for user preferences and recommendations, would a hybrid approach using both SQL and NoSQL be appropriate, and how would you manage this architecture?

Google – Senior Data EngineerAmazon – Senior Architect

Question 7: When migrating from SQL to NoSQL for a legacy system, what data consistency issues might arise during the transition period, and how would you manage the parallel operation of both systems?

Microsoft – Senior Database EngineerMeta – Data Architect

Question 8: NoSQL databases often lack complex querying capabilities that SQL provides through JOINs. How would you handle complex analytical queries in a NoSQL environment?

Oracle – Senior Data ArchitectIBM – Database EngineerLinkedIn – Senior DBA

Question 9: If a NoSQL database experiences network partitions and both sides of the partition accept writes creating conflicting data, what strategies would you use to resolve these conflicts during healing?

Stripe – Senior Data EngineerGoogle – Database Architect

Question 10: When comparing SQL and NoSQL for a newly-built system with uncertain requirements, what factors would influence your initial choice, and how would you design to support switching databases later?

Amazon – Senior Data ArchitectMicrosoft – Database EngineerMeta – Senior DBA

Question 11: SQL databases enforce constraints at the database level guaranteeing data integrity. How do you maintain equivalent data quality guarantees in NoSQL systems that lack schema validation?

Flipkart – Senior Database EngineerLinkedIn – Data Architect

Question 12: When using multiple NoSQL databases optimized for different access patterns (document store for user profiles, key-value for sessions, time-series for metrics), how would you ensure consistency across these systems?

Google – Senior Data ArchitectOracle – Senior DBAIBM – Data Architect

Question 13: If a business requirement demands ACID transactions spanning multiple documents in NoSQL, what challenges arise, and would this be a signal that SQL might be a better choice?

Stripe – Database EngineerAmazon – Senior Data Engineer

Question 14: How would you handle backup and disaster recovery strategies differently between SQL and NoSQL databases, considering their different consistency models?

Microsoft – Senior Data ArchitectMeta – Database EngineerGoogle – BI Architect

Question 15: If you need to implement full-text search across millions of documents, would SQL or NoSQL databases provide better performance, and what specialized index types support this use case?

LinkedIn – Senior Data EngineerFlipkart – Data Architect

Question 16: When designing an application requiring complex reporting and analytics, would you continue using NoSQL for transactional data or migrate critical data to SQL for analytical queries?

Stripe – Senior Data ArchitectAmazon – Database EngineerOracle – Senior DBA

Question 17: If youre evaluating NoSQL databases for compliance-heavy industries like healthcare or finance, what features would you look for to compensate for lacking ACID guarantees?

Google – Senior Data EngineerIBM – Data Architect

Question 18: How would cost of ownership differ between maintaining a SQL database with vertical scaling versus NoSQL with horizontal scaling as your system grows from 1M to 1B records?

Meta – Senior Data ArchitectMicrosoft – Database EngineerLinkedIn – Senior BI Engineer

Question 19: If your NoSQL database allows you to store heterogeneous data types for flexibility, how would you document and communicate the evolving schema to your application development team?

Stripe – Database EngineerAmazon – Senior Data Architect

Question 20: When choosing between different NoSQL databases (MongoDB, Cassandra, DynamoDB, Redis), what characteristics of your data access patterns and scale requirements would guide your selection?

Google – Senior Database ArchitectOracle – Senior DBAIBM – Data Architect

Ready to Master SQL vs NoSQL Trade-offs?

These 20 practice questions are just the tip of the iceberg. Get our comprehensive Data Analytics: Ace All The Interview Concepts course.

Scroll to Top