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
600
Videos
1
Links
570

Showing posts older than #2812 · Back to latest

Older Posts 17 shown
Post #2811 458
SELECT
region,
COUNT(*)
FROM orders
GROUP BY region;


An index on "region" may sometimes help, depending on the database and execution plan.

But indexes don't automatically make every aggregation faster.

For large analytical workloads, the database may choose another strategy.

9️⃣ Primary Keys and Indexes

Primary keys are commonly backed by an index or equivalent structure.

For example:

CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100)
);


The database generally creates an index-like structure to enforce primary-key uniqueness and support efficient lookups.

The exact implementation varies by database system.

🔟 Unique Index

A unique index prevents duplicate values in the indexed key.

Example:

CREATE UNIQUE INDEX idx_customers_email
ON customers(email);


Now duplicate email values are not allowed, subject to the database's NULL semantics.

For example:

• customer1@example.com

• customer2@example.com

can exist.

But two identical non-NULL values generally cannot.

A "UNIQUE" constraint is another way to enforce uniqueness and may be implemented using a unique index depending on the database.

1️⃣1️⃣ Single-Column Index

An index can contain one column.

CREATE INDEX idx_orders_customer
ON orders(customer_id);


This is called a single-column index.

Useful when queries frequently search using:

WHERE customer_id = ...

1️⃣2️⃣ Composite Index

An index can also contain multiple columns.

CREATE INDEX idx_orders_customer_date
ON orders(customer_id, order_date);


This is called a composite index or multi-column index.

It can be useful for queries such as:

SELECT *
FROM orders
WHERE customer_id = 101
AND order_date >= DATE '2026-01-01';


1️⃣3️⃣ Column Order Matters

This is one of the most important concepts with composite indexes.

Suppose:

CREATE INDEX idx_orders_customer_date
ON orders(customer_id, order_date);


The index starts with:

customer_id

and then:

order_date

This means the index is particularly useful for queries that use the leading column:

WHERE customer_id = 101

and often:

WHERE customer_id = 101
AND order_date >= DATE '2026-01-01';


But a query filtering only:

WHERE order_date >= DATE '2026-01-01'

may not benefit from this index in the same way.

The exact behavior depends on the database engine and optimizer.

1️⃣4️⃣ The Leftmost Prefix Concept

For:

CREATE INDEX idx_orders
ON orders(customer_id, order_date, status);


Think of the index as:

customer_id

↓

order_date

↓

status

Queries using the leading columns can often take better advantage of the index.

For example:

WHERE customer_id = 101

or:

WHERE customer_id = 101
AND order_date >= DATE '2026-01-01'


can be good candidates.

But:

WHERE status = 'Completed'

doesn't start with the leading indexed column.

The optimizer may therefore choose another access method.

1️⃣5️⃣ Indexes and LIKE

Consider:

SELECT *
FROM customers
WHERE customer_name LIKE 'Rah%';


An index may be usable for a prefix search in some database systems.

But:

WHERE customer_name LIKE '%Rah';

or:

WHERE customer_name LIKE '%Rah%';

can make ordinary B-tree index usage less effective because the pattern begins with a wildcard.

Database-specific indexing features can change this behavior.

1️⃣6️⃣ Indexes and Functions

Consider:
Post #2810 754
🚀 SQL Roadmap 2026 — Part 18

SQL Indexes & Query Performance

Writing a correct SQL query is important.

But in real-world data analytics, especially when working with millions or billions of rows, another question matters:

«How efficiently does the database find the data?»

This is where SQL indexes become important.

Indexes can dramatically improve data retrieval when used appropriately, but they also come with storage and write-performance costs.

1️⃣ What Is a SQL Index?

An index is a database structure that helps the database find rows more efficiently.

Think about a book.

Without an index:

Search for a topic

↓

Read page 1

↓

Read page 2

↓

Read page 3

↓

...

↓

Eventually find the topic

With an index:

Search topic

↓

Check index

↓

Find page

↓

Go directly to the relevant section

A database index works on a similar principle.

Instead of scanning every row, the database may use an index to locate relevant rows more efficiently.

2️⃣ Why Do We Need Indexes?

Imagine a table containing:

10 million customers

You run:

SELECT *
FROM customers
WHERE customer_id = 100245;


Without a suitable index, the database may need to inspect many rows.

With an appropriate index:

CREATE INDEX idx_customers_customer_id
ON customers(customer_id);


the database may be able to locate the requested row much more efficiently.

The exact execution strategy is chosen by the database optimizer.

3️⃣ Creating an Index

Basic syntax:

CREATE INDEX index_name
ON table_name(column_name);


Example:

CREATE INDEX idx_customers_email
ON customers(email);


