TGViewer
Channel Public Channel
SQL Programming Resources

SQL Programming Resources

@sqlanalyst

Find top SQL resources from global universities, cool projects, and learning materials for data analytics.

Admin: @coderfun

Useful links: heylink.me/DataAnalytics

Promotions: @love_data
Subscribers
76.7K
Photos
599
Videos
1
Links
569
Recent Posts 20 shown
Post #2831 1.98K
SQL Interview Series โ€” Part 2

๐Ÿ“Œ Question 2: Find Duplicate Records

Suppose you have an Employee table:

Employee

โ€ข employee_id

โ€ข employee_name

โ€ข department

โ€ข email

โ“ Find all email addresses that appear more than once in the Employee table.

Example:
employee_id | employee_name | email
------------|---------------|-------------------
1           | Amit          | amit@gmail.com
2           | Rahul         | rahul@gmail.com
3           | Priya         | amit@gmail.com
4           | Neha          | neha@gmail.com
5           | Raj           | rahul@gmail.com

Expected result:
email

amit@gmail.com
rahul@gmail.com

๐Ÿ’ก Approach

We need to:

1๏ธโƒฃ Group records by email.

2๏ธโƒฃ Count how many times each email appears.

3๏ธโƒฃ Keep only the emails whose count is greater than 1. 

๐Ÿ“Œ SQL Solution
SELECT email, COUNT(*) AS occurrence_count
FROM Employee
GROUP BY email
HAVING COUNT(*) > 1;

๐Ÿ”Ž Why use HAVING instead of WHERE?

"WHERE" filters individual rows before grouping.

"HAVING" filters groups after "GROUP BY".

Since we want to filter based on "COUNT(*)", we use "HAVING".
GROUP BY email
HAVING COUNT(*) > 1

This means:

"Group employees by email and return only those groups containing more than one record."

๐ŸŽฏ Double Tap โค๏ธ For Part-3
  • โค 13
  • ๐Ÿ‘ 1
Post #2830 1.71K
๐—™๐—ฅ๐—˜๐—˜ ๐—ฅ๐—ฒ๐˜€๐—ผ๐˜‚๐—ฟ๐—ฐ๐—ฒ๐˜€ ๐—ง๐—ผ ๐—Ÿ๐—ฒ๐—ฎ๐—ฟ๐—ป ๐—”๐—œ ๐—ถ๐—ป ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ๐Ÿš€
โ€‹
Explore 6 free resources covering AI fundamentals, tools, deep learning, research and real-world applications.

โœ… 100% Free Learning
โœ… Beginner-Friendly
โœ… AI โ€ข ML โ€ข Deep Learning
โœ… Real-World Applications

๐Ÿ”— ๐—˜๐˜…๐—ฝ๐—น๐—ผ๐—ฟ๐—ฒ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐Ÿ‘‡

https://pdlink.in/4AFHq5R

๐Ÿ“ข Share this valuable opportunity with your friends and classmates!
Post #2829 1.81K
SQL Interview Series โ€” Part 1

Hi guys, let's start a SQL interview series covering frequently asked and important SQL interview questions.

Each part will cover 1 practical interview question with:

โœ… Problem statement

โœ… SQL solution

โœ… Approach

โœ… Interview tip

๐Ÿ“Œ Question 1: Find the Second Highest Salary

Suppose you have an Employee table:

Employee

โ€ข employee_id

โ€ข employee_name

โ€ข salary

Example data:

employee_id| employee_name| salary

1| Amit| 50000

2| Rahul| 80000

3| Priya| 70000

4| Neha| 90000

5| Raj| 80000

โ“ Find the second-highest salary from the Employee table.

๐Ÿ’ก Approach

First, we need to identify the highest salary.

Then, we need the highest salary that is less than the maximum salary.

One simple approach is to use a subquery:
SELECT MAX(salary) AS second_highest_salary
FROM Employee
WHERE salary < (
    SELECT MAX(salary)
    FROM Employee
);

Output:

second_highest_salary

80000

๐Ÿ”Ž Why does this work?

The inner query:
SELECT MAX(salary)
FROM Employee;

returns:

90000

Then the outer query considers only salaries below 90000:

50000

70000

80000

80000

Finally, MAX() returns:

80000

โš ๏ธ Important Interview Point

If the question asks for the second-highest DISTINCT salary, this approach works because duplicate salaries are naturally treated as one value.

For example:

90000

80000

80000

70000

The second-highest distinct salary is still 80000.

๐Ÿ’ฏ Double Tap โค๏ธ For Part-2
  • โค 14
Post #2828 1.26K
๐Ÿง  Real-World SQL Scenario-Based Questions & Answers

1. Get the 2nd highest salary from the Employees table
SELECT MAX(salary) AS SecondHighest  
FROM Employees
WHERE salary < (SELECT MAX(salary) FROM Employees);


2. Find employees without assigned managers
SELECT * FROM Employees  
WHERE manager_id IS NULL;


3. Retrieve departments with more than 5 employees
SELECT department_id, COUNT(*) AS employee_count  
FROM Employees
GROUP BY department_id
HAVING COUNT(*) > 5;


4. List customers who made no orders
SELECT c.name  
FROM Customers c
LEFT JOIN Orders o ON c.id = o.customer_id
WHERE o.id IS NULL;


5. Find the top 3 highest-paid employees
SELECT * FROM Employees  
ORDER BY salary DESC
LIMIT 3;


6. Display total sales for each product
SELECT product, SUM(amount) AS total_sales  
FROM Sales
GROUP BY product;


7. Get employee names starting with 'A' and ending with 'n'
SELECT name FROM Employees  
WHERE name LIKE 'A%n';


8. Show employees who joined in the last 30 days
SELECT * FROM Employees  
WHERE join_date >= CURRENT_DATE - INTERVAL 30 DAY;


๐Ÿ’ฌ Tap โค๏ธ for more!
  • โค 8
