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
601
Videos
1
Links
571

Showing posts older than #2711 ยท Back to latest

Older Posts 20 shown
Post #2710 1.69K
๐Ÿš€ SQL Roadmap 2026 โ€” Part 4

Sorting, Limiting & Selecting the Right Records

In the previous part, you learned how to filter data using WHERE.

Now we'll learn how to control which records appear first, last, or how many records are returned.

These concepts are simple, but they are extremely important for SQL interviews and real-world analytics.

1๏ธโƒฃ ORDER BY

ORDER BY is used to sort query results.

Syntax

SELECT column1, column2
FROM table_name
ORDER BY column_name;


By default, SQL sorts in ascending order (ASC).

Example:

SELECT
employee_name,
salary
FROM employees
ORDER BY salary;


This displays employees from the lowest salary to the highest.

2๏ธโƒฃ ASC โ€” Ascending Order

You can explicitly specify ASC.

SELECT
employee_name,
salary
FROM employees
ORDER BY salary ASC;


For numbers:

100, 250, 500, 1000

For text:

Amit, Neha, Priya, Rahul

3๏ธโƒฃ DESC โ€” Descending Order

Use DESC when you want the highest values first.

SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC;


Result:

Amit: 1200000, Priya: 950000, Rahul: 850000, Neha: 650000

This is one of the most commonly used SQL patterns.

4๏ธโƒฃ Real-World Example: Top Salaries

Business requirement:



Find the highest-paid employees.



SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC;


But this might return thousands of employees.

That's where LIMIT becomes useful.

5๏ธโƒฃ LIMIT

LIMIT restricts the number of rows returned.

SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC
LIMIT 5;


This returns only the top 5 employees by salary.

Think of it as:

ORDER BY DESC โ†’ Highest first โ†’ LIMIT 5 โ†’ Keep first 5

6๏ธโƒฃ Top 10 Products by Price

SELECT
product_name,
price
FROM products
ORDER BY price DESC
LIMIT 10;


Very common in analytics.

7๏ธโƒฃ LIMIT Without ORDER BY

You technically can write:

SELECT *
FROM customers
LIMIT 10;


But this means:



Give me 10 rows.



It does not mean:



Give me the first 10 rows according to some meaningful business order.



Without ORDER BY, the returned order should generally not be relied upon.

If you want the top 10 customers by revenue:

SELECT
customer_id,
revenue
FROM customer_revenue
ORDER BY revenue DESC
LIMIT 10;


8๏ธโƒฃ OFFSET

OFFSET allows you to skip a number of rows.

Example:

SELECT
employee_name,
salary
FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 5;


This skips the first 5 rows and returns the next 5.

Conceptually:

Rows 1โ€“5 โ†’ Skip, Rows 6โ€“10 โ†’ Return

9๏ธโƒฃ Pagination

LIMIT and OFFSET are often used for pagination.

For example:

Page 1

SELECT *
FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 0;


Page 2

SELECT *
FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 10;


Page 3

SELECT *
FROM customers
ORDER BY customer_id
LIMIT 10 OFFSET 20;


The general pattern is:

Page 1 โ†’ OFFSET 0, Page 2 โ†’ OFFSET 10, Page 3 โ†’ OFFSET 20

๐Ÿ”Ÿ Sorting by Multiple Columns

You can sort using more than one column.

Example:

SELECT
employee_name,
department,
salary
FROM employees
ORDER BY department ASC, salary DESC;
  • โค 4
Post #2709 2.6K
๐Ÿง  Common Beginner Mistakes

โŒ Mistake 1: Forgetting FROM

Wrong: SELECT customer_name;

Correct: SELECT customer_name FROM customers;

โŒ Mistake 2: Using commas incorrectly

Wrong: SELECT customer_id customer_name city

Correct: Use commas

โŒ Mistake 3: Using quotes around column names unnecessarily

SELECT 'customer_name' treats it as text, not column.

โŒ Mistake 4: Confusing *

SELECT * means return all columns, not all rows.

๐ŸŽฏ Practice Questions

Q1. Display all columns from employees

Q2. Display employee_name, salary, department_id

Q3. Display unique cities from customers

Q4. Display product_name, price and 15% discounted price

Q5. Display product_name, selling_price, cost_price and profit

Q6. Display customer names with alias Customer

Q7. Display employee name and salary increased by 10%

โœ… Answers

-- A1
SELECT * FROM employees;

-- A2
SELECT employee_name, salary, department_id FROM employees;

-- A3
SELECT DISTINCT city FROM customers;

-- A4
SELECT product_name, price, price * 0.85 AS discounted_price FROM products;

-- A5
SELECT product_name, selling_price, cost_price, selling_price - cost_price AS profit FROM products;

-- A6
SELECT customer_name AS Customer FROM customers;

-- A7
SELECT employee_name, salary, salary * 1.10 AS increased_salary FROM employees;


๐Ÿ’ผ Interview Questions

1. What does SELECT do? โ†’ Retrieves data from columns.

2. What does SELECT * mean? โ†’ Retrieves all columns.

3. What is DISTINCT? โ†’ Removes duplicate combinations.

4. What is an alias? โ†’ Temporary name for clarity.

5. Can SQL perform calculations? โ†’ Yes, arithmetic expressions directly in queries.

Double Tap โค๏ธ For Part-3
  • โค 12
Post #2708 2.12K
๐Ÿš€ SQL Roadmap 2026 โ€” Part 2

SQL SELECT Statement & Retrieving Data

Now that you understand databases, tables, rows, columns, primary keys, and foreign keys, it's time to learn the most fundamental SQL command: SELECT.

Almost every SQL analysis starts with retrieving data.

1๏ธโƒฃ What is SELECT?

SELECT is used to retrieve data from one or more columns in a table.

Basic syntax:

SELECT column_name
FROM table_name;


Example:

SELECT customer_name
FROM customers;


2๏ธโƒฃ Select Multiple Columns

You can retrieve multiple columns by separating them with commas.

SELECT
customer_id,
customer_name,
city
FROM customers;


Result:

customer_id | customer_name | city

1 | Rahul | Mumbai

2 | Priya | Delhi

3 | Amit | Pune

3๏ธโƒฃ Select All Columns Using *

If you want every column:

SELECT *
FROM customers;


* means all columns.

โš ๏ธ Interview Tip: Although SELECT * is convenient while exploring data, avoid relying on it in production queries. Prefer selecting only needed columns.

4๏ธโƒฃ Column Aliases

Use AS to give a column a different name in the result.

SELECT
customer_name AS name,
city AS location
FROM customers;


The original table is not changed.

5๏ธโƒฃ Aliases Without AS

