SQL
SQL
ChatGPT said:
c) DQL (Data Query Language)
Got it Let’s build complete SQL full concepts notes step by step.
I’ll structure them from basics to advanced, with explanations, syntax, and examples. • SELECT – retrieve data.
👍
d) DCL (Data Control Language)
• Security and permissions.
SQL Full Concepts Notes • GRANT, REVOKE
6. SELECT Queries
SELECT column1, column2
FROM table_name 10. SQL Functions
WHERE condition
GROUP BY column
HAVING condition a) Aggregate Functions
ORDER BY column ASC|DESC • COUNT(), SUM(), AVG(), MIN(), MAX()
LIMIT n OFFSET m;
b) String Functions
• CONCAT(), LENGTH(), UPPER(), LOWER(), SUBSTRING()
7. Clauses
c) Date Functions
• WHERE → filters rows before grouping
• NOW(), CURDATE(), DATEADD(), DATEDIFF(), EXTRACT()
• GROUP BY → groups rows for aggregate functions
• HAVING → filters groups after aggregation d) Conversion Functions
• ORDER BY → sorts result • CAST(), CONVERT()
11. Views
• Virtual tables based on query.
8. SQL Joins
CREATE VIEW high_salary AS
• INNER JOIN – common rows only SELECT name, salary FROM Employees WHERE salary > 50000;
Perfect You want all important SQL code examples that implement the concepts step by step.
I’ll give you practical SQL queries for each topic, so you can run them on MySQL/Postgres/SQLite.
👍
15. Triggers
• Execute automatically on events.
CREATE TRIGGER before_insert_employee
BEFORE INSERT ON Employees SQL Concepts with Code Examples
FOR EACH ROW
SET NEW.created_at = NOW();
📘
1. Create Database & Table
-- Create a database
16. Normalization CREATE DATABASE company;
• Organize data to reduce redundancy. -- Use database (MySQL)
USE company;
• 1NF – atomic values
-- Create a table
• 2NF – no partial dependency CREATE TABLE Employees (
emp_id INT PRIMARY KEY AUTO_INCREMENT,
• 3NF – no transitive dependency name VARCHAR(50) NOT NULL,
department VARCHAR(50),
• BCNF – stronger 3NF salary DECIMAL(10,2),
hire_date DATE DEFAULT (CURRENT_DATE)
);
6. HAVING Clause
-- Departments with avg salary > 55k
SELECT department, AVG(salary) AS avg_salary 11. Views
FROM Employees
GROUP BY department CREATE VIEW high_salary_employees AS
HAVING AVG(salary) > 55000; SELECT name, salary FROM Employees WHERE salary > 60000;
Got it You want more advanced & practical SQL code examples beyond the essentials.
I’ll extend with real-world use cases, advanced queries, optimization, and special features.
👍
14. Stored Procedure (MySQL example)
DELIMITER //
CREATE PROCEDURE GetAllEmployees()
BEGIN
SELECT * FROM Employees; Advanced SQL Code Examples
END //
DELIMITER ;
CALL GetAllEmployees();
📘
17. CASE Statement
-- Categorize employees based on salary
SELECT name, salary,
CASE
15. Trigger WHEN salary >= 70000 THEN 'High'
WHEN salary BETWEEN 50000 AND 69999 THEN 'Medium'
CREATE TABLE SalaryAudit ( ELSE 'Low'
emp_id INT, END AS salary_level
old_salary DECIMAL(10,2), FROM Employees;
new_salary DECIMAL(10,2),
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
UPDATE Employees SET manager_id = 2 WHERE name = 'Alice'; -- Bob is Alice’s manager
UPDATE Employees SET manager_id = 2 WHERE name = 'Charlie';
UPDATE Employees SET manager_id = 3 WHERE name = 'David';
-- Employees with department entry in Departments table -- Extract year and month
SELECT name FROM Employees e SELECT name, EXTRACT(YEAR FROM hire_date) AS year_hired
WHERE EXISTS ( FROM Employees;
SELECT 1 FROM Departments d WHERE e.dept_id = d.dept_id
); -- Employees hired in last 1 year
SELECT * FROM Employees
-- Same with IN WHERE hire_date >= CURRENT_DATE - INTERVAL '1 year';
SELECT name FROM Employees
WHERE dept_id IN (SELECT dept_id FROM Departments);
-- NTILE (quartiles)
SELECT name, salary,
NTILE(4) OVER(ORDER BY salary DESC) AS quartile
30. Query Optimization FROM Employees;
-- See query plan
EXPLAIN SELECT * FROM Employees WHERE salary > 60000;
Now you have basic → advanced → optimization level SQL code examples. -- Sales table: (month, dept, revenue)
-- Pivot: department-wise monthly revenue
Do you want me to combine all examples into one master .sql script (in correct execution order: SELECT month,
✅
SUM(CASE WHEN dept = 'HR' THEN revenue ELSE 0 END) AS HR_revenue,
schema → insert → queries → advanced features) so you can run it directly in MySQL/Postgres? SUM(CASE WHEN dept = 'IT' THEN revenue ELSE 0 END) AS IT_revenue,
SUM(CASE WHEN dept = 'Finance' THEN revenue ELSE 0 END) AS Finance_revenue
You said: FROM Sales
GROUP BY month;
more advanced concepts
ChatGPT said:
11. Locks
7. Advanced Indexing -- Explicit lock (Postgres)
-- Composite index (multiple columns) BEGIN;
CREATE INDEX idx_dept_salary ON Employees(department, salary); SELECT * FROM Employees WHERE emp_id = 1 FOR UPDATE;
-- This row is locked until COMMIT
-- Unique index
CREATE UNIQUE INDEX idx_unique_name ON Employees(name);
These are next-level SQL concepts you’ll see in enterprise databases, big-data systems, and • CHECK – condition must be true.
interviews. • DEFAULT – default value if none given.
✅
Would you like me to now prepare a step-by-step roadmap (beginner → expert) that tells you which
concepts to practice in order for SQL mastery and interview prep?
You said:
4. Write a query to find the 2nd highest salary.
interview questions and answers Answer:
ChatGPT said:
SELECT MAX(salary)
FROM Employees
Got it You want SQL interview questions with answers. WHERE salary < (SELECT MAX(salary) FROM Employees);
I’ll give you a complete set, covering beginner → intermediate → advanced (theory + query writing).
👍
Or using LIMIT (MySQL/Postgres):
SELECT DISTINCT salary
FROM Employees
ORDER BY salary DESC
📘 SQL Interview Questions & Answers LIMIT 1 OFFSET 1;
5. What is the difference between WHERE and HAVING? • 2NF: No partial dependency (every non-key depends on full PK).
Answer: • 3NF: No transitive dependency (non-key should not depend on another non-key).
• WHERE: Filters rows before grouping. • BCNF: Stronger 3NF.
10. Write query to find employees with salary greater than department average.
Answer:
Intermediate Level SELECT name, salary, department
FROM Employees e
6. Explain types of JOINs. WHERE salary > (SELECT AVG(salary)
🔹
FROM Employees
Answer: WHERE department = [Link]);
• INNER JOIN → only matching rows.
• LEFT JOIN → all rows from left, matching from right.
• RIGHT JOIN → all rows from right, matching from left. Advanced Level
• FULL JOIN → all rows from both tables.
11. What are Window Functions? Example?
🔹
• SELF JOIN → table joins itself. Answer:
• CROSS JOIN → Cartesian product. Window functions perform calculations across a set of rows without collapsing them into one row.
SELECT name, salary,
RANK() OVER(ORDER BY salary DESC) AS rank
FROM Employees;
7. Query to find duplicate records in a table.
Answer:
SELECT name, COUNT(*)
FROM Employees
12. What is a CTE (Common Table Expression)?
GROUP BY name Answer:
HAVING COUNT(*) > 1;
A CTE is a temporary result set defined within WITH clause.
WITH DeptAvg AS (
SELECT department, AVG(salary) AS avg_sal
FROM Employees
8. What is a View? GROUP BY department
Answer: )
SELECT * FROM DeptAvg WHERE avg_sal > 60000;
A view is a virtual table based on the result of a SQL query. It does not store data itself but fetches from
underlying tables.
CREATE VIEW high_salary AS
SELECT name, salary FROM Employees WHERE salary > 60000; 13. Difference between Clustered and Non-Clustered Index.
Answer:
• Clustered Index: Data is physically stored in order of index (one per table, usually PK).
9. Explain Normalization.
• Non-Clustered Index: Separate structure pointing to table rows (can have many per table).
Answer:
Normalization organizes data to remove redundancy:
• 1NF: Atomic values (no repeating groups).
14. Explain ACID properties of a transaction. • Use indexes properly.
Answer: • Avoid SELECT *.
• Atomicity: All or nothing. • Use EXPLAIN PLAN.
• Consistency: Maintain DB rules. • Optimize JOINs (index FK).
• Isolation: Transactions run independently. • Use LIMIT for pagination.
• Durability: Changes persist after commit. • Normalize tables (but sometimes denormalize for reporting).
15. Query to find top 3 employees by salary in each department. 19. What is Row-Level Security?
Answer: Answer:
SELECT name, department, salary Restricts access to specific rows in a table based on user policy. (e.g., HR can only see HR employees).
FROM (
SELECT name, department, salary,
RANK() OVER(PARTITION BY department ORDER BY salary DESC) AS rnk
FROM Employees
) t
20. What’s the difference between OLTP and OLAP databases?
WHERE rnk <= 3; Answer:
• OLTP (Online Transaction Processing): Handles day-to-day operations, normalized schema, fast
reads/writes (e.g., banking system).
16. Explain difference between EXISTS and IN. • OLAP (Online Analytical Processing): Handles analytical queries, denormalized schema, used
Answer: in BI/data warehouses.
• IN: Compares a column with values in a list (good for small lists).
• EXISTS: Returns true if subquery returns rows (better for large tables). This gives you 20 SQL interview questions with strong answers & queries.
-- IN Do you want me to also prepare a separate set of tricky SQL query challenges with solutions (like
✅
SELECT name FROM Employees WHERE dept_id IN (SELECT dept_id FROM Departments); "Nth highest salary", "employees without manager", "employees hired in same month") that often come
-- EXISTS in interviews?
SELECT name FROM Employees e
WHERE EXISTS (SELECT 1 FROM Departments d WHERE e.dept_id = d.dept_id); You said:
more
ChatGPT said:
17. What is a Trigger? Example? Great You want more SQL interview Q&A, especially tricky, real-world, and advanced ones.
Here’s a new set (21–40) with explanations + code.
Answer:
👍
Trigger = automatic action on INSERT/UPDATE/DELETE.
CREATE TRIGGER before_insert_emp
BEFORE INSERT ON Employees
FOR EACH ROW SQL Interview Questions & Answers (Set 2)
SET NEW.hire_date = CURRENT_DATE;
📘
18. How do you optimize SQL queries?
Answer:
Query-Oriented Questions
21. Find employees who earn the highest salary in each department. 26. Find employees with the N-th highest salary (generic).
🔹
Answer: Answer:
-- Replace N with desired number
SELECT name, department, salary
SELECT name, salary
FROM Employees e
FROM (
WHERE salary = (
SELECT name, salary, DENSE_RANK() OVER(ORDER BY salary DESC) AS rnk
SELECT MAX(salary)
FROM Employees
FROM Employees
) t
WHERE department = [Link]
WHERE rnk = N;
);
22. Write a query to fetch the 5th highest salary without using TOP or LIMIT. 27. Query to fetch all employees whose salary is greater than their manager’s salary.
Answer:
Answer:
SELECT [Link] AS employee, [Link], [Link] AS manager, [Link] AS manager_salary
SELECT salary FROM Employees e
FROM ( JOIN Employees m ON e.manager_id = m.emp_id
SELECT salary, DENSE_RANK() OVER(ORDER BY salary DESC) AS rnk WHERE [Link] > [Link];
FROM Employees
) t
WHERE rnk = 5;
28. Write a query to fetch the first 3 characters of each employee’s name.
Answer:
23. Find employees who do not belong to any department.
SELECT SUBSTRING(name, 1, 3) AS short_name FROM Employees;
Answer:
SELECT e.*
FROM Employees e
LEFT JOIN Departments d
ON e.dept_id = d.dept_id 29. Write a query to show department-wise highest and lowest salaries.
WHERE d.dept_id IS NULL; Answer:
SELECT department, MAX(salary) AS max_salary, MIN(salary) AS min_salary
FROM Employees
GROUP BY department;
24. Find employees hired in the same month.
Answer:
SELECT EXTRACT(MONTH FROM hire_date) AS hire_month, COUNT(*) AS emp_count
FROM Employees 30. Write a query to show the cumulative salary expense by department.
GROUP BY EXTRACT(MONTH FROM hire_date) Answer:
HAVING COUNT(*) > 1;
SELECT department, name, salary,
SUM(salary) OVER(PARTITION BY department ORDER BY salary DESC) AS
cumulative_salary
FROM Employees;
25. Find employees with duplicate salaries.
Answer:
SELECT salary, COUNT(*)
FROM Employees
GROUP BY salary
HAVING COUNT(*) > 1;
Conceptual Questions
31. Difference between UNION and UNION ALL. 37. What are Phantom Reads?
🔹
Answer:
Answer:
When a transaction re-executes a query and finds new rows inserted by another transaction → prevented
• UNION: Combines results, removes duplicates. by SERIALIZABLE isolation.
• UNION ALL: Combines results, keeps duplicates (faster).
34. What is the difference between DELETE and TRUNCATE regarding triggers? 40. How do you debug a slow query?
Answer: Answer:
• DELETE activates triggers. • Use EXPLAIN or EXPLAIN ANALYZE.
• TRUNCATE does not fire triggers. • Check missing indexes.
• Rewrite subqueries as JOINs.
Perfect You want Oracle SQL concepts + code examples (Oracle-specific features + ANSI SQL). 4. Joins
I’ll give you a complete Oracle SQL notes + code examples so you can practice directly in Oracle -- Old Oracle Join
SELECT [Link], d.dept_name
👍
Database. FROM employees e, departments d
WHERE e.dept_id = d.dept_id;
-- ANSI Join
SELECT [Link], d.dept_name
FROM employees e
Oracle SQL Concepts & Examples INNER JOIN departments d
ON e.dept_id = d.dept_id;
📘
1. Oracle Data Types
• NUMBER(p,s): Numeric with precision & scale. 5. Subqueries
• VARCHAR2(n): Variable-length string (better than VARCHAR in Oracle). -- Employees earning more than average salary
SELECT name, salary
• CHAR(n): Fixed-length string. FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
• DATE: Stores date + time (to seconds).
• TIMESTAMP: Higher precision (nanoseconds).
• CLOB / BLOB: Character/Binary large objects. 6. Oracle Pseudocolumns
CREATE TABLE employees (
• ROWNUM → row number in result set.
emp_id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL,
• ROWID → unique physical address of row.
hire_date DATE DEFAULT SYSDATE,
salary NUMBER(10,2), SELECT * FROM employees WHERE ROWNUM <= 5; -- Top 5 employees
resume CLOB
); SELECT ROWID, emp_id, name FROM employees; -- Physical row IDs
-- Rank employees by salary SELECT name, salary, yearly_bonus(salary) AS bonus FROM employees;
SELECT name, salary,
RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees;
ChatGPT said:
Perfect Let’s build a dedicated Oracle Interview Q&A guide (theory + Oracle-specific queries).
I’ll go from basic to advanced and include Oracle-only features that often come in interviews.
👍
5. Difference between DELETE, TRUNCATE, and DROP. Advanced Oracle Features
• DELETE: Removes rows, can rollback, triggers fire.
11. What is a Materialized View?
🔹
• TRUNCATE: Removes all rows, faster, no rollback, no triggers.
Answer:
• DROP: Deletes table structure + data permanently. A snapshot table storing results of a query for performance. Can be refreshed (FAST, COMPLETE, ON
DEMAND, ON COMMIT).
CREATE MATERIALIZED VIEW emp_summary
BUILD IMMEDIATE
Query-Based Oracle Q&A REFRESH FAST ON COMMIT
AS
6. Query to fetch top 3 salaries. SELECT dept_id, AVG(salary) AS avg_salary FROM employees GROUP BY dept_id;
🔹
SELECT * FROM (
SELECT name, salary FROM employees ORDER BY salary DESC
) WHERE ROWNUM <= 3;
12. What is the difference between ROWNUM and ROW_NUMBER()?
• ROWNUM: Oracle pseudocolumn, assigned before ORDER BY.
7. Query to get Nth highest salary. • ROW_NUMBER(): Analytic function, assigned after ORDER BY (more reliable).
SELECT salary SELECT name, salary, ROW_NUMBER() OVER(ORDER BY salary DESC) rn
FROM ( FROM employees;
SELECT salary, DENSE_RANK() OVER(ORDER BY salary DESC) rnk
FROM employees
) WHERE rnk = 5;
FOR LOOP
BEGIN 7. Procedures
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Value: ' || i); CREATE OR REPLACE PROCEDURE raise_salary(p_emp_id NUMBER, p_percent NUMBER) IS
BEGIN
UPDATE employees 11. Bulk Operations (Performance)
SET salary = salary + (salary * p_percent / 100)
WHERE emp_id = p_emp_id; FORALL (Bulk DML)
DBMS_OUTPUT.PUT_LINE('Salary updated.');
END; DECLARE
/ TYPE id_array IS TABLE OF employees.emp_id%TYPE;
EXEC raise_salary(1, 10); v_ids id_array := id_array(1, 2, 3);
BEGIN
FORALL i IN v_ids.FIRST..v_ids.LAST
DELETE FROM employees WHERE emp_id = v_ids(i);
END;
/
8. Functions
CREATE OR REPLACE FUNCTION yearly_bonus(p_salary NUMBER)
RETURN NUMBER IS BULK COLLECT (Fetch multiple rows)
BEGIN DECLARE
RETURN p_salary * 0.10; TYPE name_table IS TABLE OF [Link]%TYPE;
END; v_names name_table;
/ BEGIN
SELECT name, salary, yearly_bonus(salary) AS bonus FROM employees; SELECT name BULK COLLECT INTO v_names FROM employees;
FOR i IN 1..v_names.COUNT LOOP
DBMS_OUTPUT.PUT_LINE(v_names(i));
END LOOP;
END;
9. Packages /
Got it You want a complete list of important PL/SQL & Oracle SQL built-in functions with
examples.
👍
I’ll categorize them into String, Numeric, Date/Time, Conversion, Aggregate, Analytical, PL/SQL 2. Numeric Functions
Utility functions. Function Description Example
🔹
SELECT ROUND(123.456,2) FROM dual; →
ROUND(num,n) Round to n decimals
123.46
SELECT TRUNC(123.456,2) FROM dual; →
TRUNC(num,n) Truncate decimals
Oracle & PL/SQL Important Functions (with 123.45
CEIL(num) Smallest integer ≥ num SELECT CEIL(15.2) FROM dual; → 16
Examples) FLOOR(num) Largest integer ≤ num SELECT FLOOR(15.9) FROM dual; → 15
MOD(a,b) Remainder SELECT MOD(17,5) FROM dual; → 2
📘
POWER(a,b) Exponent SELECT POWER(2,3) FROM dual; → 8
1. String Functions SQRT(num) Square root SELECT SQRT(16) FROM dual; → 4
Function Description Example ABS(num) Absolute value SELECT ABS(-15) FROM dual; → 15
Converts to SIGN(num) Returns -1,0,1 SELECT SIGN(-20) FROM dual; → -1
🔹
SELECT UPPER('oracle') FROM dual; →
UPPER()
uppercase ORACLE
LOWER() Converts to SELECT LOWER('HELLO') FROM dual; →
lowercase hello 3. Date & Time Functions
Capitalizes first SELECT INITCAP('hello world') FROM
INITCAP() Function Description Example
letter dual; → Hello World
SYSDATE Current date & time SELECT SYSDATE FROM dual;
🔹
SELECT CONCAT('Oracle','DB') FROM
CONCAT() Concatenate strings SYSTIMESTAMP SELECT SYSTIMESTAMP FROM dual;
dual; → OracleDB Current timestamp
Function Description Example 6. Analytical (Window) Functions
(ns precision)
CURRENT_DATE Function Description Example
Current session date SELECT CURRENT_DATE FROM dual;
ROW_NUMBER( Sequential SELECT name, ROW_NUMBER() OVER(ORDER BY salary
🔹
ADD_MONTHS(date,n SELECT ADD_MONTHS(SYSDATE,3) FROM
) Add months dual;
) number DESC) rn FROM employees;
MONTHS_BETWEEN(d1 SELECT MONTHS_BETWEEN(SYSDATE, RANK() Ranking with SELECT name, RANK() OVER(ORDER BY salary DESC)
,d2) Months diff TO_DATE('01-JAN-2024')) FROM dual; gaps rk FROM employees;
NEXT_DAY(date, SELECT NEXT_DAY(SYSDATE,'MONDAY') DENSE_RANK( Ranking SELECT name, DENSE_RANK() OVER(ORDER BY salary
'DAY') Next given weekday FROM dual; ) without gaps DESC) dr FROM employees;
LAST_DAY(date) SELECT LAST_DAY(SYSDATE) FROM dual; LEAD(expr, SELECT name, salary, LEAD(salary,1) OVER(ORDER
Last day of month Next row value
n) BY salary) nxt FROM employees;
SELECT ROUND(SYSDATE,'MONTH') FROM
ROUND(date, fmt) Round date LAG(expr, Previous row SELECT name, salary, LAG(salary,1) OVER(ORDER
dual;
n) value BY salary) prev FROM employees;
SELECT TRUNC(SYSDATE,'YEAR') FROM
TRUNC(date, fmt) Truncate date FIRST_VALUE SELECT FIRST_VALUE(salary) OVER(ORDER BY salary
dual; First row value
(expr) DESC) FROM employees;
EXTRACT(YEAR FROM SELECT EXTRACT(MONTH FROM SYSDATE)
date) Extract component FROM dual; SELECT LAST_VALUE(salary) OVER(ORDER BY salary
LAST_VALUE(
expr) Last row value DESC ROWS BETWEEN UNBOUNDED PRECEDING AND
TO_CHAR(date, SELECT TO_CHAR(SYSDATE,'DD-MON-YYYY UNBOUNDED FOLLOWING) FROM employees;
format) Date to string HH24:MI') FROM dual;
NTILE(n) Divide into SELECT name, NTILE(4) OVER(ORDER BY salary)
TO_DATE(str, SELECT TO_DATE('01-SEP-2024','DD-MON- quartile FROM employees;
String to date groups
format) YYYY') FROM dual;
CUME_DIST() Cumulative SELECT name, CUME_DIST() OVER(ORDER BY salary)
distribution FROM employees;
PERCENT_RAN SELECT name, PERCENT_RANK() OVER(ORDER BY
4. Conversion Functions K() Relative rank salary) FROM employees;
-- List Tables
\dt
-- Left Join
SELECT [Link], d.dept_name
5. Table Operations FROM employees e
-- Create Table LEFT JOIN departments d ON e.department_id = [Link];
CREATE TABLE employees (
🔹
id SERIAL PRIMARY KEY, -- Full Join
name VARCHAR(100), SELECT [Link], d.dept_name
salary NUMERIC(10,2), FROM employees e
department VARCHAR(50), FULL OUTER JOIN departments d ON e.department_id = [Link];
hire_date DATE DEFAULT CURRENT_DATE
);
-- Insert
INSERT INTO employees (name, salary, department)
VALUES ('Alice', 60000, 'HR'); 8. Indexing
-- Create Index
-- Select CREATE INDEX idx_emp_name ON employees(name);
SELECT * FROM employees;
🔹
-- Unique Index
-- Update CREATE UNIQUE INDEX idx_emp_email ON employees(email);
UPDATE employees SET salary = 65000 WHERE id = 1;
-- Drop Index
-- Delete DROP INDEX idx_emp_name;
DELETE FROM employees WHERE id = 1;
9. Views
6. Constraints -- Create View
CREATE VIEW high_paid AS
🔹
• PRIMARY KEY – unique + not null. SELECT name, salary FROM employees WHERE salary > 70000;
🔹
• FOREIGN KEY – references another table. -- Query View
SELECT * FROM high_paid;
• UNIQUE – ensures uniqueness.
-- Drop View
• NOT NULL – disallows null. DROP VIEW high_paid;
-- Procedure Example
15. Security
CREATE OR REPLACE PROCEDURE update_salary(emp_id INT, inc NUMERIC) -- Roles & Privileges
LANGUAGE plpgsql AS $$ CREATE ROLE readonly;
🔹
BEGIN GRANT CONNECT ON DATABASE testdb TO readonly;
UPDATE employees SET salary = salary + inc WHERE id = emp_id; GRANT USAGE ON SCHEMA public TO readonly;
END; GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;
$$;
Intermediate Level
Q6. Explain WAL (Write Ahead Logging). Q12. What is the difference between Views and Materialized Views?
WAL ensures durability. Changes are first written to the log file before being applied to the database,
🔹
so data is not lost in case of a crash.
👉
• View → Virtual table, always shows live data.
👉
• Materialized View → Stores query result physically, faster, but must be refreshed (REFRESH
Q7. What are indexes in PostgreSQL? MATERIALIZED VIEW).
Indexes speed up data retrieval. Types:
• B-Tree (default, for equality & range).
👉
Q13. Explain Partitioning in PostgreSQL. Q20. How do you optimize PostgreSQL performance?
Splitting large tables into smaller pieces:
• Range Partitioning (by date, number ranges). • Use indexes wisely.
👉 👉
• List Partitioning (by category). • Run VACUUM and ANALYZE regularly.
• Hash Partitioning (hash function). • Use connection pooling (PgBouncer).
• Optimize queries with EXPLAIN ANALYZE.
Q14. What are Window Functions? • Partition large tables.
Functions that perform calculations across a set of rows without collapsing them.
Examples: • Tune PostgreSQL parameters (work_mem, shared_buffers).
👉
• ROW_NUMBER(), RANK(), DENSE_RANK().
This covers 20 PostgreSQL interview questions with answers from beginner → advanced.
• LEAD(), LAG().
Would you like me to also prepare a PostgreSQL Cheat Sheet (commands + functions one-pager PDF)
✅
• FIRST_VALUE(), LAST_VALUE().
like I did for Oracle?
INSERT INTO users (id, name, age) VALUES (uuid(), 'Alice', 25);
Perfect Let’s go deeper into NoSQL with advanced concepts, architecture details, performance
9. When to Use NoSQL? tuning, and more interview Q&A.
👍
• Large, unstructured, or semi-structured data.
• Real-time applications (chat, IoT, analytics).
• High scalability required. Advanced NoSQL Notes
• Flexible schema requirements.
• Cloud-based distributed apps.
1. NoSQL Database Architecture
📘
• Sharding (Horizontal Partitioning)
• Data split across multiple servers.
10. Interview Questions & Answers • Example: MongoDB automatically shards large collections.
Q1. What is NoSQL? • Replication
A: NoSQL is a type of non-relational database designed to handle unstructured, distributed, and large-
• Data copied across nodes for high availability.
scale data with high scalability.
• Types: Master-Slave, Peer-to-Peer.
Q2. Difference between SQL and NoSQL?
A: SQL → structured, fixed schema, relational; NoSQL → schema-less, scalable, supports unstructured • Eventual Consistency
data.
• Not all nodes are updated immediately, but will converge over time.
Q3. Explain CAP theorem in NoSQL.
• MapReduce in NoSQL
A: CAP = Consistency, Availability, Partition tolerance. A NoSQL system can only guarantee two at the
same time. • Used for aggregation & analytics on distributed data.
Proper indexing reduces query time but increases storage. • Data Modeling → Design based on queries, not normalization.
• Sharding keys → Choose wisely to avoid hotspots.
👉
• Replication factor → Balance between performance & durability.
4. Caching in NoSQL • Use TTL (Time to Live) → For expiring data (Redis, Cassandra).
• Redis & Memcached used for fast access.
• Write-through vs Write-back caching strategies.
9. Advanced Interview Questions
Q1. What is Eventual Consistency?
5. Security in NoSQL A: It means updates propagate across nodes with some delay. At any given time, some nodes may return
stale data, but eventually all nodes will be consistent.
• Authentication & Authorization → Role-based access.
Q2. How does Cassandra handle high availability?
• Encryption → At-rest & in-transit.
A: Through peer-to-peer architecture, replication across data centers, and tunable consistency (e.g.,
• Auditing & Logging → Track DB activities. QUORUM, ONE, ALL).
• Example: MongoDB supports SCRAM-SHA-256 authentication. Q3. What is the difference between MongoDB and Cassandra?
• MongoDB → Document DB, great for flexible schema, JSON storage.
• Cassandra → Column DB, great for heavy write loads, time-series, and analytics.
6. Common Use Cases
Q4. What are Secondary Indexes in NoSQL?
• E-commerce → Product catalogs (MongoDB). A: Extra indexes (besides primary key) that allow efficient querying on non-key fields. Supported in
• Real-time analytics → Cassandra + Spark. MongoDB, Cassandra, Neo4j.
• Social media → Graph DB for relationships (Neo4j). Q5. Explain Write Concern in MongoDB.
A: Defines acknowledgment level:
• Caching → Redis.
• w:1 → Acknowledged by primary only.
• IoT & Sensor data → Time-series DB (InfluxDB, Cassandra).
• w:majority → Acknowledged by majority of replicas. • Highly scalable & distributed.
• w:0 → Unacknowledged (fast but risky). Suitable for big data, real-time analytics, IoT, and cloud-native apps.
• Stores data in JSON-like BSON (Binary JSON) format. • Object (embedded docs)
// Show collections
show collections
7. Indexing
// Drop collection
[Link]() [Link]({ name: 1 }) // Ascending index
[Link]({ age: -1 }) // Descending index
[Link]({ name: 1, age: -1 }) // Compound index
Insert Documents
Index improves query performance, but increases write cost.
[Link]({ name: "Alice", age: 25 })
[Link]([
👉
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
])
8. Aggregation Framework
Used for data processing & analytics.
Query Documents
[Link]() // Get all documents Example:
[Link]({ age: 25 }) // Equality filter [Link]([
[Link]({ age: { $gt: 25 } }) // Greater than { $match: { status: "delivered" } },
[Link]({ age: { $gte: 25, $lte: 35 } }) // Range { $group: { _id: "$cust_id", totalAmount: { $sum: "$amount" } } },
[Link]({ name: { $in: ["Alice", "Bob"] } }) { $sort: { totalAmount: -1 } }
])
Update Documents Stages: $match, $group, $sort, $limit, $project, $lookup (join).
[Link](
{ name: "Alice" },
{ $set: { age: 26 } }
)
[Link](
9. Relationships in MongoDB
{ age: { $lt: 30 } }, • Embedded Documents (denormalization, fast reads).
{ $inc: { age: 1 } }
) • References (normalization, smaller docs, extra queries).
Example (embedded):
{
"name": "Alice",
"orders": [ 14. MongoDB Interview Questions
{ "item": "Book", "price": 500 },
{ "item": "Pen", "price": 50 } Q1. What is MongoDB?
] A: A NoSQL document-oriented DB storing data as BSON.
}
Q2. Difference between MongoDB and SQL DB?
A: MongoDB → schema-less, JSON docs, horizontal scaling. SQL → relational, structured schema.
Q3. What is a Replica Set?
10. Replica Sets (High Availability) A: Cluster of MongoDB servers providing redundancy & failover.
• Primary → Accepts reads/writes. Q4. What is Sharding?
• Secondary → Replicas of primary (read-only by default). A: Horizontal partitioning of data across servers for scalability.
• Arbiter → Votes in elections (no data stored). Q5. What is Aggregation in MongoDB?
A: Framework for transforming and analyzing data (similar to SQL GROUP BY).
Ensures automatic failover.
Q6. How does MongoDB ensure high availability?
👉
A: Through Replica Sets.
Q7. Can MongoDB support ACID transactions?
11. Sharding (Scalability) A: Yes, multi-document ACID transactions introduced in version 4.0+.
• Distributes data across multiple servers.
Q8. What is the difference between find() and aggregate()?
• Uses shard key for partitioning. A: find() → simple queries. aggregate() → complex transformations & analytics.
[Link]("mydb")
[Link]("[Link]", { user_id: 1 })
[Link]()
That’s a complete MongoDB notes pack: theory + commands + examples + interview prep.
Do you also want me to prepare a MongoDB Cheat Sheet (one-page quick reference with commands
⚡
+ operators) for revision?
13. MongoDB vs SQL
You said:
Feature SQL MongoDB
more
Data Model Tables (rows/columns) JSON-like Documents
Schema Fixed Flexible ChatGPT said:
Joins Yes $lookup (less efficient) Perfect Let’s go deeper into MongoDB with advanced concepts, performance tuning,
Transactions Strong ACID ACID (since v4.0) architecture, security, and more interview prep.
👍
Scalability Vertical Horizontal (Sharding)
Best Use Structured data Big data, unstructured
• Text Index → For searching text fields.
Advanced MongoDB Notes [Link]({ content: "text" })
[Link]({ $text: { $search: "database" } })
• Use ObjectId → Unique 12-byte identifier (timestamp + machine + PID + counter). [Link]()
• Authorization: Role-Based Access Control (RBAC). Q4. How does MongoDB handle joins?
A: With $lookup in aggregation.
• Encryption:
Q5. What is TTL Index in MongoDB?
• In-transit → TLS/SSL. A: Time-to-Live index automatically deletes documents after a set time.
• At-rest → Encrypted storage engine. [Link]({ createdAt: 1 }, { expireAfterSeconds: 3600 })
• Not best for complex transactions across multiple collections. • Delete students
Now you have MongoDB basic + advanced notes including architecture, storage, replication,
sharding, performance tuning, and security. 3. Insert Sample Data
⚡
[Link]([
Would you like me to create a MongoDB Cheat Sheet (commands + operators + aggregation + { name: "Alice", age: 20, grade: "A", subjects: ["Math", "Physics"], city: "Delhi"
indexes in one page) for fast revision before interviews? },
{ name: "Bob", age: 22, grade: "B", subjects: ["Chemistry", "Biology"], city:
You said: "Mumbai" },
{ name: "Charlie", age: 23, grade: "A", subjects: ["Math", "English"], city:
example implementation project "Delhi" },
{ name: "David", age: 21, grade: "C", subjects: ["History"], city: "Bangalore" }
ChatGPT said:
])
Great idea — let’s create a MongoDB example project that you can run locally to understand how
MongoDB works in a real-world use case.
🚀
We’ll build a Student Management System (CRUD operations with MongoDB).
4. Query Documents
// Find all students
[Link]()
7. Aggregation Examples This small Student Management System project gives you CRUD + indexing + aggregation +
// Count students by city PyMongo integration.
⚡
[Link]([
{ $group: { _id: "$city", totalStudents: { $sum: 1 } } } Do you want me to extend this into a complete Flask API project (REST endpoints: add student,
]) update, delete, analytics) so you can practice full-stack integration with MongoDB?
👉
// Average age by grade
[Link]([ You said:
{ $group: { _id: "$grade", avgAge: { $avg: "$age" } } } xml full notes
])
ChatGPT said:
Got it — let’s create a complete XML (Extensible Markup Language) notes pack with concepts,
syntax, examples, and interview prep.
👍
8. Indexing
// Create index on name
[Link]({ name: 1 })
5. XML Comments
<!-- This is a comment -->
2. Features of XML <Student>
<Name>Alice</Name>
• Extensible → Users define custom tags. </Student>
Example:
defaults: &defaults
👉
role: Developer
location: Remote
9. YAML in Ansible
- name: Install Apache on Ubuntu
employee1: hosts: webservers
name: Alice become: yes
<<: *defaults tasks:
- name: Install apache2
employee2: apt:
name: Bob name: apache2
<<: *defaults state: present
Great Let’s go deeper into YAML with advanced concepts, best practices, real-world examples,
and tricky interview questions.
🚀
4. Complex Data Types
Mapping inside a list
Advanced YAML Notes employees:
- name: Alice
role: Developer
- name: Bob
role: Tester
📘
1. YAML Document Indicators
• --- → Start of a YAML document. List inside a mapping
project:
• ... → End of a YAML document (optional). name: AI System
tech:
Example: - Python
- TensorFlow
---
👉
- YAML
name: Alice
role: Developer
...
Now you have basic + advanced YAML notes with examples from Kubernetes, Docker, Ansible,
GitHub Actions + best practices + interview prep.
✅
Do you want me to prepare a 1-page YAML Cheat Sheet (all syntax rules & examples in one place)
for super quick revision?