SQL Flashcards

(21 cards)

1
Q

Question: What is SQL and what is it used for?

A

🧠 Technical Explanation:

SQL (Structured Query Language) is a domain-specific, declarative language used to communicate with and manage relational databases. It enables users to retrieve, manipulate, define, and control data efficiently.

🔩 Core Components:

🔷 DDL (Data Definition Language)

  • Purpose: Define and modify database structure.
  • Examples: CREATE, ALTER, DROP.

🔷 DML (Data Manipulation Language)

  • Purpose: Manipulate actual data in tables.
  • Examples: SELECT, INSERT, UPDATE, DELETE.

🔷 DCL (Data Control Language)

  • Purpose: Manage user permissions and access control.
  • Examples: GRANT, REVOKE.

🔷 TCL (Transaction Control Language)

  • Purpose: Handle transactions to ensure data integrity.
  • Examples: COMMIT, ROLLBACK, SAVEPOINT.

🛠️ Use Cases:

  • Creating and maintaining database schemas.
  • Querying data from databases.
  • Updating and deleting records.
  • Managing users and their access.
  • Performing atomic transactions.

💻 Code Example:

-- Create a table
CREATE TABLE users (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    email VARCHAR(100)
);

-- Insert data
INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'alice@example.com');

-- Query data
SELECT * FROM users;

-- Update data
UPDATE users SET name = 'Alicia' WHERE id = 1;

-- Delete data
DELETE FROM users WHERE id = 1;

-- Commit transaction
COMMIT;

🧾 Syntax Notes:

  • SQL keywords are case-insensitive, but usually written in uppercase.
  • Statements are terminated with semicolons (;).
  • SQL is set-based, meaning operations work on sets of rows.

🎙️ Interview-Friendly Casual Explanation:

“SQL is like the language you use to talk to a database. It helps you ask questions like ‘give me all users named John,’ or tell the database ‘add this new product.’ It’s made of different parts—like DDL for creating tables, DML for handling data, and so on. Every app that stores data pretty much uses SQL in some form.”

Let me know if you’d like a cheat sheet or mock interview questions on this!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Question: Describe the difference between SQL and NoSQL databases.

A

💡 Answer:

🧠 Top-Level Differences (Bullet Format)

  • SQL Databases:
    • Use a relational model based on tables with rows and columns.
    • Require a fixed/predefined schema.
    • Use Structured Query Language (SQL) for data operations.
    • Offer ACID compliance (Atomicity, Consistency, Isolation, Durability) for strong data integrity.
    • Scale vertically (by increasing server resources).
    • Best suited for applications needing complex queries, transactions, and structured data.
    • Examples: MySQL, PostgreSQL, Oracle, Microsoft SQL Server
  • NoSQL Databases:
    • Use a non-relational model, such as document-based, key-value, column-family, or graph.
    • Support flexible or dynamic schemas, ideal for evolving data structures.
    • Use varied APIs or query languages, depending on the type (e.g., MongoDB uses JSON-like syntax).
    • Often prioritize BASE properties (Basically Available, Soft state, Eventually consistent) for high availability and performance.
    • Scale horizontally (by adding more servers).
    • Best suited for big data, real-time web apps, and schema-less designs.
    • Examples: MongoDB, Cassandra, Redis, Couchbase, Neo4j

🔍 Use Case Breakdown:

  • ✅ Use SQL when:
    • You need strong consistency and data integrity.
    • Your data structure is stable and well-defined.
    • You require complex joins and transactions.
  • ✅ Use NoSQL when:
    • Your data is semi-structured or unstructured.
    • You expect frequent schema changes or rapid development.
    • You need to handle large-scale distributed systems.

🎙️ Interview-Friendly Casual Explanation:

“Think of SQL like a super-organized filing cabinet—you know exactly where everything goes, but it takes effort to set up and change. NoSQL is more like a flexible storage room where you can toss in stuff as you go. SQL is great for banking or anything that needs strict rules; NoSQL shines in fast-moving environments like social media apps or IoT systems where things change quickly.”

Let me know if you’d like a visual aid or a mnemonic to remember the differences!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Question: What is the difference between WHERE and HAVING clauses?

A

💡 Answer:

🧠 Technical Explanation:

  • WHERE Clause:
    • Filters rows before any grouping or aggregation happens.
    • Works on raw, individual records.
    • Cannot use aggregate functions like SUM(), COUNT() directly.
  • HAVING Clause:
    • Filters groups after aggregation (i.e., after GROUP BY).
    • Commonly used with aggregate functions.
    • Applies conditions on summarized data, not raw rows.

📌 Example to Illustrate:

✅ Using WHERE:

SELECT name, department
FROM employees
WHERE department = 'Sales';
  • 👉 Filters employees before any grouping—only those in Sales.

✅ Using HAVING:

SELECT department, COUNT(*) AS emp_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
  • 👉 Groups by department first, then filters only departments with more than 10 employees.

❗ Syntax Notes:

  • You can use both in a query:
SELECT department, AVG(salary)
FROM employees
WHERE status = 'Active'
GROUP BY department
HAVING AVG(salary) > 50000;
  • In this example:
    • WHERE filters active employees.
    • HAVING filters departments where the average salary is above 50k.

🎙️ Interview-Friendly Casual Explanation:

“Think of WHERE as the bouncer at the door—it decides who gets in. HAVING is like the judge inside, who decides which groups of people are worth keeping around. You use WHERE when filtering individual rows, and HAVING when you’ve already grouped the data and want to filter based on that summary.”

Let me know if you want a visual diagram or SQL quiz to reinforce this!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Question: Define what a JOIN is in SQL and list its types.

A

💡 Answer:

🧠 Technical Definition:

A JOIN in SQL is used to combine rows from two or more tables based on a related column, typically a foreign key. It’s essential for working with normalized databases where data is split across multiple tables.

🔗 Main Types of SQL JOINs:

  1. INNER JOIN
  • Returns only the rows with matching values in both tables.
  • Most common type of join.
SELECT a.name, b.salary
FROM employees a
INNER JOIN salaries b ON a.emp_id = b.emp_id;
  1. OUTER JOIN
  • Returns matching rows and also non-matching rows from one or both tables.
  • Subtypes:
    • LEFT OUTER JOIN (LEFT JOIN): All rows from the left table + matched rows from the right.
    • RIGHT OUTER JOIN (RIGHT JOIN): All rows from the right table + matched rows from the left.
    • FULL OUTER JOIN (FULL JOIN): All rows from both tables, matched where possible.
-- LEFT JOIN example
SELECT a.name, b.salary
FROM employees a
LEFT JOIN salaries b ON a.emp_id = b.emp_id;
  1. CROSS JOIN
  • Produces the Cartesian product of both tables.
  • Every row of table A joins with every row of table B.
SELECT *
FROM departments
CROSS JOIN employees;
  1. SELF JOIN
  • A table joined with itself, typically using table aliases.
  • Useful when dealing with hierarchical or self-referencing data (e.g., managers and employees).
SELECT a.name AS employee, b.name AS manager
FROM employees a
JOIN employees b ON a.manager_id = b.emp_id;

🎙️ Interview-Friendly Casual Explanation:

“A JOIN in SQL is like connecting two puzzle pieces based on how they fit together—usually through a shared column. INNER JOIN shows only matches, LEFT JOIN keeps all the pieces from the left even if there’s no match, and FULL JOIN shows everything from both sides. A CROSS JOIN just throws every piece from both puzzles on the table, and a SELF JOIN is like looking at yourself in a mirror—it lets a table link to itself.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Question: What is a primary key in a database?

A

💡 Answer:

🔐 Definition:

A primary key is a unique identifier for each row in a database table. It ensures that every record is distinct, non-null, and consistent, making it a cornerstone of relational database integrity.

🧬 Key Characteristics:

  • Uniqueness: No two rows can have the same primary key value.
  • Non-nullability: Every record must have a non-null primary key.
  • Immutability: It generally stays constant over time for a record.
  • Single or Composite: Can be a single column or a combination of columns (composite key).

🧱 Data Integrity Benefits:

  • Entity Integrity: Ensures that each row represents a unique entity.
  • 🔗 Referential Integrity: Forms the basis for relationships with foreign keys in other tables.
  • Prevents Duplicates: No duplicate entries for the key field.

⚙️ Performance Advantages:

  • 🚀 Indexing: Primary keys are automatically indexed in most RDBMSs, improving search performance.
  • 🔄 Faster Joins: Optimizes join operations with related tables.
  • 🧠 Query Planning: Assists the database engine in efficient query optimization.