SELECT
customer_name name,
city location
FROM customers;


However, using AS is generally clearer for beginners.

6๏ธโƒฃ Calculations Inside SELECT

SELECT
product_name,
price,
price * 0.90 AS discounted_price
FROM products;


7๏ธโƒฃ Arithmetic Operators

+ Addition, - Subtraction, * Multiplication, / Division

SELECT
product_name,
selling_price,
cost_price,
selling_price - cost_price AS profit
FROM products;


8๏ธโƒฃ Using Expressions

SELECT
product_name,
quantity,
unit_price,
quantity * unit_price AS total_value
FROM order_items;


9๏ธโƒฃ DISTINCT

Removes duplicate values.

SELECT DISTINCT city
FROM customers;


๐Ÿ”Ÿ DISTINCT Across Multiple Columns

SELECT DISTINCT
city,
customer_segment
FROM customers;


1๏ธโƒฃ1๏ธโƒฃ Using SELECT With Text

SELECT
customer_name,
'Active Customer' AS status
FROM customers;


1๏ธโƒฃ2๏ธโƒฃ Combining Columns

SELECT
first_name,
last_name,
CONCAT(first_name, ' ', last_name) AS full_name
FROM employees;


1๏ธโƒฃ3๏ธโƒฃ SELECT With a Condition

SELECT
customer_name,
city
FROM customers
WHERE city = 'Mumbai';


1๏ธโƒฃ5๏ธโƒฃ SQL Query Structure

At this stage, learn this basic pattern:

SELECT column1, column2
FROM table_name;

SELECT column1, column2
FROM table_name
WHERE condition;


1๏ธโƒฃ6๏ธโƒฃ A Real-World Example

Manager asks: "Show me product name, selling price, cost price, and profit"

SELECT
product_name,
selling_price,
cost_price,
selling_price - cost_price AS profit
FROM products;
  • โค 7
Post #2704 2.24K
A database can contain hundreds or thousands of tables.

6๏ธโƒฃ What is a Row?

A row represents one record. 1 | Rahul | IT | 80000 = 1 row = 1 record.

7๏ธโƒฃ What is a Column?

A column represents an attribute or field.

Row โ†’ Record

Column โ†’ Attribute.

8๏ธโƒฃ What is a Primary Key?

A Primary Key uniquely identifies each row in a table. e.g., employee_id = 101 cannot repeat.

Properties:

โœ… Must be unique

โœ… Cannot normally be NULL

โœ… Identifies a specific record

9๏ธโƒฃ What is a Foreign Key?

A Foreign Key creates a relationship between tables. orders.customer_id is a Foreign Key referring to customers.customer_id.

๐Ÿ”Ÿ Primary Key vs Foreign Key

PRIMARY KEY โ†’ Uniquely identifies a record

FOREIGN KEY โ†’ Connects one table to another

1๏ธโƒฃ1๏ธโƒฃ What is NULL?

NULL means the value is missing, unknown, or not available. It does NOT mean 0, empty string, or "NULL" text.

Correct query: SELECT * FROM employees WHERE manager_id IS NULL;

Wrong: WHERE manager_id = NULL;

1๏ธโƒฃ2๏ธโƒฃ What are Data Types?

INT โ†’ 101

DECIMAL(10,2) โ†’ 85000.50

VARCHAR(100) โ†’ 'Rahul Sharma'

DATE โ†’ 2026-08-25

TIMESTAMP โ†’ 2026-08-25 10:30:00

1๏ธโƒฃ3๏ธโƒฃ One Database Can Have Multiple Tables

DATABASE โ†’ Customers, Products, Employees โ†’ Orders โ†’ Payments

The power of SQL comes from being able to analyze these related tables together.

1๏ธโƒฃ4๏ธโƒฃ Example: E-Commerce Database

customers, products, orders, order_items โ€” Now business can ask: Which city generated highest revenue? Who are top 10 customers? Which products sell the most?

๐Ÿง  Your First SQL Query

SELECT * FROM customers;

SELECT โ†’ Retrieve data, * โ†’ All columns, FROM โ†’ From this table

SELECT customer_id, customer_name, city FROM customers;

๐Ÿ’ก Q: What is difference between a Primary Key and a Foreign Key?

A: A Primary Key uniquely identifies each record within its own table, while a Foreign Key is used to reference a key in another table and establish a relationship between tables.

If you understand how data is structured and how tables relate to each other, learning JOIN, GROUP BY, CTE, and Window Functions becomes much easier.

Double Tap โค๏ธ For Part-2
  • โค 14
Post #2703 2.32K
๐Ÿš€ SQL Roadmap 2026 โ€” Part 1

โœ… Database Basics You Should Know

Thanks for the amazing response to the SQL roadmap! ๐Ÿ”ฅ

Let's start from the absolute foundation. Before learning SELECT, JOIN, or window functions, you need to understand what a database actually is and how data is organized inside it.

1๏ธโƒฃ What is a Database?

A database is an organized collection of data that allows us to store, manage, search, and analyze information efficiently.

For example, an e-commerce company may need to store: Customers, Orders, Products, Payments, Employees, Reviews.

Instead of keeping everything in separate Excel files, the company can store this information in a database. Think of a database as a structured digital storage system for data.

2๏ธโƒฃ What is DBMS?

DBMS = Database Management System

A DBMS is software used to create, store, manage, retrieve, and manipulate data in databases.

Examples: MySQL, PostgreSQL, Microsoft SQL Server, Oracle Database, SQLite

For example:

You โ†’ SQL Query โ†’ DBMS โ†’ Database โ†’ Result

When you write:

SELECT * FROM customers;

the DBMS processes your SQL query and returns the requested data.

3๏ธโƒฃ SQL vs DBMS

SQL โ€” SQL is a language used to communicate with a relational database.

Example: SELECT customer_name FROM customers;

DBMS โ€” DBMS is the software that manages the database.

Examples: MySQL, PostgreSQL, SQL Server, Oracle



SQL = Language, DBMS = Software that understands and executes that language



4๏ธโƒฃ What is a Relational Database?

A relational database stores data in tables and establishes relationships between those tables.

Customers

customer_id | customer_name | city
1 | Rahul | Mumbai
2 | Priya | Delhi
3 | Amit | Pune


Orders

order_id | customer_id | amount
101 | 1 | 2500
102 | 2 | 1800
103 | 1 | 4200


Customers.customer_id โ†’ Orders.customer_id

This relationship allows us to answer: How much has each customer spent?

5๏ธโƒฃ What is a Table?

A table is where data is actually organized and stored. Think of it like an Excel sheet.

employees