Post #2827 1.15K
๐ŸŽ“ ๐—›๐—”๐—ฅ๐—ฉ๐—”๐—ฅ๐—— ๐—จ๐—ก๐—œ๐—ฉ๐—˜๐—ฅ๐—ฆ๐—œ๐—ง๐—ฌ ๐—™๐—ฅ๐—˜๐—˜ ๐—ข๐—ก๐—Ÿ๐—œ๐—ก๐—˜ ๐—–๐—ข๐—จ๐—ฅ๐—ฆ๐—˜๐—ฆ ๐Ÿ˜

Dreaming of learning from one of the worldโ€™s most prestigious universities? Explore Harvardโ€™s online courses and build valuable, career-ready skills from home!

๐Ÿ’ก Beginner-friendly options
โฐ Learn at your own pace
๐ŸŒ Accessible online worldwide
๐ŸŽฏ Ideal for students, freshers and working professionals

๐Ÿ”— ๐—˜๐˜…๐—ฝ๐—น๐—ผ๐—ฟ๐—ฒ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ ๐Ÿ‘‡

https://pdlink.in/4xPUdzU

๐Ÿ“ข Share this valuable opportunity with your friends and classmates!
Post #2826 1.47K
Data Analytics Roadmap
|
|-- Fundamentals
|   |-- Mathematics
|   |   |-- Descriptive Statistics
|   |   |-- Inferential Statistics
|   |   |-- Probability Theory
|   |
|   |-- Programming
|   |   |-- Python (Focus on Libraries like Pandas, NumPy)
|   |   |-- R (For Statistical Analysis)
|   |   |-- SQL (For Data Extraction)
|
|-- Data Collection and Storage
|   |-- Data Sources
|   |   |-- APIs
|   |   |-- Web Scraping
|   |   |-- Databases
|   |
|   |-- Data Storage
|   |   |-- Relational Databases (MySQL, PostgreSQL)
|   |   |-- NoSQL Databases (MongoDB, Cassandra)
|   |   |-- Data Lakes and Warehousing (Snowflake, Redshift)
|
|-- Data Cleaning and Preparation
|   |-- Handling Missing Data
|   |-- Data Transformation
|   |-- Data Normalization and Standardization
|   |-- Outlier Detection
|
|-- Exploratory Data Analysis (EDA)
|   |-- Data Visualization Tools
|   |   |-- Matplotlib
|   |   |-- Seaborn
|   |   |-- ggplot2
|   |
|   |-- Identifying Trends and Patterns
|   |-- Correlation Analysis
|
|-- Advanced Analytics
|   |-- Predictive Analytics (Regression, Forecasting)
|   |-- Prescriptive Analytics (Optimization Models)
|   |-- Segmentation (Clustering Techniques)
|   |-- Sentiment Analysis (Text Data)
|
|-- Data Visualization and Reporting
|   |-- Visualization Tools
|   |   |-- Power BI
|   |   |-- Tableau
|   |   |-- Google Data Studio
|   |
|   |-- Dashboard Design
|   |-- Interactive Visualizations
|   |-- Storytelling with Data
|
|-- Business Intelligence (BI)
|   |-- KPI Design and Implementation
|   |-- Decision-Making Frameworks
|   |-- Industry-Specific Use Cases (Finance, Marketing, HR)
|
|-- Big Data Analytics
|   |-- Tools and Frameworks
|   |   |-- Hadoop
|   |   |-- Apache Spark
|   |
|   |-- Real-Time Data Processing
|   |-- Stream Analytics (Kafka, Flink)
|
|-- Domain Knowledge
|   |-- Industry Applications
|   |   |-- E-commerce
|   |   |-- Healthcare
|   |   |-- Supply Chain
|
|-- Ethical Data Usage
|   |-- Data Privacy Regulations (GDPR, CCPA)
|   |-- Bias Mitigation in Analysis
|   |-- Transparency in Reporting

Free Resources to learn Data Analytics skills๐Ÿ‘‡๐Ÿ‘‡

1. SQL

https://mode.com/sql-tutorial/introduction-to-sql

https://t.me/sqlspecialist/738

2. Python

https://www.learnpython.org/

https://t.me/pythondevelopersindia/873

https://bit.ly/3T7y4ta

https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial

3. R

https://datacamp.pxf.io/vPyB4L

4. Data Structures

https://leetcode.com/study-plan/data-structure/

https://www.udacity.com/course/data-structures-and-algorithms-in-python--ud513

5. Data Visualization

https://www.freecodecamp.org/learn/data-visualization/

https://t.me/Data_Visual/2

https://www.tableau.com/learn/training/20223

https://www.workout-wednesday.com/power-bi-challenges/

6. Excel

https://excel-practice-online.com/

https://t.me/excel_data

https://www.w3schools.com/EXCEL/index.php

Join @free4unow_backup for more free courses

Like for more โค๏ธ

ENJOY LEARNING ๐Ÿ‘๐Ÿ‘
  • โค 3
  • ๐Ÿ‘ 2
Post #2825 1.4K
๐—Ÿ๐—ฒ๐˜ƒ๐—ฒ๐—น ๐—จ๐—ฝ ๐—ฌ๐—ผ๐˜‚๐—ฟ ๐—ฆ๐—ธ๐—ถ๐—น๐—น๐˜€ ๐˜„๐—ถ๐˜๐—ต ๐—ง๐—ต๐—ฒ๐˜€๐—ฒ ๐—š๐—ฎ๐—บ๐—ฒ-๐—–๐—ต๐—ฎ๐—ป๐—ด๐—ถ๐—ป๐—ด ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€!
โ€‹
Looking to learn practical, in-demand skills? These courses cover Generative AI, Cybersecurity, AI tools and Digital Marketing.

๐Ÿ’ซ Learn at your own pace
โšกBuild career-relevant skills
๐Ÿ”ฅPractical learning opportunities

๐—˜๐˜…๐—ฝ๐—น๐—ผ๐—ฟ๐—ฒ ๐˜๐—ต๐—ฒ ๐—–๐—ผ๐˜‚๐—ฟ๐˜€๐—ฒ๐˜€ :-