🧑‍💼 Industry Best Practices:

  • 🧪 Use Natural Keys Cautiously: Only use existing data (like SSNs) if it’s stable and non-sensitive.
  • 🆔 Prefer Surrogate Keys: Auto-incremented IDs (INT, UUID) are simple and effective.
  • 💡 Keep It Simple: One-column keys are easier to manage and maintain.
  • Avoid Sensitive Data: Never use personally identifiable info (PII) like email or SSN as a primary key.

💻 Code Example: Declaring a Primary Key

CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    grade_level INT,
    first_name VARCHAR(50),
    last_name VARCHAR(50)
);

🎙️ Interview-Friendly Casual Explanation:

“A primary key is like a student ID—it uniquely identifies a person at a school, and there are no duplicates. In a database, it makes sure every row is one-of-a-kind, can always be found quickly, and stays consistent. It’s how tables keep their records straight and relate to each other.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Question: Explain what a foreign key is and how it is used.

A

💡 Answer:

🧷 Definition:

A foreign key (FK) is a column (or set of columns) in one table that references the primary key in another table. It defines a relationship between two tables, typically between a parent (referenced) and a child (referencing) table.

🔍 Key Functions of a Foreign Key:

  • Data Integrity: Ensures that every value in the foreign key column matches an existing value in the referenced table or is NULL (if allowed).
  • 🔄 Relationship Mapping: Represents how data in one table relates to data in another, such as each employee belongs to one department.
  • 🔁 Action Propagation (Cascade Rules):
    • ON DELETE CASCADE: Deletes child rows when parent is deleted.
    • ON UPDATE CASCADE: Updates child foreign key values when the parent key changes.

🔐 Foreign Key Constraints Ensure:

  • Referential Consistency: Child table entries must match a primary/unique key in the parent table.
  • Optional NULLs: A foreign key can contain NULL if the relationship is optional.
  • Duplicates Allowed: Unlike primary keys, foreign key values can be duplicated unless constrained otherwise.

🧱 Use Cases & Best Practices:

  • 🔗 One-to-Many Relationships: One department ➝ many employees.
  • 🔁 Many-to-Many Relationships: Via a junction table that includes foreign keys to both related tables.
  • Join Simplification: Foreign keys make joins logical and intuitive in SQL queries.
  • 🚫 Avoid Circular FKs: Don’t let Table A FK to Table B if Table B also FK’s back to Table A without valid justification.
  • 🔐 Secure Reference Data: Use FKs to protect against invalid inputs (e.g., a non-existent product_id in an orders table).

💻 Code Example: Creating a Foreign Key Relationship

-- Parent table
CREATE TABLE departments (
    id INT PRIMARY KEY,
    name VARCHAR(100)
);

-- Child table with foreign key
CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    department_id INT,
    FOREIGN KEY (department_id) REFERENCES departments(id)
);

✅ This ensures every department_id in the employees table must exist in the departments table.

🎙️ Interview-Friendly Casual Explanation:

“A foreign key is like saying, ‘This thing over here belongs to that thing over there.’ So if you have an employee, their department ID in the employee table is a foreign key that links them to the right department. It keeps the data tidy and connected—like a safety check that makes sure nothing points to something that doesn’t exist.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Question:What is SQL Injection and how can you prevent SQL injections?

A

💡 Answer:

SQL injection happens when an attacker inserts malicious SQL code into input fields, tricking the system into executing harmful commands. This can lead to unauthorized data access or damage.

Top Prevention Methods:

  1. Use Parameterized Queries (Prepared Statements):
    This separates user input from SQL code, so inputs are treated as data, not executable commands. It’s the most reliable defense.
    Example (Java):
    PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
    ps.setString(1, username);
    ps.setString(2, password);
    ResultSet rs = ps.executeQuery();
  2. Use Stored Procedures:
    Encapsulate SQL logic in the database and pass parameters safely, reducing injection risk.
  3. Input Validation:
    Check inputs against expected patterns (e.g., only letters and numbers) to catch suspicious data early, but don’t rely on this alone.
  4. Input Escaping or Filtering:
    Sanitize inputs to remove dangerous characters, though this is less effective than parameterization.
  5. Principle of Least Privilege:
    Limit database user permissions to only what’s necessary, minimizing damage if an injection occurs.
  6. Use Web Application Firewalls (WAF):
    Add an extra layer to detect and block injection attempts before they reach your application.