employee_id | name  | department | salary
1 | Rahul | IT | 80000
2 | Priya | Finance | 75000
3 | Amit | IT | 90000
  • โค 5
  • ๐Ÿ‘ 1
Post #2699 2.64K
โ€ข Customers, Subscriptions, Usage, Billing, Support tickets

โ€ข KPIs: Churn Rate, Retention Rate, ARPU, CLV, MRR

Project 3 โ€” Banking Analytics

โ€ข Customers, Accounts, Transactions, Loans, Branches

โ€ข KPIs: Deposits, Withdrawals, Transaction Volume, Average Balance, Loan Exposure

Project 4 โ€” Marketing Analytics

โ€ข Campaigns, Leads, Customers, Conversions, Revenue

โ€ข KPIs: Conversion Rate, CAC, CPL, CPA, ROI, Revenue per Channel

๐Ÿ”ด Month 6 โ€” Interview & Job Preparation

Week 21: SQL Interview Fundamentals

โ€ข SELECT, WHERE, GROUP BY, HAVING, CASE, Joins, Subqueries

โ€ข Target: 50+ questions

Week 22: Advanced Interview Questions

โ€ข Window functions, CTEs, Ranking, LAG / LEAD, Running totals, Date calculations, Cohort analysis

โ€ข Target: 50+ questions

Week 23: Real-World Scenarios

โ€ข Customers who purchased in consecutive months

โ€ข Second-highest salary in each department

โ€ข Monthly retention

โ€ข Top 3 products by revenue for every month

โ€ข Customers whose spending increased month over month

๐Ÿ† Week 24 โ€” Final SQL Challenge

โ€ข Raw Data โ†’ Database Design โ†’ Data Cleaning โ†’ SQL Analysis โ†’ Business KPIs โ†’ Insights โ†’ Dashboard โ†’ Business Recommendations

๐Ÿ“š SQL Topics Checklist

Beginner:

โ€ข SELECT, DISTINCT, WHERE, ORDER BY, LIMIT, AND / OR, IN, BETWEEN, LIKE, NULL

Intermediate:

โ€ข GROUP BY, HAVING, CASE, Aggregate functions, String functions, Date functions, Joins, Subqueries, CTEs

Advanced:

โ€ข Window functions, ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, Running totals, Moving averages, Cohort analysis, Retention analysis, Funnel analysis, Gaps & islands, Recursive CTEs

Data Analyst SQL:

โ€ข Revenue analysis, Customer analytics, Product analytics, Marketing analytics, Churn analysis, Cohort analysis, RFM analysis, KPI calculations, Business scenario analysis

โฑ๏ธ Double Tap โค๏ธ For Detailed Explanation of each topic
  • โค 17
  • ๐Ÿ‘ 1
Post #2698 1.95K
๐Ÿš€ Complete SQL Roadmap to Learn SQL in 2026

๐Ÿ—บ๏ธ 6-Month SQL Roadmap

๐ŸŸข Month 1 โ€” SQL Fundamentals

Start by understanding how relational databases work.

Week 1: Database Basics

โ€ข What is SQL?

โ€ข SQL vs MySQL vs PostgreSQL vs SQL Server

โ€ข Database, table, row and column

โ€ข Primary keys

โ€ข Foreign keys

โ€ข Relationships

โ€ข NULL values

โ€ข Data types

โ€ข Relational databases

โ€ข Basic database design

Week 2: Basic Queries

Master:

โ€ข SELECT

โ€ข DISTINCT

โ€ข WHERE

โ€ข AND / OR

โ€ข NOT

โ€ข IN

โ€ข BETWEEN

โ€ข LIKE

โ€ข IS NULL / IS NOT NULL

โ€ข ORDER BY

โ€ข LIMIT

Week 3: SQL Functions

โ€ข COUNT(), SUM(), AVG(), MIN(), MAX()

โ€ข String functions: CONCAT(), UPPER(), LOWER(), LENGTH(), SUBSTRING()

โ€ข Date functions: CURRENT_DATE, DATE_PART / EXTRACT, DATE_TRUNC, DATE_DIFF equivalents

Week 4: GROUP BY & HAVING

โ€ข GROUP BY

โ€ข HAVING

โ€ข Revenue by category

โ€ข Employees by department

โ€ข Average salary by department

๐ŸŸก Month 2 โ€” Intermediate SQL

Week 5: CASE Statements

โ€ข CASE WHEN THEN ELSE END

โ€ข Customer segmentation

โ€ข Salary bands

โ€ข Order status classification

โ€ข Profit categories

โ€ข Age groups

Week 6: Joins

Master:

โ€ข INNER JOIN

โ€ข LEFT JOIN

โ€ข RIGHT JOIN

โ€ข FULL OUTER JOIN

โ€ข CROSS JOIN

โ€ข Self JOIN

Week 7: Subqueries

โ€ข Scalar subqueries

โ€ข Multi-row subqueries

โ€ข Correlated subqueries

โ€ข EXISTS / NOT EXISTS

โ€ข IN / NOT IN

Week 8: CTEs

โ€ข WITH cte AS (...) SELECT ... FROM cte

โ€ข Multi-step revenue analysis

โ€ข Customer segmentation

โ€ข Funnel analysis

โ€ข Cohort analysis

๐ŸŸ  Month 3 โ€” Advanced SQL

Week 9: Window Functions

โ€ข ROW_NUMBER(), RANK(), DENSE_RANK()

โ€ข LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE()

Week 10: Advanced Aggregations

โ€ข Conditional aggregation

โ€ข Multiple aggregations

โ€ข DISTINCT aggregation

โ€ข Aggregation with CASE

โ€ข GROUP BY with multiple dimensions

Week 11: Date & Time Analytics

โ€ข Daily / Weekly / Monthly / Quarterly / Yearly metrics

โ€ข Month-over-month growth

โ€ข Year-over-year growth

โ€ข Date differences

โ€ข Customer tenure

โ€ข Time between events

Week 12: Advanced SQL Patterns

โ€ข Top N per group

โ€ข Gaps and islands

โ€ข Running totals

โ€ข Moving averages

โ€ข Consecutive records

โ€ข Duplicate detection

โ€ข Missing records

โ€ข First/last record

โ€ข Latest record per customer

๐Ÿ”ต Month 4 โ€” SQL for Data Analytics

Week 13: Sales Analytics

โ€ข Revenue, Orders, AOV, Product / Category performance, Customer revenue, Monthly growth, Profit margin

โ€ข KPIs: Revenue, Orders, AOV, Gross Profit, Profit Margin, Units Sold, Repeat Purchase Rate

Week 14: Customer Analytics