https://pdlink.in/4z3vOYU

Save this post and share with your friends
Post #2824 1.34K
Answer: Both uncommitted updates are rolled back, assuming the statements executed within the same transaction and the database/session supports the shown transaction behavior.

๐Ÿ”ฅ Mini Challenge

Imagine an order-processing system. You need to:

1. Create an order.

2. Add an order item.

3. Reduce inventory.

4. Commit everything if successful.

5. Roll back if a critical operation fails.

Write a transaction structure for this workflow.

Solution:

BEGIN;

INSERT INTO orders (order_id, customer_id, order_amount)
VALUES (1001, 101, 5000);

INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1001, 501, 2);

UPDATE products
SET stock_quantity = stock_quantity - 2
WHERE product_id = 501
AND stock_quantity >= 2;

COMMIT;


In a real application, you would also validate that each critical operation succeeded and handle errors according to the database/application's transaction mechanism.

If a critical operation fails:

ROLLBACK;


๐ŸŽฏ Key Takeaway

Remember:

โ€ข TRANSACTION โ†’ Group related operations into one unit

โ€ข COMMIT โ†’ Save changes

โ€ข ROLLBACK โ†’ Undo uncommitted changes

โ€ข SAVEPOINT โ†’ Create a rollback point

โ€ข ACID โ†’ Atomicity โ†’ Consistency โ†’ Isolation โ†’ Durability

The most important practical lesson:

ยซBefore making large UPDATE or DELETE changes, first run the corresponding SELECT and verify exactly which rows will be affected.ยป

Transactions help protect data, but safe SQL also depends on careful query design, validation, permissions, and understanding your database's transaction behavior.

Double Tap โค๏ธ For More
  • โค 3
Post #2823 779
The exact workflow should follow your organization's production-change and approval procedures.

29๏ธโƒฃ COMMIT vs SAVEPOINT vs ROLLBACK

Remember:

โ€ข COMMIT โ†’ Save the transaction

โ€ข ROLLBACK โ†’ Undo uncommitted transaction changes

โ€ข SAVEPOINT โ†’ Mark a point inside a transaction

โ€ข ROLLBACK TO SAVEPOINT โ†’ Undo changes after that point

Example:

BEGIN;

UPDATE customers
SET status = 'Active'
WHERE customer_id = 101;

SAVEPOINT s1;

UPDATE customers
SET status = 'Inactive'
WHERE customer_id = 102;

ROLLBACK TO SAVEPOINT s1;

COMMIT;


The first update can remain while the second update is rolled back, subject to the database's transaction semantics.

30๏ธโƒฃ Common Mistakes

โŒ Mistake 1: Forgetting COMMIT โ€” You may make changes but not persist them as intended.

โŒ Mistake 2: Assuming ROLLBACK always works โ€” If the changes have already been committed, a normal rollback cannot undo them.

โŒ Mistake 3: Running UPDATE without checking the WHERE condition โ€” Dangerous:

UPDATE customers SET status = 'Inactive';


Safer workflow:

SELECT * FROM customers WHERE ...;
UPDATE customers SET status = 'Inactive' WHERE ...;


โŒ Mistake 4: Assuming transaction behavior is identical everywhere โ€” Database systems differ in areas such as:

- Autocommit

- DDL transactions

- Isolation

- Locking

- Savepoints

- Error handling

๐ŸŽฏ Interview Questions

โ€ข

Q1. What is a transaction? A transaction is a logical unit of one or more database operations that are handled together.

โ€ข

Q2. What does COMMIT do? It commits the transaction's changes.

โ€ข

Q3. What does ROLLBACK do? It reverses uncommitted changes in the transaction.

โ€ข

Q4. What is SAVEPOINT? A savepoint marks a point inside a transaction to which you can potentially roll back without undoing the entire transaction.

โ€ข

Q5. What does ACID stand for?

A โ†’ Atomicity,

C โ†’ Consistency,

I โ†’ Isolation,

D โ†’ Durability

โ€ข

Q6. What is atomicity? It treats the transaction as a logical unit so that its operations are committed together or rolled back as appropriate.

โ€ข

Q7. What is isolation? It controls how concurrent transactions interact and what changes they can see.

โ€ข

Q8. What is durability? Committed changes are intended to survive failures according to the database's durability mechanisms.

โ€ข

Q9. What is autocommit? A mode where individual statements may be committed automatically.

โ€ข

Q10. What is a dirty read? Reading data changed by another transaction before that transaction commits.

๐Ÿง  Practice Questions

Practice 1 Write a transaction that updates a customer's status and commits it.

BEGIN;
UPDATE customers SET status = 'Active' WHERE customer_id = 101;
COMMIT;


Practice 2 Update a customer's status but roll back the change.

BEGIN;
UPDATE customers SET status = 'Inactive' WHERE customer_id = 101;
ROLLBACK;


Practice 3 Create a savepoint after the first update.

BEGIN;
UPDATE customers SET status = 'Active' WHERE customer_id = 101;
SAVEPOINT customer_update;
UPDATE customers SET status = 'Inactive' WHERE customer_id = 102;
ROLLBACK TO SAVEPOINT customer_update;
COMMIT;


Practice 4 Before executing this UPDATE:

UPDATE orders SET status = 'Cancelled' WHERE order_date < DATE '2025-01-01';


write a SELECT that lets you inspect the affected records.

SELECT * FROM orders WHERE order_date < DATE '2025-01-01';


Practice 5 Explain what happens here:

BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE account_id = 101;
UPDATE accounts SET balance = balance + 5000 WHERE account_id = 202;
ROLLBACK;
Post #2822 424
will behave identically across every database.

Always check the behavior of your specific database.

21๏ธโƒฃ Transaction Isolation Levels

Isolation is one of the deeper transaction concepts.

Common isolation levels include:

โ€ข READ UNCOMMITTED

โ€ข READ COMMITTED

โ€ข REPEATABLE READ

โ€ข SERIALIZABLE