Now the database has an index on:

customers.email

4️⃣ Querying an Indexed Column

You don't need to change your SQL query after creating the index.

You still write:

SELECT *
FROM customers
WHERE email = 'customer@example.com';


The database optimizer decides whether using the index is beneficial.

Important:

«Creating an index does not guarantee that the database will use it.»

5️⃣ Indexes and WHERE Conditions

Indexes are particularly useful for columns frequently used for filtering.

For example:

SELECT *
FROM orders
WHERE customer_id = 101;


An index on "customer_id" may help:

CREATE INDEX idx_orders_customer_id
ON orders(customer_id);


Other common candidates include:

• customer_id

• order_id

• transaction_id

• account_id

• date columns

• status columns

• foreign keys

But whether an index is useful depends on the data, query patterns, database engine, and existing indexes.

6️⃣ Indexes and JOINs

Indexes can also help queries involving JOINs.

Consider:

SELECT
c.customer_name,
o.order_amount
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id;


An index on the relevant join column may help the database execute the JOIN efficiently.

For example:

CREATE INDEX idx_orders_customer_id
ON orders(customer_id);


This is one reason foreign-key columns are often considered for indexing.

However, indexing strategy should be based on actual workload and execution plans rather than applying indexes blindly.

7️⃣ Indexes and ORDER BY

Suppose you frequently run:

SELECT *
FROM orders
ORDER BY order_date;


An index on:

order_date

may help some database systems avoid or reduce sorting work.

Example:

CREATE INDEX idx_orders_order_date
ON orders(order_date);


But again, the optimizer determines whether the index provides a benefit for the particular query.

8️⃣ Indexes and GROUP BY

Consider:
Post #2809 1.23K
𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄𝗲𝗿: You have 2 minutes to solve this SQL query.
Retrieve the department name and the highest salary in each department from the employees table, but only for departments where the highest salary is greater than $70,000.

𝗠𝗲: Challenge accepted!

SELECT department, MAX(salary) AS highest_salary
FROM employees
GROUP BY department
HAVING MAX(salary) > 70000;

I used GROUP BY to group employees by department, MAX() to get the highest salary, and HAVING to filter the result based on the condition that the highest salary exceeds $70,000. This solution effectively shows my understanding of aggregation functions and how to apply conditions on the result of those aggregations.

𝗧𝗶𝗽 𝗳𝗼𝗿 𝗦𝗤𝗟 𝗝𝗼𝗯 𝗦𝗲𝗲𝗸𝗲𝗿𝘀:
It's not about writing complex queries; it's about writing clean, efficient, and scalable code. Focus on mastering subqueries, joins, and aggregation functions to stand out!

Like this post if you need more 👍❤️

Hope it helps :)
  • ❤ 11
  • 👍 1
Post #2808 1.6K
𝗡𝗲𝘄 𝗔𝗜 𝗧𝗼𝗼𝗹 𝗔𝗹𝗲𝗿𝘁: 𝗚𝗶𝗴𝗮𝗖𝗵𝗮𝘁 𝟯.𝟱 𝗥𝗲𝗮𝘀𝗼𝗻𝗶𝗻𝗴 🚀

Want to solve complex coding & math problems faster? This new open-source LLM actually thinks before it answers!

💡 Built on GigaChat 3.5 Ultra: explores multiple step-by-step reasoning paths & uses automated verification

💡 Autonomously plans multi-step actions & decides when to call external tools

💡 Highly efficient: Linear attention retains key points, using 37% fewer tokens than DeepSeek V4 Flash Preview

📈 Massive benchmark gains over non-reasoning versions:
• IFBench: 44 → 77
• Natural Plan: 64 → 80
• LiveCodeBench v6: 56 → 85

🎯 Perfect for Software Engineers, Data Scientists, and Students preparing for technical interviews!

🔗 𝗗𝗼𝘄𝗻𝗹𝗼𝗮𝗱 𝘄𝗲𝗶𝗴𝗵𝘁𝘀 𝗵𝗲𝗿𝗲 👇 (MIT License):
fp8 | bf16
  • ❤ 8
  • 👍 1
  • 👏 1
Post #2807 1.64K
🚀 𝗧𝗼𝗽 𝟳 𝗙𝗥𝗘𝗘 𝗠𝗶𝗰𝗿𝗼𝘀𝗼𝗳𝘁 𝗖𝗼𝘂𝗿𝘀𝗲𝘀 𝘁𝗼 𝗟𝗲𝗮𝗿𝗻 𝗗𝗮𝘁𝗮 𝗔𝗻𝗮𝗹𝘆𝘁𝗶𝗰𝘀! 📊

Want to start a career in Data Analytics?