โ€ข New / Existing / Repeat customers

โ€ข Customer retention / churn

โ€ข Customer lifetime value

โ€ข RFM analysis

Week 15: Marketing Analytics

โ€ข Leads, Campaigns, Conversions, Marketing channels

โ€ข CAC, CPL, CPA, Conversion rate, Campaign ROI

โ€ข Funnel: Impressions โ†’ Clicks โ†’ Leads โ†’ Signups โ†’ Purchases

Week 16: Product Analytics

โ€ข DAU, WAU, MAU

โ€ข Retention, Churn

โ€ข Feature adoption, Activation

โ€ข Conversion funnel, Cohort analysis

๐ŸŸฃ Month 5 โ€” Real-World SQL Projects

Build at least 4 complete projects.

Project 1 โ€” E-Commerce Analytics

โ€ข Customers, Orders, Products, Revenue, Profit, Discounts

โ€ข KPIs: Revenue, AOV, Profit, Margin, Repeat Purchase Rate, CLV

Project 2 โ€” Customer Churn
  • โค 4
Post #2696 2.19K
10 Advanced SQL Concepts For Data Analysts

1. Window Functions for Advanced Analytics:
Calculate running totals, ranks, and moving averages without subqueries.

SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS running_total FROM sales_data;


2. Conditional Aggregation with CASE WHEN:
Segment data within a single query, saving time and creating versatile summaries.

SELECT COUNT(CASE WHEN status = 'Completed' THEN 1 END) AS completed_orders FROM orders;


3. CTEs for Modular Queries:
Make complex queries more readable and reusable with CTEs.

WITH filtered_sales AS (SELECT * FROM sales_data WHERE region = 'North')
SELECT product, SUM(sales) FROM filtered_sales GROUP BY product;


4. Optimize with EXISTS vs. IN:
Use EXISTS for better performance in larger datasets.

SELECT * FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);


5. Self Joins for Row Comparisons:
Compare rows within the same table, helpful for changes over time.

SELECT a.date, (a.sales - b.sales) AS sales_diff FROM sales_data a JOIN sales_data b ON a.date = b.date + INTERVAL '1' MONTH;


6. UNION vs. UNION ALL:
Combine results from multiple queries; UNION ALL is faster as it doesnโ€™t remove duplicates.

7. Handle NULLs with COALESCE:
Replace NULLs with defaults to avoid calculation issues.

SELECT product, COALESCE(sales, 0) AS sales FROM product_sales;


8. Pivot Data with CASE Statements:
Transform rows into columns for clearer insights.

9. Extract Data with STRING Functions:
Useful for semi-structured data; extract domains, product codes, etc.

SELECT SUBSTRING(email, CHARINDEX('@', email) + 1, LEN(email)) AS domain FROM users;


10. Indexing for Faster Queries:
Indexes speed up data retrieval, especially on frequently queried columns.

Mastering these SQL tricks will optimize your queries, simplify logic, and enable complex analyses.

Hope it helps :)
  • โค 4
Post #2694 2.14K
The Learning Trap: What Most Beginners Fall Into

When starting out, it's common to feel like you need to master every possible SQL concept. You binge YouTube videos, tutorials, and courses, yet still feel lost in interviews or when given a real dataset.

Common traps:

- Complex subqueries

- Advanced CTEs

- Recursive queries

- 100+ tutorials watched

- 0 practical experience


Reality Check: What You'll Actually Use 75% of the Time

Most data analytics roles (especially entry-level) require clarity, speed, and confidence with core SQL operations. Hereโ€™s what covers most daily work:

1. SELECT, FROM, WHERE โ€” The Foundation

SELECT name, age
FROM employees
WHERE department = 'Finance';

This is how almost every query begins. Whether exploring a dataset or building a dashboard, these are always in use.

2. JOINs โ€” Combining Data From Multiple Tables

SELECT e.name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;

Youโ€™ll often join tables like employee data with department, customer orders with payments, etc.

3. GROUP BY โ€” Summarizing Data

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

Used to get summaries by categories like sales per region or users by plan.

4. ORDER BY โ€” Sorting Results

SELECT name, salary
FROM employees
ORDER BY salary DESC;

Helps sort output for dashboards or reports.

5. Aggregations โ€” Simple But Powerful

Common functions: COUNT(), SUM(), AVG(), MIN(), MAX()

SELECT AVG(salary)
FROM employees
WHERE department = 'IT';

Gives quick insights like average deal size or total revenue.

6. ROW_NUMBER() โ€” Adding Row Logic

SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY order_date DESC) as rn
FROM orders
) sub
WHERE rn = 1;

Used for deduplication, rankings, or selecting the latest record per group.

Credits: https://whatsapp.com/channel/0029VaGgzAk72WTmQFERKh02

React โค๏ธ for more
  • โค 7
Post #2691 2.09K
WITH sales_summary AS (
SELECT customer_id,
SUM(amount) AS total_sales
FROM sales
GROUP BY customer_id
)
SELECT *
FROM sales_summary
WHERE total_sales > 10000;


This makes your SQL easier to read and debug.

๐Ÿ“Œ 16. Don't Memorize Interview Queries

Instead of memorizing:



"Query to find the second-highest salary"



Understand the underlying concept:



Ranking โ†’ Ordering โ†’ Selecting the required rank.



This allows you to solve variations of the same problem.

๐Ÿ“Œ 17. Practice Real Business Scenarios

Don't practice only basic employee tables.

Try problems involving:

Sales

Customers

Orders

Transactions

Revenue

Products

Employee retention

Customer churn

Fraud detection

This will make your SQL much more practical.

๐Ÿ“Œ 18. Always Validate Your Output

After writing a query, ask yourself:

Is the row count correct?

Are duplicates present?

Are NULLs handled?

Are totals correct?

Did the JOIN produce the expected records?

Does the result actually answer the business question?

Writing a query is only half the job. Validating the result is equally important.

๐Ÿ“Œ 19. Understand SQL Execution Order

A simplified logical execution order is:

FROM
โ†“
WHERE
โ†“
GROUP BY
โ†“
HAVING
โ†“
SELECT
โ†“
ORDER BY
โ†“
LIMIT

Understanding this will help you solve many tricky SQL interview questions.

๐Ÿ“Œ 20. Practice Consistently

You don't need to solve 100 questions in one day.

Solve 5โ€“10 SQL problems every day and gradually move from:

Basic Queries
      โ†“
Filtering
      โ†“
Aggregations
      โ†“
JOINs
      โ†“
CASE WHEN
      โ†“
Subqueries
      โ†“
CTEs
      โ†“
Window Functions
      โ†“
Advanced SQL