🎙️ Interview-Friendly Explanation:

“SQL injection is when attackers sneak harmful SQL code into user inputs to manipulate your database. The best way to stop this is by using parameterized queries, which keep data separate from commands so attackers can’t trick the database. Stored procedures, input checks, and limiting database permissions help too, but parameterized queries are the main defense.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Question: Describe the concept of denormalization and when you would use it.

A

💡 Short Answer:

🎯 What is Denormalization?

Denormalization means intentionally adding duplicate data in your database to speed up read queries by reducing the need for joins.

🚀 Why Use It?

It’s useful when your app reads data a lot, like in reports or dashboards, and you want faster, simpler queries.

Example

Instead of joining Customers and Orders tables to get a customer’s country, you store the country directly in the Orders table.

⚖️ Pros & Cons

  • Pros: Faster reads, simpler queries.
  • Cons: More storage, harder updates, risk of inconsistent data.

🎙️ Interview-Friendly Explanation

“Denormalization is copying some data to avoid joins and speed up reads, especially in read-heavy apps. It makes queries faster but means updates need extra care to keep data consistent.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is index ?

A

Indexes in databases are like the index at the back of a book—they help you quickly find the information you need without flipping through every page. In SQL, indexes speed up query performance by letting the database jump straight to the relevant data instead of scanning the whole table

But you have to use indexes carefully. Too many indexes can slow down data inserts and updates, and they also take up extra space. The best approach is to add indexes only to columns that are frequently searched or used in joins

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is Normalization ?

A

Normalization is a method used in designing databases to organize data efficiently. The main goal is to reduce duplicate data and make sure everything is stored logically.

Think of it like cleaning up a messy spreadsheet:

  • You split big tables into smaller ones that focus on one topic each (like customers, orders, products).
  • You link these smaller tables using keys (like customer IDs) so you can still connect the data when needed.
  • You follow rules (called normal forms) to decide how to split the data properly.

For example, instead of repeating a customer’s name and address in every order record, you keep that info in a separate Customers table. The Orders table just references the customer by ID. This way, if the customer moves, you update their address once, and all orders automatically reflect the change.

Normalization helps:

  • Avoid data duplication
  • Keep data consistent and accurate
  • Make updates and maintenance easier

However, highly normalized databases might need more complex queries with multiple joins, so sometimes you balance normalization with performance needs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is Group by ?

A

The GROUP BY clause in SQL is used to organize rows in a table into groups based on one or more columns that share the same values. This grouping allows you to perform aggregate calculations (like counting, summing, averaging) on each group

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is subquery ?

A

A subquery is a SQL query nested inside another query, that returns data used by the outer (main) query. It acts like a helper query to provide intermediate results, such as a single value, a list of values, or a temporary table, to assist the main query in filtering, calculating, or joining data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is Aggregate ?

A

Aggregate functions in SQL perform calculations on a set of values and return a single result. Common aggregate functions include:

  • COUNT: Counts the number of rows.
  • SUM: Calculates the sum of values in a column.
  • AVG: Computes the average of values in a column.
  • MIN: Returns the smallest value from a column.
  • MAX: Returns the largest value from a column.

These functions are typically used with the GROUP BY clause to summarize data across groups or without it to get an overall summary of a column.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is The Entity-Relationship (ER) ?

A

The Entity-Relationship (ER) Model is a key framework for designing databases, providing a visual way to represent data systems through entities, attributes, and relationships.

Core Concepts:
1. Entity: A distinct object or concept with its own properties.
2. Attribute: A property of an entity, unique to its entity type.
3. Relationship: A logical link between two or more entities.

Types of Entities:
- Strong Entity: Independent, with a primary key (shown as a solid rectangle).
- Weak Entity: Dependent, lacking its own primary key, relies on a strong entity (double rectangle).

Types of Relationships:
- One-to-One (1:1): One record links to exactly one other record.
- One-to-Many (1:M): One record connects to multiple records.
- Many-to-Many (M:N): Multiple records relate to multiple records, managed via a junction table.

Cardinality and Optionality:
- Cardinality: Defines the numerical link between records (e.g., exact like 2, or at least 1+).
- Optionality: Indicates if a relationship is mandatory or optional.