Some databases also support additional modes or implement these differently.

The general idea is:

โ€ข More isolation โ†“ Stronger guarantees between concurrent transactions โ†“ Potentially more locking/contention or reduced concurrency

The exact behavior is database-specific.

22๏ธโƒฃ READ UNCOMMITTED

This is the weakest commonly described isolation level.

A transaction may potentially see changes that another transaction has not committed.

This can lead to phenomena such as:

โ€ข Dirty reads

It is not appropriate for every workload.

23๏ธโƒฃ READ COMMITTED

A transaction generally sees committed data rather than another transaction's uncommitted changes.

This is a common default isolation level in some database systems.

However, behavior across databases can differ.

24๏ธโƒฃ REPEATABLE READ

The goal is to ensure that repeated reads within a transaction provide a stable view of previously read data under the database's isolation model.

It provides stronger guarantees than READ COMMITTED.

The exact implementation differs between database systems.

25๏ธโƒฃ SERIALIZABLE

This provides the strongest standard isolation level among these four.

The goal is to make concurrent transactions behave as if they were executed serially.

Conceptually: Transaction A โ†“ Transaction B rather than allowing certain conflicting operations to interact concurrently.

The trade-off can be reduced concurrency or increased contention.

26๏ธโƒฃ Common Transaction Problems

When transactions run concurrently, several phenomena can occur depending on the isolation level and database.

Dirty Read

โ€ข Transaction A reads data changed by Transaction B before B commits.

โ€ข B โ†’ UPDATE โ†“ A โ†’ reads uncommitted value โ†“ B โ†’ ROLLBACK

โ€ข A saw a value that never became permanent.

Non-Repeatable Read

โ€ข A transaction reads the same row twice and gets different values because another transaction committed a change between the reads.

โ€ข A โ†’ Read = 100

โ€ข B โ†’ Update = 200, B โ†’ COMMIT

โ€ข A โ†’ Read again = 200

Phantom Read

โ€ข A transaction repeats a query and sees additional or missing rows because another transaction inserted or deleted matching rows.

โ€ข A โ†’ SELECT ... WHERE amount > 1000 โ†’ 5 rows

โ€ข B โ†’ INSERT another matching row, B โ†’ COMMIT

โ€ข A โ†’ same query โ†’ 6 rows

The exact handling depends on the database and isolation level.

27๏ธโƒฃ Transaction vs Query

Don't confuse these concepts.

A query is a SQL statement such as:

SELECT * FROM customers;


A transaction is a logical unit containing one or more operations.

For example:

Transaction

โ”‚

โ”œโ”€โ”€ INSERT

โ”œโ”€โ”€ UPDATE

โ”œโ”€โ”€ UPDATE

โ””โ”€โ”€ COMMIT

So:

โ€ข Query โ†’ Individual SQL operation

โ€ข Transaction โ†’ Unit of work containing one or more operations

28๏ธโƒฃ Real-World Analytics Example

Suppose an operations team needs to correct payment statuses.

There are 10,000 affected records.

Instead of blindly running:

UPDATE payments
SET status = 'Completed'
WHERE payment_date IS NOT NULL;


first inspect:

SELECT payment_id, status, payment_date
FROM payments
WHERE payment_date IS NOT NULL;


Then, if the correction is confirmed:

BEGIN;

UPDATE payments
SET status = 'Completed'
WHERE payment_date IS NOT NULL;

SELECT COUNT(*) AS updated_rows
FROM payments
WHERE payment_date IS NOT NULL
AND status = 'Completed';

COMMIT;


If the validation reveals an unexpected result:

ROLLBACK;
Post #2821 378
ROLLBACK;


If everything is correct:

COMMIT;


This can be useful when performing potentially dangerous data modifications.

1๏ธโƒฃ8๏ธโƒฃ A Safe Pattern for Data Changes

Before executing a large UPDATE or DELETE, analysts often first run a SELECT using the same condition.

Instead of immediately doing:

UPDATE customers
SET status = 'Inactive'
WHERE last_order_date < DATE '2024-01-01';


first check:

SELECT *
FROM customers
WHERE last_order_date < DATE '2024-01-01';


Then, where transaction support and operational rules permit:

BEGIN;

UPDATE customers
SET status = 'Inactive'
WHERE last_order_date < DATE '2024-01-01';

-- Verify the affected rows

COMMIT;


If something looks wrong:

ROLLBACK;


This is a valuable habit when working with production data.

1๏ธโƒฃ9๏ธโƒฃ Transactions and Autocommit

Many database clients use an autocommit mode.

When autocommit is enabled, individual statements may be committed automatically.

For example:

UPDATE customers
SET status = 'Active'
WHERE customer_id = 101;


may be committed immediately.

That means you may not be able to simply run:

ROLLBACK;


after the statement has already been committed.

The exact behavior depends on:

โ€ข Database system

โ€ข Client/tool

โ€ข Connection settings

โ€ข Transaction configuration

Always understand the transaction mode before modifying production data.

20๏ธโƒฃ Transactions and DDL

Statements such as:

โ€ข CREATE

โ€ข ALTER

โ€ข DROP

are DDL statements.

Their transaction behavior varies significantly across database systems.

Some databases implicitly commit certain DDL operations.

Therefore, don't assume:

BEGIN;
DROP TABLE test_table;
ROLLBACK;
Post #2820 455
The transaction can continue from there.

Conceptually:

Transaction starts โ†“ Update 101 โ†“ SAVEPOINT โ†“ Update 102 โ†“ ROLLBACK TO SAVEPOINT โ†“ Update 101 remains, Update 102 is undone

Exact savepoint syntax varies by database.

8๏ธโƒฃ Why Are Transactions Important?

Imagine an order-processing system.

Creating an order might require:

1. Create order

2. Create order items

3. Reduce inventory

4. Record payment

5. Update customer balance

If step 4 fails after steps 1โ€“3 succeed, you could end up with inconsistent data.

A transaction can group these operations together.