๐Ÿ”ฅ Double Tap โค๏ธ For More
  • โค 7
Post #2690 1.8K
๐Ÿ—„๏ธ SQL Important Tips for Beginners โ€” Part 2

If you're learning SQL for Data Analytics, don't just memorize syntax. Focus on understanding how to write correct queries and how SQL processes your data.

๐Ÿ“Œ 1. Always Understand the Question First

Before writing SQL, identify:

โ€ข What information is required?

โ€ข Which table contains the data?

โ€ข Which columns are needed?

โ€ข Do you need filtering?

โ€ข Do you need grouping?

โ€ข Do you need a JOIN?

Understanding the problem first makes writing the query much easier.

๐Ÿ“Œ 2. Use WHERE to Filter Rows

WHERE is used to filter individual records.

SELECT *
FROM employees
WHERE department = 'IT';


Think:

WHERE โ†’ Which rows do I need?

๐Ÿ“Œ 3. Remember WHERE vs HAVING

This is one of the most common SQL interview questions.

WHERE โ†’ Filters rows before grouping

HAVING โ†’ Filters groups after aggregation

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;


๐Ÿ“Œ 4. Be Very Careful with JOINs

JOINs are extremely important for Data Analysts.

Before joining tables, understand:

โ€ข Primary key

โ€ข Foreign key

โ€ข One-to-one relationship

โ€ข One-to-many relationship

โ€ข Many-to-many relationship

A wrong JOIN can produce incorrect results and duplicate records.

๐Ÿ“Œ 5. Understand INNER JOIN vs LEFT JOIN

Remember the basic idea:

INNER JOIN โ†’ Returns matching records from both tables.

LEFT JOIN โ†’ Returns all records from the left table and matching records from the right table.

This simple concept will help you solve many interview questions.

๐Ÿ“Œ 6. Always Check for Duplicate Rows After a JOIN

If you expected 1,000 rows but your JOIN produces 10,000 rows, don't immediately use DISTINCT.

First investigate whether the JOIN relationship is causing multiple matches.

๐Ÿ“Œ 7. Master GROUP BY

GROUP BY is essential for data analysis.

SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;


Think:

GROUP BY โ†’ How do I want to summarize my data?

๐Ÿ“Œ 8. Learn Aggregate Functions Properly

Master these functions:

โ€ข COUNT()

โ€ข SUM()

โ€ข AVG()

โ€ข MIN()

โ€ข MAX()

Practice them with GROUP BY and HAVING.

๐Ÿ“Œ 9. Don't Forget NULL

NULL means missing or unknown value.

Incorrect:

WHERE salary = NULL

Correct:

WHERE salary IS NULL

Also learn:

โ€ข COALESCE()

โ€ข NULLIF()

๐Ÿ“Œ 10. Learn CASE WHEN

CASE WHEN is extremely useful for creating business categories.

CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Low'
END


You'll use it frequently in real-world analytics.

๐Ÿ“Œ 11. Don't Overuse DISTINCT

DISTINCT removes duplicate results.

But if you're using DISTINCT because your JOIN unexpectedly created duplicates, investigate the JOIN instead.

๐Ÿ“Œ 12. Learn Date Functions

Data Analyst interviews frequently involve dates.

Practice questions involving:

โ€ข Year

โ€ข Month

โ€ข Quarter

โ€ข Date difference

โ€ข Month-over-month growth

โ€ข Year-over-year growth

โ€ข Rolling periods

Date-based SQL problems are extremely common in analytics.

๐Ÿ“Œ 13. Start Learning Window Functions

Once you're comfortable with basic SQL, learn:

โ€ข ROW_NUMBER()

โ€ข RANK()

โ€ข DENSE_RANK()

โ€ข LAG()

โ€ข LEAD()

โ€ข SUM() OVER()

โ€ข AVG() OVER()

These are extremely important for Data Analyst interviews.

๐Ÿ“Œ 14. Understand RANK vs DENSE_RANK

For example, if salaries are:

100000

100000

90000

80000

RANK() gives:

1

1

3

4

DENSE_RANK() gives:

1

1

2

3

This difference is frequently tested in interviews.

๐Ÿ“Œ 15. Use CTEs for Complex Queries

Instead of writing one huge query, break the logic into smaller steps using a CTE.
  • โค 5
Post #2688 2.02K
12. Master Window Functions

Once your basics are strong, learn:

โ€ข ROW_NUMBER()

โ€ข RANK()

โ€ข DENSE_RANK()

โ€ข LAG()

โ€ข LEAD()

โ€ข SUM() OVER()

โ€ข AVG() OVER()

These are especially important for Data Analyst interviews.

13. Don't just memorize queries

Instead of memorizing: "This is the query to find the second-highest salary."

Understand the problem: "I need to rank salaries and identify the second position."

Then decide whether DENSE_RANK(), ROW_NUMBER(), a subquery, or another approach is appropriate.

14. Practice with business problems

Don't practice only: Find employees, Find salaries, Find departments

Practice realistic problems:

โ€ข Find customers who haven't purchased in 90 days

โ€ข Find the top 3 products in each category

โ€ข Calculate month-over-month sales growth

โ€ข Find duplicate transactions

โ€ข Identify customers whose spending increased

โ€ข Calculate employee retention

โ€ข Find the second-highest salary in each department

15. Learn to read execution plans later

Once you're comfortable with SQL, start learning:

โ€ข Indexes

โ€ข Query execution plans

โ€ข Table scans

โ€ข Index scans

โ€ข Query optimization

You don't need this on day one, but it's important as you progress.

๐Ÿ”ฅ Most important tip: Don't just watch SQL tutorials. Write SQL every day. Even 5โ€“10 problems daily will build your confidence much faster than passive learning.

Double Tap โค๏ธ For More
  • โค 8
Post #2687 1.69K
๐Ÿ—„๏ธ SQL Important Tips for Beginners

If you're starting SQL for Data Analytics, don't try to memorize hundreds of queries. Focus on understanding how SQL thinks and practice consistently.

1. Master the basic SQL order

Learn these clauses first:

โ€ข SELECT

โ€ข FROM

โ€ข WHERE

โ€ข GROUP BY

โ€ข HAVING

โ€ข ORDER BY

โ€ข LIMIT

Understand what each one does before moving to advanced SQL.

2. Understand the logical execution order

SQL doesn't logically execute a query in the same order you write it.

A simplified order is:

โ€ข FROM

โ€ข WHERE

โ€ข GROUP BY

โ€ข HAVING

โ€ข SELECT

โ€ข ORDER BY

โ€ข LIMIT

This helps explain many SQL interview questions.