Explore these 7 free Microsoft-backed learning resources covering Power BI, Excel, SQL and data fundamentals

🔗 𝗔𝗰𝗰𝗲𝘀𝘀 𝘁𝗵𝗲 𝗙𝗥𝗘𝗘 𝗖𝗼𝘂𝗿𝘀𝗲𝘀 👇

https://pdlink.in/3Tm2D3Z

💡 Ideal for students, freshers and professionals who want to build practical data skills.
  • ❤ 1
Post #2806 1.71K
🎓 𝗦𝘁𝗮𝗻𝗳𝗼𝗿𝗱 𝗨𝗻𝗶𝘃𝗲𝗿𝘀𝗶𝘁𝘆 𝗙𝗥𝗘𝗘 𝗢𝗻𝗹𝗶𝗻𝗲 𝗖𝗼𝘂𝗿𝘀𝗲𝘀! 🚀

Explore free online learning opportunities from Stanford University across technology, business and more!

💻 Tech & Programming
🤖 Artificial Intelligence & Data Science
💼 Business & Entrepreneurship
💡 Leadership & Innovation

🔗 𝗘𝘅𝗽𝗹𝗼𝗿𝗲 𝘁𝗵𝗲 𝗙𝗥𝗘𝗘 𝗖𝗼𝘂𝗿𝘀𝗲𝘀 👇

https://pdlink.in/4hlnZGw

🎯 Great for students, freshers and working professionals looking to expand their knowledge.
Post #2805 1.63K
Q6. Can every View be updated?

No. Whether a View is updatable depends on its definition and the database system.

Q7. Does creating a View automatically improve performance?

No. A normal View is primarily used for abstraction, reuse, and centralized logic.

Q8. What is a Materialized View?

A Materialized View stores the result of a query physically and can be refreshed according to the database's configuration.

Q9. Why are Views useful in BI?

They can provide a clean, reusable reporting layer while centralizing SQL transformations and business logic.

Q10. What is one security benefit of Views?

A View can expose only selected columns or rows instead of giving users direct access to the entire underlying table, when combined with appropriate permissions.

🧠 Practice Questions

Practice 1

Create a View containing active customers.

CREATE VIEW active_customers AS
SELECT
customer_id,
customer_name,
country
FROM customers
WHERE status = 'Active';


Practice 2

Query only customers from India:

SELECT *
FROM active_customers
WHERE country = 'India';


Practice 3

Create a View showing total sales by region.

CREATE VIEW regional_sales AS
SELECT
region,
SUM(order_amount) AS total_sales
FROM orders
GROUP BY region;


Practice 4

Find regions with sales above 500,000.

SELECT *
FROM regional_sales
WHERE total_sales > 500000;


Practice 5

Create a View combining customers and their orders.

CREATE VIEW customer_orders AS
SELECT
c.customer_id,
c.customer_name,
o.order_id,
o.order_date,
o.order_amount
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id;


🔥 Mini Challenge

You have:

customers

orders

The customers table contains:

customer_id

customer_name

region

status

The orders table contains:

order_id

customer_id

order_date

order_amount

Create a View called customer_sales_summary containing:

• Customer ID

• Customer name

• Region

• Number of orders

• Total sales

• Average order value

Solution

CREATE VIEW customer_sales_summary AS
SELECT
c.customer_id,
c.customer_name,
c.region,
COUNT(o.order_id) AS order_count,
SUM(o.order_amount) AS total_sales,
AVG(o.order_amount) AS average_order_value
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
GROUP BY
c.customer_id,
c.customer_name,
c.region;


Now you can easily analyze high-value customers:

SELECT *
FROM customer_sales_summary
WHERE total_sales > 100000
ORDER BY total_sales DESC;


🎯 Key Takeaway

TABLE → Stores data

VIEW → Stores a reusable query definition

MATERIALIZED VIEW → Stores the query result

A strong Data Analyst doesn't just know how to write SQL queries.

They also know how to create reusable, maintainable, and consistent data logic.

🎯 Double Tap ❤️ For More
  • ❤ 5
  • 👏 1
Post #2804 903
This is particularly useful when your reporting logic contains multiple analytical steps.

1️⃣8️⃣ Views Can Be Layered

In some environments, one View can reference another View.

For example:

Raw Tables → View 1 → View 2 → Reporting View → Dashboard

This can be powerful, but excessive layering can make debugging and performance analysis difficult.

A good design keeps dependencies understandable.

1️⃣9️⃣ Common Mistakes

❌ Mistake 1: Assuming a View stores a separate copy of data

A normal View generally stores the query definition, not an independent copy of the data.

❌ Mistake 2: Assuming Views always improve performance