BEGIN โ†“ Create order โ†“ Create order items โ†“ Reduce inventory โ†“ Record payment โ†“ Update balance โ†“ COMMIT

If a critical operation fails: ROLLBACK

This helps keep the system consistent.

9๏ธโƒฃ The ACID Properties

Transactions are commonly explained using the ACID properties:

โ€ข A โ†’ Atomicity

โ€ข C โ†’ Consistency

โ€ข I โ†’ Isolation

โ€ข D โ†’ Durability

These are fundamental database concepts.

๐Ÿ”Ÿ Atomicity

Atomicity means a transaction is treated as a logical unit.

Either the required transaction changes are committed, or the transaction can be rolled back.

Example:

โ€ข Transfer โ‚น1,000

โ€ข Debit account A + Credit account B

You don't want only one side of the transfer to succeed.

Conceptually:

โ€ข Both succeed โ†’ COMMIT

โ€ข Critical failure โ†’ ROLLBACK

1๏ธโƒฃ1๏ธโƒฃ Consistency

Consistency means a successful transaction should leave the database in a state that satisfies its defined rules and constraints.

For example:

โ€ข Account balance must not violate business/database constraints

Suppose a database has:

CHECK (balance >= 0)


An operation that violates the constraint may fail rather than leaving the database in an invalid state.

1๏ธโƒฃ2๏ธโƒฃ Isolation

Isolation deals with how concurrent transactions interact with each other.

Imagine Transaction A + Transaction B both accessing the same data at the same time.

The database needs rules governing what each transaction can see while the other is running.

This becomes especially important in:

โ€ข Banking

โ€ข Payments

โ€ข Order processing

โ€ข Inventory systems

โ€ข Financial systems

โ€ข High-volume applications

1๏ธโƒฃ3๏ธโƒฃ Durability

Once a transaction has successfully committed, its changes are intended to survive subsequent failures according to the database's durability guarantees.

Conceptually:

COMMIT โ†“ Data saved โ†“ System failure โ†“ Committed changes remain

Durability is supported by database mechanisms such as transaction logs and recovery systems.

1๏ธโƒฃ4๏ธโƒฃ Transaction Example โ€” Bank Transfer

Suppose:

โ€ข Account 101 โ†’ โ‚น50,000

โ€ข Account 202 โ†’ โ‚น30,000

โ€ข Transfer: โ‚น5,000

SQL:

BEGIN;

UPDATE accounts
SET balance = balance - 5000
WHERE account_id = 101;

UPDATE accounts
SET balance = balance + 5000
WHERE account_id = 202;

COMMIT;


After success:

โ€ข Account 101 โ†’ โ‚น45,000

โ€ข Account 202 โ†’ โ‚น35,000

โ€ข The total money remains: โ‚น80,000

1๏ธโƒฃ5๏ธโƒฃ What If Something Fails?

Suppose the second update fails.

Without appropriate transaction handling:

โ€ข Account 101 โ‚น50,000 โ†’ โ‚น45,000

โ€ข Account 202 Still โ‚น30,000

The system has become inconsistent.

With a transaction:

BEGIN โ†“ Debit Account 101 โ†“ Credit Account 202 โŒ โ†“ ROLLBACK

The debit can be rolled back along with the other uncommitted changes.

1๏ธโƒฃ6๏ธโƒฃ Transactions with INSERT

Transactions aren't limited to UPDATE.

Example:

BEGIN;

INSERT INTO orders (order_id, customer_id, order_amount)
VALUES (1001, 101, 5000);

INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1001, 501, 2);

COMMIT;


Both operations belong to the transaction.

1๏ธโƒฃ7๏ธโƒฃ Transactions with DELETE

You can also use transactions before deleting records.

For example:

BEGIN;

DELETE FROM orders
WHERE order_date < DATE '2020-01-01';


Before committing, you can inspect the result.

If it isn't what you expected:
  • โค 2
Post #2819 887
๐Ÿš€ SQL Roadmap 2026 โ€” Part 19

SQL Transactions โ€” COMMIT, ROLLBACK & SAVEPOINT

SQL isn't only about retrieving data.

In real-world systems, SQL is also used to:

โ€ข Insert records

โ€ข Update records

โ€ข Delete records

โ€ข Process financial transactions

โ€ข Move money between accounts

โ€ข Update multiple related tables

โ€ข Maintain data consistency

But what happens when a process involves multiple SQL statements and one of them fails?

That's where SQL transactions become important.

1๏ธโƒฃ What Is a Transaction?

A transaction is a group of one or more SQL operations that are treated as a logical unit of work.

For example, transferring money between two accounts may involve:

โ€ข Account A โ†’ Deduct โ‚น1,000

โ€ข Account B โ†’ Add โ‚น1,000

These two operations should normally be treated as one transaction.

You don't want this situation:

โ€ข Account A โ†’ โ‚น1,000 deducted โœ…

โ€ข Account B โ†’ โ‚น1,000 not credited โŒ

The transaction mechanism helps maintain consistency.

2๏ธโƒฃ Basic Transaction Flow

BEGIN TRANSACTION

โ†“

SQL Statement 1

โ†“

SQL Statement 2

โ†“

SQL Statement 3

โ†“

COMMIT

If something goes wrong:

BEGIN TRANSACTION

โ†“

SQL Statement 1

โ†“

SQL Statement 2 โŒ

โ†“

ROLLBACK

โ†“

Changes undone

3๏ธโƒฃ BEGIN TRANSACTION

Depending on the database, you may see:

BEGIN TRANSACTION;
-- or
BEGIN;


Some database systems handle transaction boundaries differently, so exact syntax varies.

For example:

BEGIN;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 101;


The transaction has started.

4๏ธโƒฃ COMMIT

"COMMIT" permanently saves the changes made during the transaction.

Example:

BEGIN;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 101;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 202;

COMMIT;


After the transaction is successfully committed, the changes become durable according to the database's transaction rules.

5๏ธโƒฃ ROLLBACK

"ROLLBACK" reverses uncommitted changes within the transaction.

