DBMS · 67 topics
What is DBMS?
DBMS stands for Database Management System. It is software used to store, manage, retrieve, update and organize data efficiently.
Examples
MySQL
PostgreSQL
Oracle
SQLite
What is a database?
A database is an organized collection of related data that can be accessed, managed and updated efficiently.
A database is the organized collection of data itself, while a DBMS is the software used to store, manage and interact with that data
Example: A college database containing student details, marks, attendance and fees.
What is RDBMS?
RDBMS stands for Relational Database Management System.
It stores data in tables consisting of rows and columns and establishes relationships between tables.
Examples: MySQL, PostgreSQL and Oracle.
Difference between DBMS and RDBMS?
DBMS | RDBMS |
|---|---|
General database management system | Relational database management system |
May use different data models | Uses relational tables |
Relationships are not necessarily enforced through relational keys | Supports relationships through keys |
Basic security; does not enforce strict ACID properties. | High security with granular permissions and full ACID compliance. |
What is SQL?
SQL stands for Structured Query Language. It is used to communicate with relational databases.
It allows us to:
Create tables.
Insert data.
Retrieve data.
Update records.
Delete records.
What is a table?
A table is a collection of related data organized into rows and columns.
What are rows and columns?
Row: A single record in a table.
Column: An attribute or field of a table.
Example:
ID | Name | Age |
|---|---|---|
1 | Rahul | 21 |
2 | Aman | 22 |
3 | Ritesh | 22 |
What is a schema?
A schema is the logical structure or blueprint of a database.
It defines tables, columns, data types, relationships and constraints.
What is an instance?
An instance is the actual data stored in a database at a particular moment.
What is metadata?
Metadata means data about data. For example, column names, data types, table definitions and constraints.
What are DDL, DML, DCL and TCL?
DDL, DML, DCL and TCL are categories of SQL commands that define database structure, modify stored data, manage user permissions and control database transactions.
DDL (Data Definition Language): DDL commands create, alter and delete database structures such as tables, schemas and indexes.
CREATE: Builds new tables, databases, views or indexes.ALTER: Modifies existing structures, such as adding or changing columns.DROP: Deletes database objects and their data.TRUNCATE: Removes all rows from a table while keeping its structure.RENAME: Renames an existing database object.
DML (Data Manipulation Language): DML commands insert, update and delete data inside database tables.
INSERT: Adds new rows into a table.UPDATE: Modifies existing row values.DELETE: Removes specific rows from a table.SELECT: Retrieves data from tables (often classified as DQL).
DCL (Data Control Language): DCL commands manage user access, privileges and security permissions on database objects.
GRANT: Gives specific permissions (likeSELECTorINSERT) to users or roles.REVOKE: Removes previously granted permissions.
TCL (Transaction Control Language): TCL commands manage transactions to keep data consistent.
COMMIT: Permanently saves changes made during a transaction.ROLLBACK: Reverts uncommitted changes back to the last commit or savepoint.SAVEPOINT: Sets a marker within a transaction for partial rollbacks.
What is the logical order of execution of a SELECT query?
The logical order of execution for a
SELECTquery isFROM/JOIN→WHERE→GROUP BY→HAVING→SELECT→DISTINCT→ORDER BY→LIMIT/OFFSET
What is a Primary Key?
A primary key uniquely identifies each record in a table.
Properties:
Must be unique.
Cannot contain NULL values.
Only one primary key constraint per table (it may consist of multiple columns).
Example:
Student_ID.
What is a Foreign Key?
A foreign key is a column or group of columns that references a candidate key, usually the primary key in another table.
What is a Candidate Key?
A candidate key is a minimal set of attributes that can uniquely identify a record.
Example: If both Student_ID and Email are unique, either could be a candidate key.
What is a Super Key?
A super key is any set of one or more attributes that uniquely identifies a record.
Example:
Student_ID
Student_ID + Name
Student_ID + Email
What is an Alternate Key?
A candidate key that is not selected as the primary key is called an alternate key.
What is a Composite Key?
A key formed using two or more columns to uniquely identify a record.
Difference between Primary Key and Unique Key?
Primary Key | Unique Key |
|---|---|
A primary key uniquely identifies each record in a table. | Unique Key prevents duplicate values in a column while allowing |
Cannot contain NULL | NULL handling depends on DBMS |
One primary key constraint per table | Multiple unique constraints possible |
Can be composite | Can be composite |
What is a Natural Key?
A natural key is an attribute that has real-world meaning and can uniquely identify a record, such as a properly validated national identification number.
What is a Surrogate Key?
A surrogate key is an artificially generated identifier without business meaning, such as an auto-incrementing student ID.
What is Referential Integrity?
Referential integrity is a relational database rule that ensures relationships between tables remain valid and consistent.
Specifically, it guarantees that every Foreign Key value in a child table must either match an existing Primary Key value in the parent table or be
NULL.
Difference between DELETE, DROP and TRUNCATE?
DELETE | TRUNCATE | DROP |
|---|---|---|
It deletes selected rows or all rows | It removes all rows | It removes the entire table |
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping.
HAVING filters groups after GROUP BY.
SELECT department, COUNT(*)
FROM employees
WHERE salary > 30000
GROUP BY department
HAVING COUNT(*) > 5;What is GROUP BY?
GROUP BY groups rows having the same values in specified columns, often used with aggregate functions.
SELECT department, COUNT(*)
FROM employees
GROUP BY department;What are aggregate functions?
Aggregate functions perform calculations on multiple rows and return a single result per group or for the entire result.
Examples:
COUNT()
SUM()
AVG()
MIN()
MAX()
What is DISTINCT?
DISTINCT removes duplicate rows from the selected result.
SELECT DISTINCT department
FROM employees;What is ORDER BY?
ORDER BY sorts the query result in ascending or descending order.
SELECT *
FROM employees
ORDER BY salary DESC;What is the difference between COUNT(*) and COUNT(column)?
COUNT(*)counts all rows.COUNT(column)counts non-NULL values in that column.
What is NULL in SQL?
NULL represents missing, unknown or unavailable information.
It is not equivalent to zero or an empty string.
# To check NULL
SELECT *
FROM employees
WHERE salary IS NULL;
# Do not use salary = NULL.What is the LIKE operator?
LIKE is used for pattern matching.
Common wildcards:
%= zero or more characters._= exactly one character.
SELECT *
FROM employees
WHERE name LIKE 'A%';Joins
A JOIN combines rows from two or more tables based on a related column.
Consider:
Employees
ID | Name | Dept_ID |
|---|---|---|
1 | Aman | 10 |
2 | Rahul | 20 |
3 | Ritesh | 30 |
4 | Karan | 10 |
Departments
Dept_ID | Department |
|---|---|
10 | IT |
20 | HR |
40 | Sales |
What is INNER JOIN?
Returns only matching rows from both tables.
SELECT e.Name, d.Department
FROM Employees e
INNER JOIN Departments d
ON e.Dept_ID = d.Dept_ID;Result:
Name | Department |
|---|---|
Aman | IT |
Rahul | HR |
Karan | IT |
What is LEFT JOIN?
Returns all rows from the left table and matching rows from the right table.
If there is no match, right-side columns contain NULL.
SELECT e.Name, d.Department
FROM Employees e
LEFT JOIN Departments d
ON e.Dept_ID = d.Dept_ID;Ritesh will appear with NULL as the department.
What is RIGHT JOIN?
Returns all rows from the right table and matching rows from the left table.
SELECT e.Name, d.Department
FROM Employees e
RIGHT JOIN Departments d
ON e.Dept_ID = d.Dept_ID;Sales will appear with NULL for employee details.
What is FULL OUTER JOIN?
Returns all matching and non-matching rows from both tables, filling missing sides with NULL.
SELECT e.Name, d.Department
FROM Employees e
FULL OUTER JOIN Departments d
ON e.Dept_ID = d.Dept_ID;What is CROSS JOIN?
Returns the Cartesian product of two tables.
If table A has 3 rows and table B has 4 rows, CROSS JOIN returns 12 rows.
What is SELF JOIN?
A table is joined with itself.
Example: Finding employees and their managers.
SELECT e.Name AS Employee,
m.Name AS Manager
FROM Employees e
LEFT JOIN Employees m
ON e.Manager_ID = m.ID;What is normalization?
Normalization is the process of organizing data to reduce data redundancy and avoid insertion, deletion and update anomalies.
Why do we need normalization?
Reduces duplicate data.
Prevents data inconsistency.
Improves data organization.
Avoids insertion, deletion and update anomalies.
What are database anomalies?
Anomalies in a database are data inconsistencies, errors or unexpected behaviors that happen during insertion, update or delete operations.
They are usually caused by poor database design, high data redundancy or a lack of normalization.
There are three major anomalies:
Insertion anomaly: We cannot add new data to a table because it requires other unrelated or missing information. Trying to add a new course (
Power BI) to aStudent_Coursetable, the database rejects or forces you to fill in student information that does not exist yet because a student ID is tied to the primary key.Update anomaly: Data is duplicated across multiple rows. If we change it in one row and forget to change it in others, the database becomes inconsistent. Example: If a course instructor's name is stored in 50 different student enrollment rows and you update it in only 49 rows, the database will show two different instructors for the same course
Deletion anomaly: Deleting one record accidentally removes other useful information. Deleting the last student enrolled in a specific class removes that student and also deletes all records and history of the course itself from the table
1NF (First Normal Form)
A table is in 1NF if:
Each cell contains a single atomic value.
There are no repeating groups or multi-valued attributes.
Example of violation:
Student_ID | Subjects |
|---|---|
1 | Java, Python |
2 | SQL, C++ |
Correct representation:
Student_ID | Subject |
|---|---|
1 | Java |
1 | Python |
2 | SQL |
2 | C++ |
2NF (Second Normal Form)
A table must:
Be in 1NF.
Have no partial dependency: every non-key attribute must depend on the whole candidate key, not just part of a composite key.
Before 2NF (Violates 2NF)
Student_ID (PK) | Course_ID (PK) | Student_Name | Course_Title | Grade |
|---|---|---|---|---|
101 | C01 | Aarav | SQL Basics | A |
101 | C02 | Aarav | Power BI | B+ |
102 | C01 | Priya | SQL Basics | A- |
The Problem:
Student_Namedepends only onStudent_ID, andCourse_Titledepends only onCourse_ID. OnlyGradedepends on both keys together.The Anomalies: If Aarav changes his name, you must update multiple rows (update anomaly). You also cannot add a new course until a student enrolls (insertion anomaly).
After 2NF (Decomposed into 3 Tables)
To reach 2NF, split the columns that depend on partial keys into their own dedicated tables.
1. Students Table (Student_ID is the primary key)
Student_ID (PK) | Student_Name |
|---|---|
101 | Aarav |
102 | Priya |
2. Courses Table (Course_ID is the primary key)
Course_ID (PK) | Course_Title |
|---|---|
C01 | SQL Basics |
C02 | Power BI |
3. Enrollments Table (Student_ID, Course_ID is the composite primary key)
Student_ID (PK, FK) | Course_ID (PK, FK) | Grade |
|---|---|---|
101 | C01 | A |
101 | C02 | B+ |
102 | C01 | A- |
3NF (Third Normal Form)
A table must:
Be in 2NF.
Have no transitive dependency: every non-key attribute depends directly on the primary key, not on another non-key attribute.
Before 3NF (Violates 3NF)
Courses Table
Course_ID (PK) | Course_Title | Instructor_Name | Instructor_Office |
|---|---|---|---|
C01 | SQL Basics | Dr. Sharma | Room 302 |
C02 | Power BI | Dr. Sharma | Room 302 |
C03 | Python | Prof. Verma | Room 405 |
The Problem:
Course_IDdeterminesInstructor_Name, andInstructor_NamedeterminesInstructor_Office. BecauseInstructor_Officedepends on a non-key column (Instructor_Name) rather than directly onCourse_ID, this creates a transitive dependency.The Anomalies: If Dr. Sharma moves to a new office, you must update multiple rows (update anomaly). If you delete all courses taught by Prof. Verma, you lose the record of his office room (delete anomaly).
After 3NF (Decomposed into 2 Tables)
To reach 3NF, move the transitively dependent columns into a separate table with the determining column as its primary key.
1. Courses Table (Course_ID is the primary key)
Course_ID (PK) | Course_Title | Instructor_Name (FK) |
|---|---|---|
C01 | SQL Basics | Dr. Sharma |
C02 | Power BI | Dr. Sharma |
C03 | Python | Prof. Verma |
2. Instructors Table (Instructor_Name is the primary key)
Instructor_Name (PK) | Instructor_Office |
|---|---|
Dr. Sharma | Room 302 |
Prof. Verma | Room 405 |
What is BCNF (Boyce-Codd Normal Form)
BCNF is a stronger version of 3NF.
A relation is in BCNF if for every non-trivial functional dependency (X → Y), X must be a superkey.
Before BCNF (In 3NF, but Violates BCNF)
Student_ID (PK) | Subject (PK) | Professor |
|---|---|---|
101 | SQL | Dr. Sharma |
101 | Python | Prof. Verma |
102 | SQL | Dr. Sharma |
103 | SQL | Dr. Rao |
Why it passes 3NF: There are no partial or transitive dependencies on non-prime attributes because
Subjectis part of the candidate key(Student_ID, Subject).Why it fails BCNF: In the dependency
Professor → Subject,ProfessordeterminesSubject, yetProfessoris not a superkey (Dr. Sharma appears twice).The Anomalies: If Dr. Rao leaves the university and student 103 drops SQL, deleting that row erases the fact that Dr. Rao teaches SQL (delete anomaly). Also, "SQL" is stored repeatedly alongside Dr. Sharma's name (redundancy).
After BCNF (Decomposed into 2 Tables)
To reach BCNF, separate the offending dependency (Professor → Subject) into its own table where Professor is the primary key.
1. Professor_Subject Table (Professor is the primary key)
Professor (PK) | Subject |
|---|---|
Dr. Sharma | SQL |
Prof. Verma | Python |
Dr. Rao | SQL |
2. Student_Professor Table (Student_ID, Professor is the composite primary key)
Student_ID (PK, FK) | Professor (PK, FK) |
|---|---|
101 | Dr. Sharma |
101 | Prof. Verma |
102 | Dr. Sharma |
103 | Dr. Rao |
Q45. Difference between 2NF and 3NF?
2NF | 3NF |
|---|---|
Removes partial dependency | Removes transitive dependency |
Must satisfy 1NF | Must satisfy 2NF |
Focuses on composite keys | Focuses on non-key dependencies |
What is denormalization?
Denormalization is the process of intentionally introducing redundancy into a database to improve read performance in certain workloads.
Example: Storing a frequently needed department name with employee records to avoid repeatedly joining tables.
What is a transaction?
A transaction is a logical unit of database operations that should be executed as a single unit.
Example: Transferring ₹1,000 from Account A to Account B.
Steps:
Deduct ₹1,000 from Account A.
Add ₹1,000 to Account B.
Both operations should succeed together.
What are ACID properties?
ACID properties stand for Atomicity, Consistency, Isolation, and Durability, which are four core rules that guarantee database transactions remain accurate and reliable even during errors, power failures or heavy concurrent traffic.
Atomicity (All or Nothing). Every operation inside a transaction must succeed together, or the entire transaction fails and rolls back to its original state. If a ₹500 bank transfer deducts money from Account A but crashes before crediting Account B, atomicity cancels the deduction so no money vanishes.
Consistency (Valid State to Valid State). A transaction must follow all predefined database rules and constraints so data never becomes invalid. For example, if a rule forbids negative balances, any transaction attempting to withdraw more money than available is rejected.
Isolation (No Interference). Multiple transactions running at the exact same time cannot see each other's unfinished changes.
Durability (Permanent Changes). Once a transaction finishes and commits, its changes are permanently saved to non-volatile storage like a hard drive or SSD.
What is COMMIT?
COMMIT permanently saves the changes made by a transaction.
BEGIN;
UPDATE Accounts
SET balance = balance - 1000
WHERE account_id = 1;
COMMIT;What is ROLLBACK?
ROLLBACK reverses uncommitted changes in the current transaction.
BEGIN;
UPDATE Accounts
SET balance = balance - 1000
WHERE account_id = 1;
ROLLBACK;What is SAVEPOINT?
SAVEPOINT creates a point within a transaction to which we can roll back without necessarily cancelling the entire transaction.
BEGIN;
UPDATE Accounts
SET balance = balance - 1000
WHERE account_id = 1;
SAVEPOINT sp1;
UPDATE Accounts
SET balance = balance + 1000
WHERE account_id = 2;
ROLLBACK TO SAVEPOINT sp1;
COMMIT;What are transaction states?
Transaction states are the five distinct stages a database transaction passes through during its lifecycle, from the moment it starts running until it either saves permanently or cancels completely.
Common transaction states:
Active: The transaction starts in this initial state and stays here while executing read and write operations. If all steps finish without errors, it moves forward, if an error occurs, it drops to the failed state.
Partially Committed: The transaction enters this state right after executing its final operation. At this stage, the results exist only in temporary memory and have not yet been written permanently to disk.
Committed: Once temporary memory changes are safely written to permanent storage from the partially committed state, the transaction becomes committed. At this point, the changes are permanent and cannot be undone by a rollback.
Failed: The transaction moves here if a hardware crash, power outage, or rule violation during the active or partially committed phase. No further operations can proceed from this point.
Aborted: After reaching the failed state, the DBMS uses undo logs to roll back all changes made so far and enters the aborted state. Once aborted, the system either kills the transaction permanently or restarts it from scratch.
Terminated: It is the final stage of a database transaction's lifecycle, marking the point where the transaction has completely finished and exited the system.
What is concurrency control?
Concurrency control is the set of techniques a DBMS uses to manage multiple transactions running at the exact same time so they do not interfere with each other or corrupt data.
Its primary goal is to enforce the Isolation property of ACID while keeping the database fast and responsive for thousands of simultaneous users.
What is a dirty read?
A dirty read happens when a transaction reads data that has been modified by another running transaction, but those changes have not been committed yet.
If the second transaction fails and rolls back, the first transaction is left holding invalid, "dirty" data that technically never existed in the database.
What is a phantom read?
It occurs when repeating a query that returns a set of rows produces a different set because another transaction inserted or deleted matching rows.
What are isolation levels?
Transaction isolation levels are database settings that control how and when changes made by one transaction become visible to other concurrent transactions.
Isolation level | General protection |
|---|---|
Read Uncommitted | Lowest isolation; dirty reads possible |
Read Committed | Prevents dirty reads |
Repeatable Read | Prevents dirty and non-repeatable reads |
Serializable | Strongest standard isolation level |
What is an index?
A database index is a data structure that speeds up data retrieval in a database table by letting the database jump directly to matching rows instead of scanning every row.
It works similarly to an index in a book.
CREATE INDEX idx_employee_name
ON Employees(Name);Why do we use indexes?
Faster searching.
Faster filtering.
Improved join performance in suitable queries.
Faster sorting in suitable cases.
Disadvantage: Indexes require additional storage and can slow down INSERT, UPDATE and DELETE operations because indexes may also need updating.
What is the difference between an index and a primary key?
A database index is a data structure that speeds up data retrieval in a database table by letting the database jump directly to matching rows instead of scanning every row.
A primary key uniquely identifies each record in a table.
Many DBMSs automatically create an index to enforce a primary key.
What is a View?
A view is a virtual table based on the result of a SQL query.
Advantages:
Simplifies complex queries.
Can restrict access to selected columns or rows.
Provides an abstraction over underlying tables.
CREATE VIEW IT_Employees AS
SELECT *
FROM Employees
WHERE Dept_ID = 10;What is deadlock in DBMS?
A deadlock occurs when two or more transactions wait indefinitely for resources locked by one another.
Example:
Transaction T1 locks resource A and waits for B.
Transaction T2 locks resource B and waits for A.
Neither can proceed.
What are the four necessary conditions for deadlock?
Mutual Exclusion: A resource can be held by only one transaction at a time.
Hold and Wait: A transaction holds one resource while waiting for another.
No Preemption: Resources cannot be forcibly taken away.
Circular Wait: Transactions form a circular chain of waiting.
What is a deadlock prevention technique?
Deadlock can be prevented by breaking at least one of its necessary conditions.
Eliminate Mutual Exclusion. Resources are made shareable whenever possible so multiple tasks can access them simultaneously without blocking.
Eliminate Hold and Wait. Processes must either request all required resources at once before starting execution, or release all currently held resources before asking for new ones. This ensures a task never sits idle holding one lock while waiting on another.
Allow Preemption (Break No Preemption). If a process holding resources requests another resource that is busy, the system forcibly takes away (preempts) its current resources and adds them to a waiting list.
Eliminate Circular Wait (Resource Ordering). Assign a strict ordering (like priorities) to resources and require processes to request them in increasing order, preventing waiting loops.
What is a database lock?
A database lock is a concurrency control mechanism that restricts access to database resources such as rows, pages, or tables when multiple transactions run at the same time.
Common types:
Shared Lock (S-Lock). Used for read operations (
SELECT). Multiple transactions can hold a shared lock on the same data simultaneously, but no transaction can modify the data until all shared locks are released.Exclusive Lock (X-Lock). Used for write operations (
INSERT,UPDATE,DELETE). Only one transaction can hold an exclusive lock on a resource at a time, blocking all other reads and writes until the transaction finishes.Update Lock (U-Lock). Used when a transaction reads a record with the intent to update it later. It prevents deadlocks caused when two transactions hold shared locks and both try to upgrade to exclusive locks at once.
What is NoSQL?
NoSQL databases are non-relational databases that stores and retrieves data in flexible formats rather than rigid, table-based rows and columns
Four Main Types:
Document databases
Key-value stores
Graph databases
Examples:
MongoDB
Cassandra
Redis
SQL vs NoSQL?
SQL | NoSQL |
|---|---|
Relational | Non-relational |
Structured schemas | Flexible data models |
Tables and relations | Documents, key-value, graphs |
SQL query language | Query mechanisms vary by database |
What is CAP theorem?
The CAP theorem (also known as Brewer's theorem) states that a distributed database system can guarantee at most two of three properties Consistency, Availability and Partition Tolerance at the same time, especially when a network failure splits the system
What is data redundancy?
Data redundancy is the condition where the same piece of data is stored in two or more places within a database or across multiple storage systems which can cause inconsistency and waste storage.
Problems Caused by data Redundancy
Data Inconsistency. If a customer changes their phone number and the database updates three rows but misses a fourth, the system now holds conflicting versions of the truth.
Update Anomalies. Changing a single fact requires finding and rewriting every duplicate copy across the database, which slows down performance and increases the risk of partial updates.
How Databases Manage Redundancy
Normalization: Eliminate unintentional redundancy
Denormalization: Add controlled redundancy
Data Replication: Automatically syncs identical copies of a database across multiple servers for backup and disaster recovery.
What is data integrity?
Data integrity means maintaining the accuracy, consistency and reliability of data throughout its lifecycle.
An entity is a distinct, real-world object, person, place, event, or concept that you want to store information about.
Type | What It Enforces |
|---|---|
Entity Integrity | Every row in a table must represent a unique entity and cannot be duplicated or left empty. |
Referential Integrity | Relationships between linked tables must stay valid so child records never point to missing parent records. |
Domain Integrity | All values in a column must fall within an allowed format, data type or range. |
What is a functional dependency?
A functional dependency X → Y means that a value of X uniquely determines the corresponding value of Y in a relation.
Example:
Student_ID → Student_NameIf Student_ID is unique, it determines the student's name.
UNION vs UNION ALL?
SELECT Name FROM Employees
UNION
SELECT Name FROM Managers;Both UNION and UNION ALL combine the result of two or more
SELECTqueries into a single list, but UNION removes duplicate rows, whereas UNION ALL keeps all rows including duplicates.Because
UNIONmust sort or hash the data to find and remove duplicates,UNION ALLis significantly faster and uses less memory.
CHAR vs VARCHAR?
CHAR stores fixed-length character data.
VARCHAR stores variable-length character data up to a defined limit.
What is a subquery?
A query nested inside another SQL query.
SELECT *
FROM Employees
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
);What is a CTE?
CTE stands for Common Table Expression.
It is defined at the top of a statement using the WITH clause, it acts like a temporary virtual table that you can query immediately inside a SELECT, INSERT, UPDATE, or DELETE statement
Key Benefits and Use Cases
Improves readability. Breaking a massive query into clean, top-to-bottom named steps makes SQL much easier to read, debug and maintain.
Allows code reuse within a query. You can reference the same CTE multiple times inside the main query without rewriting the underlying logic.
WITH HighValueOrders AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000
)
SELECT c.name, h.total_spent
FROM customers c
JOIN HighValueOrders h ON c.customer_id = h.customer_id;