They primarily improve abstraction and reuse.

❌ Mistake 3: Creating too many nested Views

A complicated chain of Views can become difficult to maintain.

❌ Mistake 4: Forgetting business logic inside a View

If a View contains WHERE status = 'Active', users need to understand that the View already filters inactive records.

❌ Mistake 5: Using SELECT * unnecessarily

Instead of:

CREATE VIEW customer_report AS
SELECT *
FROM customers;


prefer explicitly listing the columns needed:

CREATE VIEW customer_report AS
SELECT
customer_id,
customer_name,
country,
status
FROM customers;


This makes the View's structure clearer and more controlled.

💼 Real-World Data Analyst Example

Suppose you regularly create a monthly sales report.

Every time, you write:

SELECT
region,
DATE_TRUNC('month', order_date) AS month,
SUM(order_amount) AS revenue,
COUNT(DISTINCT customer_id) AS customers,
COUNT(*) AS orders
FROM orders
GROUP BY
region,
DATE_TRUNC('month', order_date);


Instead, create:

CREATE VIEW monthly_sales_report AS
SELECT
region,
DATE_TRUNC('month',
order_date) AS month,
SUM(order_amount) AS revenue,
COUNT(DISTINCT customer_id) AS customers,
COUNT(*) AS orders
FROM orders
GROUP BY
region,
DATE_TRUNC('month', order_date);


Now your analysis becomes:

SELECT *
FROM monthly_sales_report;


You can even filter it:

SELECT *
FROM monthly_sales_report
WHERE month >= DATE '2026-01-01'
ORDER BY revenue DESC;


The View becomes a reusable reporting layer.

🎯 Interview Questions

Q1. What is a SQL View?

A View is a named database object that represents the result of a SQL query and can generally be queried like a table.

Q2. Does a normal View physically store data?

Generally, no. It stores the query definition rather than a separate copy of the underlying data.

Q3. What is the difference between a View and a table?

A table physically stores data, while a normal View generally represents a query over underlying data.

Q4. Can a View contain JOINs?

Yes.

CREATE VIEW customer_orders AS
SELECT ...
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id;


Q5. Can a View contain GROUP BY?

Yes.

CREATE VIEW regional_sales AS
SELECT
region,
SUM(amount) AS total_sales
FROM sales
GROUP BY region;
Post #2803 501
SELECT
customer_type,
COUNT(*) AS customer_count
FROM customer_classification
GROUP BY customer_type;


This helps keep business definitions consistent.

1️⃣4️⃣ Views for BI and Reporting

Views are very common in reporting environments.

Imagine Power BI needs:

Customer, Order, Product, Region, Revenue, Profit, Order Date

Instead of exposing many raw tables, a database team may create a reporting View:

CREATE VIEW sales_reporting AS
SELECT
o.order_id,
o.order_date,
c.customer_id,
c.customer_name,
p.product_name,
o.region,
o.sales_amount,
o.profit
FROM orders o
JOIN customers c
ON o.customer_id = c.customer_id
JOIN products p
ON o.product_id = p.product_id;


The BI tool can then consume:

SELECT *
FROM sales_reporting;


This can simplify the data model and centralize transformation logic.

1️⃣5️⃣ Views and Query Performance

A very important point:

A normal View does not automatically make a query faster.

For example:

CREATE VIEW customer_orders AS
SELECT ...
FROM customers
JOIN orders ...;


Then:

SELECT *
FROM customer_orders;


The database generally still needs to execute the underlying query.

A View is primarily an abstraction and reuse mechanism.

Performance depends on factors such as:

• Indexes

• Query structure

• Join conditions

• Filtering

• Data volume

• Database optimizer

• Statistics

• Execution plan

Some database systems also support materialized views, which are different.

1️⃣6️⃣ Materialized View

A Materialized View stores the result of a query physically.

Conceptually:

Normal View → Stores query definition

Materialized View → Stores query result

Example concept:

CREATE MATERIALIZED VIEW monthly_sales AS
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(order_amount) AS total_sales
FROM orders
GROUP BY DATE_TRUNC('month', order_date);


The exact syntax and refresh behavior depend heavily on the database.

Materialized Views can be useful when:

• Queries are expensive

• Data is large

• Aggregations are repeatedly requested

• Near-real-time data isn't required

But the stored result needs to be refreshed according to the database's configuration.

1️⃣7️⃣ View with CTE

You can also create a View using a CTE.

CREATE VIEW customer_summary AS
WITH customer_orders AS (
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(order_amount) AS total_sales
FROM orders
GROUP BY customer_id
)
SELECT
c.customer_id,
c.customer_name,
co.order_count,
co.total_sales
FROM customers c
JOIN customer_orders co
ON c.customer_id = co.customer_id;