Example:

BEGIN;

UPDATE accounts
SET balance = balance - 1000
WHERE account_id = 101;

UPDATE accounts
SET balance = balance + 1000
WHERE account_id = 202;

ROLLBACK;


The changes made in that transaction are undone.

6๏ธโƒฃ COMMIT vs ROLLBACK

This is a common interview question.

โ€ข COMMIT โ†’ Save the transaction

โ€ข ROLLBACK โ†’ Undo uncommitted changes

Example:

BEGIN;
UPDATE customers
SET status = 'Inactive'
WHERE customer_id = 101;
COMMIT;


The change is committed.

Whereas:

BEGIN;
UPDATE customers
SET status = 'Inactive'
WHERE customer_id = 101;
ROLLBACK;


The uncommitted update is rolled back.

7๏ธโƒฃ SAVEPOINT

Sometimes you don't want to roll back the entire transaction.

You can create a "SAVEPOINT".

Example:

BEGIN;

UPDATE customers
SET status = 'Active'
WHERE customer_id = 101;

SAVEPOINT customer_update;

UPDATE customers
SET status = 'Inactive'
WHERE customer_id = 102;


Now suppose you don't want the second update.

You can roll back to the savepoint:

ROLLBACK TO SAVEPOINT customer_update;
  • โค 3
Post #2818 1.32K
๐Ÿš€ ๐—š๐—ผ๐—ผ๐—ด๐—น๐—ฒ ๐—ฃ๐—ฟ๐—ผ๐—ณ๐—ฒ๐˜€๐˜€๐—ถ๐—ผ๐—ป๐—ฎ๐—น ๐—–๐—ฒ๐—ฟ๐˜๐—ถ๐—ณ๐—ถ๐—ฐ๐—ฎ๐˜๐—ฒ๐˜€ ๐—ถ๐—ป ๐——๐—ฎ๐˜๐—ฎ ๐—”๐—ป๐—ฎ๐—น๐˜†๐˜๐—ถ๐—ฐ๐˜€ & ๐—”๐—œ! ๐Ÿ“Š

Explore these 4 Google learning programs and develop practical, career-relevant skills.

๐ŸŽ“ Explore the programs:
1๏ธโƒฃ Google Data Analytics Professional Certificate
2๏ธโƒฃ Google Business Intelligence Professional Certificate
3๏ธโƒฃ Google AI Essentials
4๏ธโƒฃ Google Advanced Data Analytics Professional Certificate

๐Ÿ”— ๐—˜๐—ป๐—ฟ๐—ผ๐—น๐—น ๐—ณ๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜ ๐Ÿ‘‡:-

https://pdlink.in/4htgIEW

๐Ÿ“Œ Save this post and share it with someone interested in Data Analytics or AI!
Post #2817 1.93K
SQL Interview Questions with Answers

1. What is a primary key and why is it important in a database?
   - A primary key is a unique identifier for each record in a database table. It is important because it ensures that each record can be uniquely identified and helps maintain data integrity by preventing duplicate or null values.

2. Can you explain the difference between INNER JOIN and OUTER JOIN in SQL?
   - INNER JOIN returns only the rows that have matching values in both tables, while OUTER JOIN returns all rows from one table and the matched rows from the other table (or null values if there is no match).

3. How do you optimize a SQL query for better performance?
   - To optimize a SQL query, you can use indexes, avoid using SELECT *, limit the number of columns selected, use appropriate data types, and avoid using functions in WHERE clauses.

4. What is normalization and why is it important in database design?
   - Normalization is the process of organizing data in a database to reduce redundancy and dependency. It is important because it helps improve data integrity, reduce storage space, and make data maintenance easier.

5. How do you handle missing data in SQL queries?
   - You can handle missing data in SQL queries by using functions like COALESCE or IFNULL to replace null values with a default value, or by using the IS NULL or IS NOT NULL operators to filter out records with missing data.

6. Can you explain the difference between GROUP BY and HAVING clauses in SQL?
   - GROUP BY is used to group rows that have the same values into summary rows, while HAVING is used to filter groups based on specified conditions after the GROUP BY clause has been applied.

7. How do you identify and remove duplicate records from a database table?
   - You can identify duplicate records by using the DISTINCT keyword or by using the GROUP BY clause with COUNT() function. To remove duplicate records, you can use the DELETE statement with a subquery that identifies the duplicates.

8. How do you write a subquery in SQL?
   - A subquery is a query nested within another query. You can write a subquery by enclosing the inner query within parentheses and using it as a part of the outer query's WHERE, FROM, or SELECT clause.

9. What is the difference between a view and a table in SQL?
   - A table stores actual data in a database, while a view is a virtual table that displays data from one or more tables based on a predefined query. Views do not store data themselves but provide a way to present data in a specific format.

10. How do you use indexes to improve query performance in SQL?
    - Indexes are used to speed up data retrieval in SQL queries by creating an ordered list of values for one or more columns in a table. You can create indexes on columns frequently used in WHERE, JOIN, or ORDER BY clauses to improve query performance.

Hope it helps :)
  • โค 5
Post #2816 1.55K
๐Ÿš€ ๐๐ž๐œ๐จ๐ฆ๐ž ๐š๐ง ๐€๐ˆ ๐„๐ง๐ ๐ข๐ง๐ž๐ž๐ซ ๐ข๐ง ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ”

๐ŸŽฏ Choose Your Learning Track:

๐Ÿ’ป Java Full Stack + AI Engineering
๐ŸŒ MERN Full Stack + AI Engineering

Placement Highlights: โ‚น41 LPA highest package | โ‚น7.4 LPA average package | 2,000+ students placed | 500+ hiring partners

๐Ÿ”— ๐—•๐—ผ๐—ผ๐—ธ ๐—™๐—ฅ๐—˜๐—˜ ๐——๐—ฒ๐—บ๐—ผ ๐—–๐—น๐—ฎ๐˜€๐˜€ :- https://pdlink.in/4fWJVID