3. Get comfortable with filtering

Master:

โ€ข WHERE

โ€ข AND / OR / NOT

โ€ข IN

โ€ข BETWEEN

โ€ข LIKE

โ€ข IS NULL / IS NOT NULL

Note: use IS NULL, not = NULL.

4. Learn aggregate functions properly

You should be comfortable with:

โ€ข COUNT()

โ€ข SUM()

โ€ข AVG()

โ€ข MIN()

โ€ข MAX()

Example:

SELECT department, AVG(salary)
FROM employees
GROUP BY department;


5. Understand GROUP BY vs HAVING

โ€ข WHERE โ†’ filters rows before grouping

โ€ข HAVING โ†’ filters groups after aggregation

Example:

SELECT department, COUNT(*) AS employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;


6. Master JOINs

For Data Analyst interviews, JOINs are extremely important. Learn:

โ€ข INNER JOIN

โ€ข LEFT JOIN

โ€ข RIGHT JOIN

โ€ข FULL OUTER JOIN

โ€ข CROSS JOIN

โ€ข SELF JOIN

Most importantly, understand why rows are included or excluded in each JOIN.

7. Always understand your keys

Know the difference between:

โ€ข Primary Key

โ€ข Foreign Key

โ€ข Composite Key

โ€ข Unique Key

Understanding relationships between tables will make JOINs much easier.

8. Don't ignore NULL

NULL does not mean:

โ€ข 0

โ€ข Empty string

โ€ข False

Learn how NULL behaves with: IS NULL, IS NOT NULL, COALESCE(), NULLIF()

9. Learn CASE WHEN early

CASE is one of the most useful SQL features for analytics.

SELECT employee,
salary,
CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;


10. Practice subqueries

Understand queries inside queries:

SELECT *
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);


Then move toward correlated subqueries.

11. Learn CTEs

CTEs make complex SQL easier to read and maintain.

WITH sales_summary AS (
SELECT customer_id, SUM(amount) AS total_sales
FROM sales
GROUP BY customer_id
)
SELECT *
FROM sales_summary
WHERE total_sales > 10000;
  • โค 2
  • ๐Ÿ‘ 1
Post #2685 1.94K
If you are interested to learn SQL for data analytics purpose and clear the interviews, just cover the following topics

1)Install MYSQL workbench
2) Select
3) From
4) where
5) group by
6) having
7) limit
8) Joins (Left, right , inner, self, cross)
9) Aggregate function ( Sum, Max, Min , Avg)
9) windows function ( row num, rank, dense rank, lead, lag, Sum () over)
10)Case
11) Like
12) Sub queries
13) CTE
14) Replace CTE with temp tables
15) Methods to optimize Sql queries
16) Solve problems and case studies at Ankit Bansal youtube channel

Trick: Just copy each term and paste on youtube and watch any 10 to 15 minute on each topic and practise it while learning , By doing this , you get the basics understanding

17) Now time to go on youtube and search data analysis end to end project using sql

18) Watch them and practise them end to end.

17) learn integration with power bi

In this way , you will not only memorize the concepts but also learn how to implement them in your current working and projects and will be able to defend it in your interviews as well.

Like for more
  • โค 8
Post #2682 2K
12. Master Window Functions

Once your basics are strong, learn:

โ€ข ROW_NUMBER()

โ€ข RANK()

โ€ข DENSE_RANK()

โ€ข LAG()

โ€ข LEAD()

โ€ข SUM() OVER()

โ€ข AVG() OVER()

These are especially important for Data Analyst interviews.

13. Don't just memorize queries

Instead of memorizing: "This is the query to find the second-highest salary."

Understand the problem: "I need to rank salaries and identify the second position."

Then decide whether DENSE_RANK(), ROW_NUMBER(), a subquery, or another approach is appropriate.

14. Practice with business problems

Don't practice only: Find employees, Find salaries, Find departments

Practice realistic problems:

โ€ข Find customers who haven't purchased in 90 days

โ€ข Find the top 3 products in each category

โ€ข Calculate month-over-month sales growth

โ€ข Find duplicate transactions

โ€ข Identify customers whose spending increased

โ€ข Calculate employee retention

โ€ข Find the second-highest salary in each department

15. Learn to read execution plans later

Once you're comfortable with SQL, start learning:

โ€ข Indexes

โ€ข Query execution plans

โ€ข Table scans

โ€ข Index scans

โ€ข Query optimization

You don't need this on day one, but it's important as you progress.

๐Ÿ”ฅ Most important tip: Don't just watch SQL tutorials. Write SQL every day. Even 5โ€“10 problems daily will build your confidence much faster than passive learning.

Double Tap โค๏ธ For More
  • โค 3
Post #2681 1.73K
๐Ÿ—„๏ธ SQL Important Tips for Beginners

If you're starting SQL for Data Analytics, don't try to memorize hundreds of queries. Focus on understanding how SQL thinks and practice consistently.

1. Master the basic SQL order

Learn these clauses first:

โ€ข SELECT

โ€ข FROM

โ€ข WHERE

โ€ข GROUP BY

โ€ข HAVING

โ€ข ORDER BY

โ€ข LIMIT

Understand what each one does before moving to advanced SQL.

2. Understand the logical execution order

SQL doesn't logically execute a query in the same order you write it.

A simplified order is:

โ€ข FROM

โ€ข WHERE

โ€ข GROUP BY

โ€ข HAVING

โ€ข SELECT

โ€ข ORDER BY

โ€ข LIMIT

This helps explain many SQL interview questions.

3. Get comfortable with filtering

Master:

โ€ข WHERE

โ€ข AND / OR / NOT

โ€ข IN

โ€ข BETWEEN

โ€ข LIKE

โ€ข IS NULL / IS NOT NULL

Note: use IS NULL, not = NULL.

4. Learn aggregate functions properly

You should be comfortable with:

โ€ข COUNT()

โ€ข SUM()

โ€ข AVG()

โ€ข MIN()

โ€ข MAX()

Example:

SELECT department, AVG(salary)
FROM employees
GROUP BY department;


5. Understand GROUP BY vs HAVING

โ€ข WHERE โ†’ filters rows before grouping

โ€ข HAVING โ†’ filters groups after aggregation

Example:

SELECT department, COUNT(*) AS employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;


6. Master JOINs

For Data Analyst interviews, JOINs are extremely important. Learn:

โ€ข INNER JOIN

โ€ข LEFT JOIN

โ€ข RIGHT JOIN

โ€ข FULL OUTER JOIN

โ€ข CROSS JOIN

โ€ข SELF JOIN

Most importantly, understand why rows are included or excluded in each JOIN.