Now the complex logic is reusable:

SELECT *
FROM customer_summary;
Post #2802 551
This avoids having slightly different definitions of "High Value Customer" across reports.

7️⃣ View vs Table

This is an important distinction.

Table

A table physically stores data.

Customers Table → Data is stored

View

A normal View stores the query definition rather than a separate copy of the underlying data.

Customers Table → View → Query result

So if the underlying data changes, querying the View generally reflects the current underlying data.

8️⃣ View vs Temporary Table

These are also different.

View

Usually created for reusable logic:

CREATE VIEW customer_summary AS
SELECT ...


It can be used by multiple queries and users, subject to permissions.

Temporary Table

Used to store intermediate results temporarily.

For example:

CREATE TEMPORARY TABLE temp_customer_data AS
SELECT *
FROM customers
WHERE status = 'Active';


The exact temporary-table syntax varies by database.

Simple distinction:

VIEW → Reusable saved query

TEMP TABLE → Temporary stored result

9️⃣ Can You Update Data Through a View?

Sometimes.

Certain simple Views may be updatable.

For example:

CREATE VIEW active_customers AS
SELECT
customer_id,
customer_name,
status
FROM customers
WHERE status = 'Active';


Depending on the database and View definition, an operation such as:

UPDATE active_customers
SET customer_name = 'New Name'
WHERE customer_id = 101;


may update the underlying table.

However, Views containing things such as:

• Aggregations

• GROUP BY

• DISTINCT

• Set operators

• Certain JOINs

• Window functions

may not be directly updatable, depending on the database.

Therefore, don't assume every View can be modified.

🔟 CREATE OR REPLACE VIEW

If your database supports it, you can modify a View definition using:

CREATE OR REPLACE VIEW active_customers AS
SELECT
customer_id,
customer_name,
country,
status
FROM customers
WHERE status = 'Active';


This allows you to change the query behind the View without creating a completely new View.

The exact syntax varies between database systems.

1️⃣1️⃣ Dropping a View

If you no longer need a View:

DROP VIEW active_customers;


This removes the View definition.

It does not normally mean that the underlying table data is deleted.

For example:

DROP VIEW customer_orders;


doesn't mean:

DELETE FROM customers;
DELETE FROM orders;


The underlying tables remain.

1️⃣2️⃣ Views for Data Security

Views can also help control which columns users can access.

Suppose your employee table contains:

employee_id

employee_name

department

salary

bank_account

You may not want every analyst to access sensitive columns.

You could create:

CREATE VIEW employee_directory AS
SELECT
employee_id,
employee_name,
department
FROM employees;


Users can query:

SELECT *
FROM employee_directory;


without directly accessing columns that aren't included in the View.

Important: a View is not automatically a complete security solution. Proper database permissions are still required.

1️⃣3️⃣ Views for Business Logic

Suppose the business defines:

High Value Customer = Customer with sales >= 100,000

You can encode this definition in a View:

CREATE VIEW customer_classification AS
SELECT
customer_id,
customer_name,
total_sales,
CASE
WHEN total_sales >= 100000
THEN 'High Value'
ELSE 'Standard'
END AS customer_type
FROM customers;


Now different reports can use:
Post #2801 1.24K
🚀 SQL Roadmap 2026 — Part 17

SQL Views — Creating Reusable Virtual Tables

A SQL View is a saved SQL query that behaves like a virtual table.

Instead of writing the same complex query repeatedly, you can create a View once and query it like a table.

This is especially useful in:

• Data analytics

• Reporting

• Business Intelligence

• Power BI datasets

• Data warehouses

• Reusable business logic

• Data security

1️⃣ What Is a View?

Suppose you frequently need this query:

SELECT
customer_id,
customer_name,
country,
total_sales
FROM customers
WHERE country = 'India'
AND total_sales > 100000;


Instead of writing it every time, you can create a View:

CREATE VIEW high_value_indian_customers AS
SELECT
customer_id,
customer_name,
country,
total_sales
FROM customers
WHERE country = 'India'
AND total_sales > 100000;


Now you can simply write:

SELECT *
FROM high_value_indian_customers;


The View behaves like a table from the user's perspective.

2️⃣ Why Do We Need Views?

Imagine your reporting query contains:

• 4 JOINs

• 3 CASE statements

• Multiple filters

• Several calculated columns

• Aggregations

You don't want every analyst or report to rewrite that logic.

A View allows you to centralize the logic.

3️⃣ Basic CREATE VIEW Syntax

The general syntax is:

CREATE VIEW view_name AS
SELECT
column1,
column2,
column3
FROM table_name
WHERE condition;


Example:

CREATE VIEW active_customers AS
SELECT
customer_id,
customer_name,
country
FROM customers
WHERE status = 'Active';


Query the View:

SELECT *
FROM active_customers;


4️⃣ A View Can Contain JOINs

Views aren't limited to simple SELECT statements.

For example:

CREATE VIEW customer_orders AS
SELECT
c.customer_id,
c.customer_name,
o.order_id,
o.order_date,
o.order_amount
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id;


Now:

SELECT *
FROM customer_orders;


returns the result of that JOIN.

You don't need to repeatedly write the JOIN.

5️⃣ Views with Aggregation

You can also create aggregated Views.

Suppose management regularly needs regional sales:

CREATE VIEW regional_sales AS
SELECT
region,
SUM(order_amount) AS total_sales,
COUNT(*) AS total_orders
FROM orders
GROUP BY region;


Now:

SELECT *
FROM regional_sales;


Example result:

region     total_sales     total_orders
North 450000 1250
South 620000 1580
West 510000 1390
East 380000 980


You can further analyze the View:

SELECT *
FROM regional_sales
WHERE total_sales > 500000;


6️⃣ Views with CASE Statements

Views are useful for standardizing business logic.

For example:

CREATE VIEW customer_segments AS
SELECT
customer_id,
customer_name,
total_sales,
CASE
WHEN total_sales >= 100000 THEN 'High Value'
WHEN total_sales >= 50000 THEN 'Medium Value'
ELSE 'Low Value'
END AS customer_segment
FROM customers;


Now every report can use the same segmentation logic:

SELECT
customer_segment,
COUNT(*) AS customers
FROM customer_segments
GROUP BY customer_segment;
  • ❤ 1
Post #2800 1.17K
𝗙𝗥𝗘𝗘 𝗔𝗜 𝗖𝗮𝗿𝗲𝗲𝗿 𝗠𝗮𝘀𝘁𝗲𝗿𝗰𝗹𝗮𝘀𝘀 🚀

Join this expert-led masterclass and discover how to become industry-ready for high-growth AI roles.

📅 Date: 24 September 2026
⏰ Time: 7:00 PM–9:00 PM IST
🌐 Mode: Online
🎓 Certificate: Available to all attendees

Eligibility :- Graduates Passing In 2025 or earlier

🔗 𝗥𝗲𝗴𝗶𝘀𝘁𝗲𝗿 𝗳𝗼𝗿 𝗙𝗥𝗘𝗘 👇

https://pdlink.in/4xAMeGW

⚡ Register now and take your first step towards a successful career in AI!
  • ❤ 2
Post #2796 1.27K
Double Tap ❤️ For More SQL Notes
  • ❤ 7
  • 👏 1
Post #2795 1.38K
🚀 𝗧𝗼𝗽 𝗜𝗻-𝗗𝗲𝗺𝗮𝗻𝗱 𝗖𝗲𝗿𝘁𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀 𝘁𝗼 𝗠𝗮𝘀𝘁𝗲𝗿 𝗶𝗻 𝟮𝟬𝟮𝟲

Explore these certification courses in today’s most in-demand technology fields:

💻 Full Stack :- https://pdlink.in/3SuUeuD

📊 Data Analytics :- https://pdlink.in/45vk5ph

💫AI Engineering :- https://pdlink.in/4fWJVID

🔥 Take the first step towards your high-paying tech career in 2026!
  • ❤ 1
Post #2794 1.49K
💼 Interview Questions

Q1. What is UNION? - Combines results from multiple SELECT statements and removes duplicate rows.

Q2. What is UNION ALL? - Combines results while retaining duplicates.

Q3. Which is generally faster: UNION or UNION ALL? - UNION ALL is generally faster when duplicate removal isn't required.

Q4. What is the difference between UNION and JOIN? - JOIN combines related tables horizontally by adding columns. UNION combines compatible result sets vertically by adding rows.

Q5. What does INTERSECT do? - Returns rows common to both result sets.

Q6. What does EXCEPT do? - Returns rows present in the first result set but absent from the second.

Q7. What is MINUS? - In Oracle, MINUS is commonly used for the same type of operation as EXCEPT.

Q8. Do the columns have to have the same names? - No. The queries need compatible column positions and data types.

Q9. Can you use ORDER BY with UNION? - Yes. Normally, place the final ORDER BY after the complete set operation.

Q10. When would you choose UNION ALL instead of UNION? - When duplicate rows are valid or when you know the inputs are already unique.

🧠 Practice Questions

Practice 1 - Combine customers from two tables while keeping duplicates.

SELECT customer_id FROM customers_a
UNION ALL
SELECT customer_id FROM customers_b;