ER Diagram Components:
- Entities: Rectangles with the entity name.
- Attributes: Ovals connected to their entity.
- Relationships: Diamonds showing linked entities and cardinality.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Pros & Cons of Putting Business Logic in Stored Procedures vs Backend

A

💡 Answer

⚙️ 1. Business Logic in Stored Procedures (SP)

Pros:

  • High performance: Logic runs close to the data, minimizing network latency — great for heavy batch processing or reporting.
  • Data integrity: Keeps critical rules enforced directly in the database.
  • Fast to deploy small fixes: You can tweak logic without rebuilding the backend.

Cons:

  • Hard to test & debug: No modern unit testing frameworks; debugging often requires DB logs or profilers.
  • Poor CI/CD integration: Difficult to version-control, test, and deploy cleanly.
  • Tightly coupled to the DB: Harder to evolve or move logic across services.

🖥️ 2. Business Logic in Backend

Pros:

  • Easier to maintain and test: Unit testing, mocking, debugging — all supported by modern tools.
  • Scalable & modular: Better for growing systems and microservices.
  • CI/CD-friendly: Code lives in repositories, goes through review pipelines, and can be deployed automatically.

Cons:

  • Potential performance hit: For large datasets, making multiple DB calls can slow things down.
  • More moving parts: Logic may get scattered if not well-organized.

⚖️ Conclusion (My Preferred Approach):

“If performance is critical and data stays mostly inside the DB (e.g., reporting), I’ll consider SPs. But for evolving logic and testability, backend is far more manageable. Personally, I go hybrid: keep complex data manipulation in SPs, but put business rules in the app layer for flexibility.”

🎙️ Interview-Friendly Experience-Based Answer:
“In a fintech project I worked on, we initially used stored procedures for interest calculations. Performance was great, but testing and rollback were painful. We moved that logic to the backend — added unit tests and integrated it into CI/CD. It sped up development and improved reliability. Since then, I’ve preferred keeping critical data ops in SPs and core business logic in code.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a Stored Procedure?

A

💡 Answer

📘 Definition:

A Stored Procedure is a precompiled set of SQL statements stored in the database that can be executed as a single unit. It’s like a function in SQL — you can pass parameters to it, control flow (IF, WHILE), and perform multiple operations such as SELECT, INSERT, UPDATE, etc.

🧠 Key Characteristics:

  • Stored in the database, not in application code.
  • Can accept input/output parameters.
  • Can be reused and called by applications or other procedures.
  • Often used for data processing, batch jobs, and enforcing business rules close to the data.

Why Use Stored Procedures:

  • Improves performance: Executes directly in the DB engine.
  • Reduces client-server round-trips.
  • Enhances security: Can control access to data via procedure instead of direct table access.
  • Encapsulates business logic within the database.

🧾 Example:

CREATE PROCEDURE GetCustomerOrders
    @CustomerId INT
AS
BEGIN
    SELECT * FROM Orders WHERE CustomerId = @CustomerId
END

Call it like:

EXEC GetCustomerOrders @CustomerId = 5;

🎙️ Interview-Friendly Explanation:

“A stored procedure is basically a reusable block of SQL logic stored in the database. Instead of writing complex queries in the app every time, we put the logic inside the DB and just call the procedure. It’s faster for heavy data tasks and helps centralize business rules at the data layer.”

17
Q

What Are SQL Triggers?

A

SQL triggers are special stored procedures that automatically run when specific events happen in a database, like adding, updating, or deleting data. They help automate tasks and keep data consistent without manual intervention.
When Are They Used?

Triggers activate for:

DML Events: Like INSERT, UPDATE, or DELETE operations.
DDL Events: Such as CREATE, ALTER, or DROP commands.
Database Events: Like when the database starts or shuts down.

Key Parts of a Trigger

Triggering Event: The action that sets off the trigger, like a DELETE.
Trigger Action: The SQL commands that run automatically, such as logging changes.

Benefits

They automate routine tasks, like updating timestamps.
Ensure data stays consistent, even with complex rules.
Enhance security by logging activities or restricting access.
Help maintain audit trails for tracking changes.
Validate data to catch errors early.

Things to Watch Out For

They can slow down large systems due to extra processing.
Too many triggers can make the code hard to maintain and debug.