โšก AI is creating new career opportunitiesโ€”start building the skills companies need in 2026!
Post #2815 1.59K
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 101;


If supported by your database:

EXPLAIN ANALYZE
SELECT *
FROM orders
WHERE customer_id = 101;


๐Ÿ”ฅ Mini Challenge

You have an "orders" table containing 50 million

rows:

โ€ข order_id

โ€ข customer_id

โ€ข order_date

โ€ข status

โ€ข region

โ€ข order_amount

The following query is running slowly:

SELECT
order_id,
order_date,
order_amount
FROM orders
WHERE customer_id = 5001
AND order_date >= DATE '2026-01-01'
AND status = 'Completed';


Think about:

1. Which columns are being filtered?

2. Would a composite index be worth investigating?

3. Which column should come first?

4. Should you use "SELECT *"?

5. How would you inspect the execution plan?

6. Would the index always be used?

7. What happens to performance when the table receives millions of new rows?

Possible candidate to investigate:

CREATE INDEX idx_orders_customer_date
ON orders(customer_id, order_date);


Then inspect the query:

EXPLAIN
SELECT
order_id,
order_date,
order_amount
FROM orders
WHERE customer_id = 5001
AND order_date >= DATE '2026-01-01'
AND status = 'Completed';


Don't automatically assume this is the optimal index.

Use the execution plan, data distribution, workload, and database-specific behavior to determine whether it actually helps.

๐ŸŽฏ Key Takeaway

Remember:

INDEX โ†’ Helps the database find data efficiently

COMPOSITE INDEX โ†’ Index on multiple columns

EXPLAIN โ†’ Inspect how the database plans to execute a query

SELECTIVITY โ†’ How much a filter narrows the data

And the most important principle:

More indexes โ‰  Always faster

Good indexing + Good query design + Execution-plan analysis = Better SQL performance

A strong Data Analyst doesn't just write SQL that produces the correct answer.

They also understand how that SQL behaves when the data grows from thousands of rows to millions or billions. ๐Ÿš€

๐ŸŽฏ Double Tap โค๏ธ For More
  • โค 6
Post #2814 917
Why?

Because the query filters on:

customer_id

โ€ข order_date

The database can then evaluate the index as part of its execution strategy.

But you should verify the impact using an execution plan and real workload data.

30๏ธโƒฃ Query Optimization Checklist

When you have a slow SQL query, ask:

Step 1

Do I actually need all columns? SELECT * may be unnecessary.

Step 2

Can I filter earlier? WHERE can reduce the amount of data processed.

Step 3

Are JOIN conditions correct? Check: ON a.id = b.id

Step 4

Could a suitable index help? Look at frequently used WHERE, JOIN, ORDER BY columns.

Step 5

Is the index being used? Check the execution plan.

Step 6

Am I processing unnecessary rows? Look at the data volume.

Step 7

Are functions preventing efficient access? For example: WHERE UPPER(name) = ...

Step 8

Am I creating too many indexes? Indexes also have costs.

๐Ÿ’ผ Data Analyst Example

Imagine a dashboard queries:

SELECT
customer_id,
SUM(order_amount) AS total_sales
FROM orders
WHERE order_date >= DATE '2026-01-01'
GROUP BY customer_id;


The table contains:

100 million orders

Potential performance considerations include:

1. Is order_date indexed?

2. How selective is the date filter?

3. How many rows are processed?

4. Is partitioning available?

5. What does EXPLAIN show?

6. Is the aggregation expensive?

7. Is the dashboard requesting this data repeatedly?

A strong analyst doesn't immediately say:

ยซ"Create an index."ยป

Instead, they investigate the execution plan and workload first.

๐ŸŽฏ Interview Questions

Q1. What is an index?

An index is a database structure that can help locate rows more efficiently.

Q2. Why are indexes useful?

They can improve read performance for suitable queries, especially when searching or joining on indexed columns.

Q3. Can indexes slow down INSERT operations?

Yes. The database may need to maintain indexes when rows are inserted.

Q4. Can indexes slow down UPDATE and DELETE?

Yes, depending on which indexed columns are affected and the database implementation.

Q5. What is a composite index?

An index containing multiple columns.

CREATE INDEX idx_customer_date
ON orders(customer_id, order_date);


Q6. Does the order of columns in a composite index matter?

Yes. The leading columns strongly influence which queries can efficiently use the index.

Q7. Does every query use an index if one exists?

No. The optimizer decides whether using an index is beneficial.

Q8. What is EXPLAIN?

It is a command or feature used to inspect a query's execution plan, with syntax varying by database.

Q9. What is selectivity?

It describes how effectively a condition narrows the number of matching rows.

Q10. Why shouldn't you index every column?

Indexes consume storage and require maintenance during data modifications, so excessive indexing can hurt write performance.

๐Ÿง  Practice Questions

Practice 1

Create an index on "customer_id":

CREATE INDEX idx_orders_customer_id
ON orders(customer_id);


Practice 2

Create a composite index using customer and date:

CREATE INDEX idx_orders_customer_date
ON orders(customer_id, order_date);


Practice 3

Create a unique index on email:

CREATE UNIQUE INDEX idx_customers_email
ON customers(email);


Practice 4

Write a query that could potentially benefit from an index on "customer_id":

SELECT
order_id,
order_date,
order_amount
FROM orders
WHERE customer_id = 101;


Practice 5

Inspect the execution plan:
  • โค 2
Post #2813 422
Don't retrieve every transaction and filter it later in Python or Excel if the database can efficiently perform the filtering.

A good principle is:

ยซLet the database do the data filtering and aggregation whenever practical.ยป

24๏ธโƒฃ Execution Plans

One of the most important tools for understanding SQL performance is the execution plan.

An execution plan shows how the database intends to execute your query.

It can reveal things such as:

โ€ข Table Scan

โ€ข Index Scan

โ€ข Index Seek

โ€ข Join Strategy

โ€ข Sort

โ€ข Aggregation

โ€ข Estimated Rows

โ€ข Actual Rows