7. Always understand your keys

Know the difference between:

โ€ข Primary Key

โ€ข Foreign Key

โ€ข Composite Key

โ€ข Unique Key

Understanding relationships between tables will make JOINs much easier.

8. Don't ignore NULL

NULL does not mean:

โ€ข 0

โ€ข Empty string

โ€ข False

Learn how NULL behaves with: IS NULL, IS NOT NULL, COALESCE(), NULLIF()

9. Learn CASE WHEN early

CASE is one of the most useful SQL features for analytics.

SELECT employee,
salary,
CASE
WHEN salary >= 100000 THEN 'High'
WHEN salary >= 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_category
FROM employees;


10. Practice subqueries

Understand queries inside queries:

SELECT *
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);


Then move toward correlated subqueries.

11. Learn CTEs

CTEs make complex SQL easier to read and maintain.

WITH sales_summary AS (
SELECT customer_id, SUM(amount) AS total_sales
FROM sales
GROUP BY customer_id
)
SELECT *
FROM sales_summary
WHERE total_sales > 10000;
  • โค 4
Post #2678 2.48K
Essential SQL Topics for Data Analysts ๐Ÿ‘‡

- Basic Queries: SELECT, FROM, WHERE clauses.
- Sorting and Filtering: ORDER BY, GROUP BY, HAVING.
- Joins: INNER JOIN, LEFT JOIN, RIGHT JOIN.
- Aggregation Functions: COUNT, SUM, AVG, MIN, MAX.
- Subqueries: Embedding queries within queries.
- Data Modification: INSERT, UPDATE, DELETE.
- Indexes: Optimizing query performance.
- Normalization: Ensuring efficient database design.
- Views: Creating virtual tables for simplified queries.
- Understanding Database Relationships: One-to-One, One-to-Many, Many-to-Many.

Window functions are also important for data analysts. They allow for advanced data analysis and manipulation within specified subsets of data. Commonly used window functions include:

- ROW_NUMBER(): Assigns a unique number to each row based on a specified order.
- RANK() and DENSE_RANK(): Rank data based on a specified order, handling ties differently.
- LAG() and LEAD(): Access data from preceding or following rows within a partition.
- SUM(), AVG(), MIN(), MAX(): Aggregations over a defined window of rows.

Here is an amazing resources to learn & practice SQL: https://bit.ly/3FxxKPz

Share with credits: https://t.me/sqlspecialist

Hope it helps :)
  • โค 4
Post #2676 2.21K
๐Ÿ’ป ๐— ๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ ๐—ฆ๐—ค๐—Ÿ ๐—ณ๐—ผ๐—ฟ ๐—™๐—ฅ๐—˜๐—˜ | ๐Ÿฑ ๐—•๐—ฒ๐˜€๐˜ ๐—ฌ๐—ผ๐˜‚๐—ง๐˜‚๐—ฏ๐—ฒ ๐—–๐—ต๐—ฎ๐—ป๐—ป๐—ฒ๐—น๐˜€ ๐Ÿš€

Want to learn SQL from scratch to advanced level without spending anything? These 5 YouTube channels offer tutorials, practical examples and problem-solving content.

๐Ÿ”ฅ Learn โ†’ Practice โ†’ Build Projects โ†’ Prepare for SQL Interviews

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

https://pdlink.in/4wCjU6x

๐Ÿ“Š Perfect for Students | Freshers | Data Analyst Aspirants | SQL Beginners
  • ๐Ÿ‘ 1
Post #2675 2.44K
๐Ÿ“ˆ Total Customers 
๐Ÿ“ˆ Active Customers 
๐Ÿ“ˆ Active Accounts 
๐Ÿ“ˆ Total Deposits 
๐Ÿ“ˆ Total Withdrawals 
๐Ÿ“ˆ Net Transaction Value 
๐Ÿ“ˆ Average Transaction Value 
๐Ÿ“ˆ Transaction Volume 
๐Ÿ“ˆ Customer Average Balance 
๐Ÿ“ˆ Total Deposits by Branch 
๐Ÿ“ˆ Branch-wise Transaction Volume 
๐Ÿ“ˆ Customer Segment Analysis 
๐Ÿ“ˆ Premium Customer Contribution 
๐Ÿ“ˆ High-Value Customers 
๐Ÿ“ˆ Monthly Transaction Growth 
๐Ÿ“ˆ Account Growth 
๐Ÿ“ˆ Loan Portfolio Value 
๐Ÿ“ˆ Average Loan Amount 
๐Ÿ“ˆ Loan Distribution by Type 
๐Ÿ“ˆ Active vs Closed Loans 
๐Ÿ“ˆ Customer Loan Exposure 
๐Ÿ“ˆ Deposit-to-Withdrawal Ratio 
๐Ÿ“ˆ Transaction Success Rate 
๐Ÿ“ˆ Dormant Account Analysis 
๐Ÿ“ˆ Unusual Transaction Detection 
๐Ÿ“ˆ Customer Profitability 
๐Ÿ“ˆ Executive Banking Dashboard 

๐Ÿ’ก Example 1: Total Deposits 
SELECT SUM(amount) AS total_deposits 
FROM transactions 
WHERE transaction_type = 'Deposit' AND transaction_status = 'Success'; 

๐Ÿ’ก Example 2: Customer Transaction Summary 
SELECT c.customer_id, c.customer_name, COUNT(t.transaction_id) AS total_transactions, SUM(t.amount) AS total_transaction_value 
FROM customers c 
JOIN accounts a ON c.customer_id = a.customer_id 
JOIN transactions t ON a.account_id = t.account_id 
WHERE t.transaction_status = 'Success' 
GROUP BY c.customer_id, c.customer_name 
ORDER BY total_transaction_value DESC; 

๐Ÿ’ก Example 3: Branch-wise Deposits 
SELECT b.branch_name, SUM(t.amount) AS total_deposits 
FROM branches b 
JOIN accounts a ON b.branch_id = a.branch_id 
JOIN transactions t ON a.account_id = t.account_id 
WHERE t.transaction_type = 'Deposit' AND t.transaction_status = 'Success' 
GROUP BY b.branch_name 
ORDER BY total_deposits DESC; 

๐Ÿ’ก Example 4: Identify High-Value Customers 
SELECT c.customer_id, c.customer_name, SUM(a.current_balance) AS total_balance 
FROM customers c 
JOIN accounts a ON c.customer_id = a.customer_id 
GROUP BY c.customer_id, c.customer_name 
HAVING SUM(a.current_balance) > 500000 
ORDER BY total_balance DESC; 