Practice 2 - Find customers who appear in both tables.

SELECT customer_id FROM customers_a
INTERSECT
SELECT customer_id FROM customers_b;


Practice 3 - Find customers who appear in customers_a but not customers_b.

SELECT customer_id FROM customers_a
EXCEPT
SELECT customer_id FROM customers_b;


Practice 4 - Combine two years of transactions and calculate total transaction value.

SELECT SUM(amount) AS total_amount FROM (
SELECT amount FROM transactions_2025
UNION ALL
SELECT amount FROM transactions_2026
) t;


Practice 5 - Find unique customer IDs across two sales channels.

SELECT customer_id FROM online_sales
UNION
SELECT customer_id FROM store_sales;


🔥 Mini Challenge

You have two tables: orders_2025 and orders_2026 with columns: order_id, customer_id, order_amount

Write SQL to:

1. Combine all orders from both years.

2. Calculate total order value.

3. Calculate total number of orders.

4. Find customers who ordered in both years.

5. Find customers who ordered in 2025 but not in 2026.

Solution:

-- 1. Combine all orders
SELECT order_id, customer_id, order_amount FROM orders_2025
UNION ALL
SELECT order_id, customer_id, order_amount FROM orders_2026;

-- 2. Total order value
SELECT SUM(order_amount) AS total_order_value FROM (
SELECT order_amount FROM orders_2025
UNION ALL
SELECT order_amount FROM orders_2026
) o;

-- 3. Total number of orders
SELECT COUNT(*) AS total_orders FROM (
SELECT order_id FROM orders_2025
UNION ALL
SELECT order_id FROM orders_2026
) o;

-- 4. Customers who ordered in both years
SELECT customer_id FROM orders_2025
INTERSECT
SELECT customer_id FROM orders_2026;

-- 5. Customers who ordered in 2025 but not 2026
SELECT customer_id FROM orders_2025
EXCEPT
SELECT customer_id FROM orders_2026;


🎯 Double Tap ❤️ For More
  • ❤ 5
Post #2793 922
If 2025: 101, 102, 103 and 2026: 102, 103, 104 → Result: 102, 103

Real-world use - Find customers who purchased in both years:

SELECT customer_id FROM purchases_2025
INTERSECT
SELECT customer_id FROM purchases_2026;


9️⃣ EXCEPT

"EXCEPT" returns rows from the first query that don't exist in the second query.

SELECT customer_id FROM customers_2025
EXCEPT
SELECT customer_id FROM customers_2026;


Result: 101. In Oracle, the equivalent is commonly: MINUS

🔟 Understanding the Four Operators

Suppose: A = {1, 2, 3}, B = {2, 3, 4}

• UNION → {1, 2, 3, 4}

• UNION ALL → {1, 2, 3, 2, 3, 4}

• INTERSECT → {2, 3}

• EXCEPT → {1}

This is the easiest way to remember them.

1️⃣1️⃣ UNION for Combining Similar Data

SELECT order_id, customer_id, sales_amount FROM online_sales
UNION ALL
SELECT order_id, customer_id, sales_amount FROM store_sales;


1️⃣2️⃣ Current + Historical Data

SELECT * FROM current_transactions
UNION ALL
SELECT * FROM historical_transactions;


1️⃣3️⃣ Finding Common Customers

SELECT customer_id FROM product_a_users
INTERSECT
SELECT customer_id FROM product_b_users;


1️⃣4️⃣ Finding Customers Who Stopped Using a Product

SELECT customer_id FROM product_a_users
EXCEPT
SELECT customer_id FROM product_b_users;


1️⃣5️⃣ Set Operators vs JOINs

JOIN - JOIN combines columns from related tables.

SELECT c.customer_id, c.customer_name, o.order_amount
FROM customers c JOIN orders o ON c.customer_id = o.customer_id;


UNION - UNION combines rows from compatible queries.

Simple rule: JOIN → Add columns, UNION → Add rows

1️⃣6️⃣ UNION vs JOIN — Example

Table A: 101 Rahul, 102 Priya | Table B: 103 Amit, 104 Neha

To stack the records:

SELECT customer_id, name FROM table_a
UNION ALL
SELECT customer_id, name FROM table_b;


Result: 101 Rahul, 102 Priya, 103 Amit, 104 Neha

1️⃣7️⃣ Using Set Operators with Filters

SELECT customer_id FROM customers_2025 WHERE country = 'India'
UNION
SELECT customer_id FROM customers_2026 WHERE country = 'India';


1️⃣8️⃣ Set Operators with Aggregation

SELECT region, SUM(sales_amount) AS total_sales FROM sales_2025 GROUP BY region
UNION ALL
SELECT region, SUM(sales_amount) AS total_sales FROM sales_2026 GROUP BY region;