โ€ข Cost

Different databases use different terminology.

25๏ธโƒฃ EXPLAIN

Many SQL databases support "EXPLAIN".

For example:

EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 101;


This lets you inspect the planned execution strategy.

Some databases support:

EXPLAIN ANALYZE

which can provide information about actual execution as well.

Exact syntax and output vary by database.

26๏ธโƒฃ Table Scan vs Index Access

Imagine a table with:

10,000,000 rows

A table scan may mean the database reads a large portion of the table to find matching records.

Conceptually:

10 million rows

โ†“

Check rows

โ†“

Find matching rows

An index-based access path may instead look more like:

Index

โ†“

Locate matching keys

โ†“

Fetch relevant rows

For highly selective queries, the second approach can be much more efficient.

But if a query needs a large percentage of the table, scanning the table may actually be more efficient.

This is why the optimizer chooses the execution strategy.

27๏ธโƒฃ Selectivity

Selectivity describes how effectively a condition narrows down the data.

Consider:

WHERE customer_id = 100245

If customer IDs are unique, this may return one row.

Highly selective.

Now consider:

WHERE country = 'India'

If 60% of the table contains Indian customers, the condition is much less selective.

The database may decide that scanning the table is cheaper than using an index.

Therefore:

ยซAn index isn't automatically useful simply because the column appears in WHERE.ยป

28๏ธโƒฃ Indexes on Low-Cardinality Columns

Suppose:

status

contains only:

โ€ข Active

โ€ข Inactive

That's a low-cardinality column.

An index may not always provide a large benefit if most rows match the condition.

For example:

WHERE status = 'Active'

If 95% of rows are Active, reading the index and then retrieving almost the entire table may be less efficient than scanning the table.

Again, the optimizer makes the decision.

29๏ธโƒฃ Real-World Example

Suppose an orders table contains:

50 million rows

Analysts frequently run:

SELECT
order_id,
order_date,
order_amount
FROM orders
WHERE customer_id = 12345
AND order_date >= DATE '2026-01-01';


A possible candidate is:

CREATE INDEX idx_orders_customer_date
ON orders(customer_id, order_date);
Post #2812 391
SELECT *
FROM customers
WHERE UPPER(customer_name) = 'RAHUL';


If you have a normal index on:

customer_name

the database may not be able to use that index efficiently because the query applies a function to the column.

Depending on the database, an expression/function-based index may help:

CREATE INDEX idx_customer_upper_name
ON customers(UPPER(customer_name));


The exact syntax and availability depend on the database.

1๏ธโƒฃ7๏ธโƒฃ Indexes and NULL

Indexes can have database-specific behavior regarding NULL values.

For example:

SELECT *
FROM customers
WHERE email IS NULL;


Whether and how an index can help depends on the database's index implementation.

Don't assume every database handles NULL indexing identically.

1๏ธโƒฃ8๏ธโƒฃ Why Not Create an Index on Every Column?

This is a common beginner mistake.

You might think:

More indexes

Faster database

But that's not true.

Indexes have costs.

When data changes:

โ€ข INSERT

โ€ข UPDATE

โ€ข DELETE

the database may also need to maintain the relevant indexes.

Therefore:

More indexes

โ†“

More storage

โ†“

More maintenance

โ†“

Potentially slower writes

Indexes should be created based on actual query patterns and workload requirements.

1๏ธโƒฃ9๏ธโƒฃ Indexes Have a Storage Cost

Suppose your table contains:

100 million rows

and you create several large indexes.

The indexes themselves can consume significant storage.

So database design involves a trade-off:

Read performance

โ†•

Write performance

โ†•

Storage

A good indexing strategy balances all three.

20๏ธโƒฃ Query Performance

Indexes are only one part of SQL performance.

Other factors include:

โ€ข Query structure

โ€ข JOIN strategy

โ€ข Filtering

โ€ข Data volume

โ€ข Table design

โ€ข Statistics

โ€ข Partitioning

โ€ข Database engine

โ€ข Execution plan

โ€ข Network transfer

โ€ข Aggregations

โ€ข Sorting

โ€ข Data types

A slow query isn't automatically an "index problem."

21๏ธโƒฃ SELECT * and Performance

Consider:

SELECT *
FROM orders
WHERE customer_id = 101;


If you only need:

โ€ข order_id

โ€ข order_date

โ€ข order_amount

prefer:

SELECT
order_id,
order_date,
order_amount
FROM orders
WHERE customer_id = 101;


Why?

Because retrieving unnecessary columns can:

โ€ข Increase data transfer

โ€ข Increase memory usage

โ€ข Increase I/O

โ€ข Make downstream processing heavier

It also makes your SQL less explicit.

22๏ธโƒฃ Filter Early

Suppose you need sales for 2026:

SELECT
customer_id,
SUM(order_amount) AS total_sales
FROM orders
WHERE order_date >= DATE '2026-01-01'
GROUP BY customer_id;


Filtering before aggregation can significantly reduce the amount of data that needs to be processed.

Conceptually:

10 million rows

โ†“

Filter

โ†“

2 million rows

โ†“

Aggregate

instead of:

10 million rows

โ†“

Aggregate everything

โ†“

Filter later

The optimizer may transform queries internally, but writing clear predicates is still important.

23๏ธโƒฃ Avoid Unnecessary Data Processing

Suppose you need only completed transactions:

SELECT
transaction_id,
amount
FROM transactions
WHERE status = 'Completed';
Older posts โ†’

About this channel

How can I read @sqlanalyst without a Telegram account?
TGViewer shows the public web preview Telegram publishes for SQL Programming Resources: recent posts, photos, videos and the subscriber count, with no app, login or account.
How many subscribers does SQL Programming Resources have?
SQL Programming Resources (@sqlanalyst) has 76.7K subscribers on Telegram, refreshed roughly every 30 minutes.
Does SQL Programming Resources know I viewed it here?
No. Public channel previews carry no viewer identity, and TGViewer has no accounts or tracking of what you look up.
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’