๐Ÿ’ก Example 5: Monthly Transaction Trend 
SELECT DATE_TRUNC('month', transaction_date) AS month, COUNT(*) AS transaction_count, SUM(amount) AS transaction_value 
FROM transactions 
WHERE transaction_status = 'Success' 
GROUP BY DATE_TRUNC('month', transaction_date) 
ORDER BY month; 

๐Ÿ’ก Example 6: Rank Customers by Balance 
SELECT c.customer_name, SUM(a.current_balance) AS total_balance, DENSE_RANK() OVER (ORDER BY SUM(a.current_balance) DESC) AS balance_rank 
FROM customers c 
JOIN accounts a ON c.customer_id = a.customer_id 
GROUP BY c.customer_id, c.customer_name; 

๐Ÿ’ก Example 7: Identify Potentially Unusual Transactions 
SELECT account_id, transaction_id, transaction_date, amount 
FROM transactions 
WHERE amount > 100000 AND transaction_status = 'Success' 
ORDER BY amount DESC; 

๐ŸŽฏ Key Insights You Can Derive 

๐Ÿ”น Which branches generate the highest transaction volume? 
๐Ÿ”น Which customer segments hold the most deposits? 
๐Ÿ”น Who are the highest-value customers? 
๐Ÿ”น Which account types have the highest activity? 
๐Ÿ”น How are deposits and withdrawals trending? 
๐Ÿ”น Which customers have significant loan exposure? 
๐Ÿ”น Which transactions may require additional investigation? 

๐Ÿ’ผ Double Tap โค๏ธ For More
  • โค 7
Post #2674 1.96K
๐Ÿš€ SQL Project Series #36

Banking Customer & Transaction Analytics ๐Ÿฆ

Analyze customers, accounts, transactions, branches, and loan activity using SQL to understand customer behavior, transaction trends, account profitability, and banking operations.

๐ŸŽฏ Business Objectives

โœ… Analyze customer activity
โœ… Monitor account balances
โœ… Track deposits and withdrawals
โœ… Identify high-value customers
โœ… Analyze branch performance
โœ… Detect unusual transaction patterns
โœ… Measure loan performance
โœ… Build banking dashboards

๐Ÿ“‚ Step 1: Create Database

CREATE DATABASE banking_analytics_db;
USE banking_analytics_db;


๐Ÿ“‚ Step 2: Create Customers Table

CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100),
city VARCHAR(50),
customer_segment VARCHAR(30),
signup_date DATE
);


๐Ÿ“‚ Step 3: Create Branches Table

CREATE TABLE branches (
branch_id INT PRIMARY KEY,
branch_name VARCHAR(100),
city VARCHAR(50)
);


๐Ÿ“‚ Step 4: Create Accounts Table

CREATE TABLE accounts (
account_id INT PRIMARY KEY,
customer_id INT,
branch_id INT,
account_type VARCHAR(30),
opening_date DATE,
current_balance DECIMAL(15,2),
account_status VARCHAR(20),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
FOREIGN KEY (branch_id) REFERENCES branches(branch_id)
);


๐Ÿ“‚ Step 5: Create Transactions Table

CREATE TABLE transactions (
transaction_id INT PRIMARY KEY,
account_id INT,
transaction_date DATETIME,
transaction_type VARCHAR(30),
amount DECIMAL(15,2),
transaction_status VARCHAR(20),
FOREIGN KEY (account_id) REFERENCES accounts(account_id)
);


๐Ÿ“‚ Step 6: Create Loans Table

CREATE TABLE loans (
loan_id INT PRIMARY KEY,
customer_id INT,
loan_type VARCHAR(50),
loan_amount DECIMAL(15,2),
interest_rate DECIMAL(5,2),
loan_status VARCHAR(20),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);


๐Ÿ“‚ Step 7: Insert Sample Customers

INSERT INTO customers VALUES
(1,'Rahul Sharma','Mumbai','Premium','2022-01-10'),
(2,'Priya Verma','Delhi','Mass Affluent','2022-04-15'),
(3,'Amit Patel','Pune','Premium','2023-02-20'),
(4,'Sneha Joshi','Bangalore','Mass Market','2023-06-05'),
(5,'Rohan Gupta','Hyderabad','Premium','2024-01-18');


๐Ÿ“‚ Step 8: Insert Sample Branches

INSERT INTO branches VALUES
(101,'Mumbai Central','Mumbai'),
(102,'Connaught Place','Delhi'),
(103,'Pune Central','Pune'),
(104,'Bangalore Main','Bangalore');


๐Ÿ“‚ Step 9: Insert Sample Accounts

INSERT INTO accounts VALUES
(1001,1,101,'Savings','2022-01-10',250000,'Active'),
(1002,2,102,'Current','2022-04-15',520000,'Active'),
(1003,3,103,'Savings','2023-02-20',175000,'Active'),
(1004,4,104,'Savings','2023-06-05',85000,'Active'),
(1005,5,101,'Current','2024-01-18',750000,'Active');


๐Ÿ“‚ Step 10: Insert Sample Transactions

INSERT INTO transactions VALUES
(5001,1001,'2025-01-05 10:15:00','Deposit',50000,'Success'),
(5002,1001,'2025-01-07 14:30:00','Withdrawal',15000,'Success'),
(5003,1002,'2025-01-08 11:20:00','Deposit',120000,'Success'),
(5004,1003,'2025-01-10 09:45:00','Withdrawal',25000,'Success'),
(5005,1004,'2025-01-12 16:10:00','Deposit',30000,'Success'),
(5006,1005,'2025-01-15 13:25:00','Withdrawal',85000,'Success'),
(5007,1003,'2025-01-18 18:40:00','Transfer',45000,'Success');


๐Ÿ“‚ Step 11: Insert Sample Loans

INSERT INTO loans VALUES
(9001,1,'Home Loan',5000000,8.25,'Active'),
(9002,2,'Personal Loan',800000,11.50,'Active'),
(9003,3,'Car Loan',1200000,9.10,'Active'),
(9004,4,'Personal Loan',500000,12.00,'Closed'),
(9005,5,'Business Loan',3000000,10.25,'Active');


๐Ÿง  SQL Concepts You'll Practice

โœ” INNER JOIN
โœ” LEFT JOIN
โœ” GROUP BY
โœ” HAVING
โœ” CASE WHEN
โœ” CTEs
โœ” Subqueries
โœ” Window Functions
โœ” RANK()
โœ” DENSE_RANK()
โœ” LAG()
โœ” Date Functions
โœ” Conditional Aggregation
โœ” Financial KPI Calculations

๐Ÿ“Š Business KPIs You Can Build
  • โค 7
Older posts โ†’
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 โ†’