In short, SQL triggers are great for automating simple database tasks, but use them carefully to avoid performance issues.

18
Q

What is a Function in SQL?

A

💡 Answer

📘 Definition:

A Function in SQL is a named, reusable block of code that takes input parameters, performs operations, and returns a single value (scalar function) or a table (table-valued function). Unlike stored procedures, functions must return a value and cannot modify database state (no INSERT, UPDATE, DELETE).

🧠 Key Characteristics:

  • Always returns a result (scalar or table).
  • Used in SELECT, WHERE, JOIN, etc.
  • Cannot perform transactions or modify data.
  • Supports input parameters.
  • Good for reusable logic like calculations or lookups.

Common Use Cases:

  • String manipulation (e.g., format names, parse text)
  • Mathematical calculations (e.g., tax, discount)
  • Date handling (e.g., calculate age, time difference)
  • Returning filtered/custom datasets (with table-valued functions)

🧾 Example 1: Scalar Function

CREATE FUNCTION dbo.GetFullName (@FirstName NVARCHAR(50), @LastName NVARCHAR(50))
RETURNS NVARCHAR(101)
AS
BEGIN
    RETURN @FirstName + ' ' + @LastName
END

Use it like:

SELECT dbo.GetFullName(FirstName, LastName) AS FullName FROM Employees;

🧾 Example 2: Table-Valued Function

CREATE FUNCTION dbo.GetOrdersByCustomer (@CustomerId INT)
RETURNS TABLE
AS
RETURN (
    SELECT * FROM Orders WHERE CustomerID = @CustomerId
)

Use it like:

SELECT * FROM dbo.GetOrdersByCustomer(5);

🎙️ Interview-Friendly Explanation:

“In SQL, a function is like a helper tool — it takes input, does some logic, and returns a value. It’s great for reusable pieces of logic like formatting or calculations, and unlike stored procedures, it can be used right inside a SELECT query.”

19
Q
A

💡 Answer: What is ACID in Databases?

ACID stands for Atomicity, Consistency, Isolation, Durability — four key properties that ensure data integrity and reliability in database transactions.

🔹 1. Atomicity

> “All or nothing.”

  • A transaction must either complete fully or not at all.
  • If any part of the transaction fails, the entire operation is rolled back.

Example (Bank Transfer):
Transferring $100 from Account A to B involves two steps:
– Debit A, Credit B.
If credit to B fails, the debit from A is rolled back.

🔹 2. Consistency

> “Start and end in a valid state.”

  • A transaction must move the database from one valid state to another.
  • All constraints, triggers, and rules must be respected.

Example: Placing an order should deduct stock only if items are available. If stock is insufficient, the transaction fails.

🔹 3. Isolation

> “Transactions don’t step on each other.”

  • Multiple transactions can run concurrently, but they must appear isolated.
  • Intermediate states of one transaction are not visible to others.

Example (Ticket Reservation):
Two users reserving the last seat at the same time must not both succeed. One wins; the other sees an error or availability change.

🔹 4. Durability

> “Once saved, always saved.”

  • After a transaction is committed, changes are permanently stored, even in the event of a crash.

Example (Flight Booking):
You book a flight, get confirmation, then the server crashes. The booking is safe and retrievable.

🎙️ Interview-Friendly Summary:

“ACID ensures that database transactions are safe and reliable. I’ve seen these principles play out directly—for example, while working on a payment system, we had to guarantee atomicity for multi-step fund transfers, and isolation to prevent race conditions during checkout. Without ACID, financial or critical systems would easily fall apart under concurrent loads.”

Let me know if you want a diagram, real code-based demo, or ACID vs BASE comparison.

20
Q

🧠 What is Locking?

A

💡 Answer:

Locking = A way for the database to protect data when many users access it at once.
It prevents errors like two users editing the same data at the same time.

🔐 Why Use Locks?

  • Stop data conflicts
  • Keep transactions safe
  • Enforce isolation in ACID

🎯 Real Example (Easy to Picture):

Two people buying 1 concert ticket online.
Lock makes sure only one gets it, the other has to wait or gets an error.

🗣️ How to Say in Interview:

“Locking helps keep data safe when multiple users access it. It’s like a traffic light — only one car (transaction) moves at a time to avoid crashes (conflicts).”