For one combined total per region:

SELECT region, SUM(sales_amount) AS total_sales FROM (
SELECT region, sales_amount FROM sales_2025
UNION ALL
SELECT region, sales_amount FROM sales_2026
) s GROUP BY region;


1️⃣9️⃣ NULL Values with Set Operators

NULL values can participate in set operations. If both result sets contain NULL, duplicate elimination treats the corresponding rows as duplicates for set-operation purposes.

2️⃣0️⃣ Common Mistakes

❌ Mistake 1: Different number of columns

❌ Mistake 2: Incompatible data types

❌ Mistake 3: Using UNION when duplicates are required - Use UNION ALL when appropriate.

❌ Mistake 4: Confusing JOIN and UNION - Remember: JOIN → combine related columns, UNION → combine compatible rows

🎯 Business Example

SELECT COUNT(*) AS payment_count FROM (
SELECT payment_id FROM payments_2025
UNION ALL
SELECT payment_id FROM payments_2026
) p;

SELECT SUM(payment_amount) AS total_payment_value FROM (
SELECT payment_amount FROM payments_2025
UNION ALL
SELECT payment_amount FROM payments_2026
) p;
  • ❤ 2
Post #2792 922
🚀 SQL Roadmap 2026 — Part 16

SQL Set Operators — UNION, UNION ALL, INTERSECT & EXCEPT

Set operators allow you to combine the results of multiple SELECT queries.

They are extremely useful when you have similar datasets and want to:

• Combine records from different sources

• Remove duplicates

• Find common records

• Find records existing in one dataset but not another

• Compare two datasets

• Combine current and historical data

The four important set operators are: UNION, UNION ALL, INTERSECT, EXCEPT



In Oracle, "MINUS" is commonly used instead of "EXCEPT".



1️⃣ What Are Set Operators?

Suppose you have two tables: customers_2025 and customers_2026. Both contain: customer_id, customer_name. You want one result containing customers from both years.

You can use:

SELECT customer_id, customer_name FROM customers_2025
UNION
SELECT customer_id, customer_name FROM customers_2026;


The result combines the two result sets.

2️⃣ UNION

"UNION" combines two result sets and removes duplicate rows.

SELECT customer_id FROM customers_2025
UNION
SELECT customer_id FROM customers_2026;


If customer "101" appears in both tables, it appears only once in the final result.

Example: 2025: 101, 102, 103 | 2026: 102, 103, 104 | Result: 101, 102, 103, 104

When to use UNION?

Use "UNION" when duplicate rows should be removed.

SELECT email FROM online_customers
UNION
SELECT email FROM store_customers;


This can produce a unique list of customer emails across both channels.

3️⃣ UNION ALL

"UNION ALL" also combines result sets, but keeps duplicates.

SELECT customer_id FROM customers_2025
UNION ALL
SELECT customer_id FROM customers_2026;


Using the previous example: Result: 101, 102, 103, 102, 103, 104. The duplicate records remain.

4️⃣ UNION vs UNION ALL

This is one of the most common SQL interview questions.

UNION → Combines results → Removes duplicates

UNION ALL → Combines results → Keeps duplicates

Performance consideration: "UNION" generally needs additional work to identify and remove duplicates.

"UNION ALL" does not need that deduplication step. Therefore, when duplicates are valid and you don't need to remove them, "UNION ALL" is generally preferable.

5️⃣ Rules for Using Set Operators

The queries being combined must be compatible.

SELECT customer_id, customer_name FROM customers
UNION
SELECT customer_id, customer_name FROM archived_customers;


Both queries return 2 columns - This is valid.

But:

SELECT customer_id, customer_name FROM customers
UNION
SELECT customer_id FROM archived_customers;


is invalid because the number of columns doesn't match.

Important rule:

The participating SELECT statements should have:

1. The same number of columns

2. Compatible data types in corresponding positions. The column names in the final result generally come from the first SELECT.

6️⃣ Column Order Matters

Set operators match columns by position, not by column name. So structure your queries carefully:

SELECT customer_id, customer_name FROM customers
UNION ALL
SELECT customer_id, customer_name FROM archived_customers;


7️⃣ ORDER BY with UNION

If you want to sort the final combined result, put "ORDER BY" at the end.

SELECT customer_id, customer_name FROM customers_2025
UNION
SELECT customer_id, customer_name FROM customers_2026
ORDER BY customer_id;


8️⃣ INTERSECT

"INTERSECT" returns rows that exist in both result sets.

SELECT customer_id FROM customers_2025
INTERSECT
SELECT customer_id FROM customers_2026;
  • ❤ 2
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 →