0% found this document useful (0 votes)
6 views13 pages

DDL FUNC

The document explains the concept of views and functions in SQL, detailing their characteristics, use cases, and limitations. Views serve as virtual tables to simplify queries and restrict data access, while functions allow for reusable logic and dynamic parameters. It also distinguishes between Query Language Functions and Procedural Language Functions, highlighting when to use each based on the complexity of the logic required.

Uploaded by

guldariya299
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

DDL FUNC

The document explains the concept of views and functions in SQL, detailing their characteristics, use cases, and limitations. Views serve as virtual tables to simplify queries and restrict data access, while functions allow for reusable logic and dynamic parameters. It also distinguishes between Query Language Functions and Procedural Language Functions, highlighting when to use each based on the complexity of the logic required.

Uploaded by

guldariya299
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

DDL FUNC

🔍 PART 1: Views
✅ What is a View?
●​ A view is like a virtual table based on the result of a SELECT statement.
●​ It doesn't store data — it just shows data from one or more tables.

✅ Why use a View?


●​ To simplify complex queries (especially joins or aggregations).
●​ To improve readability and make reports easier.
●​ To restrict data access (show only specific columns/rows to users).
●​ Great for creating business-friendly versions of raw data.

✅ Key Characteristics
Feature Explanation

Virtual Table Doesn’t hold data; based on a SELECT.

Simplifies Access Hides complex logic (joins, filters).

Read-Only (mostly) Usually can’t insert/update through it unless certain conditions are
met.

No Parameters You can’t pass parameters into a view.

No Logic or Flow No conditions, loops, or variables — just pure SQL.

✅ When NOT to Use


●​ When you need logic or parameters.
●​ When you want to perform inserts/updates with validations.
●​ When performance is critical (views re-run the full query each time).

EXAMPLE: In a university setting, we created a view called department_student_summary to


help department heads easily see how many students are enrolled in each department.
Instead of writing a long SQL query with joins and groupings every time, they can just query
the view like a normal table. It saves time, avoids mistakes, and hides complexity.

1. Updatable Views — What Are They?

What’s an updatable view?

An updatable view is a view that allows you to perform INSERT, UPDATE, and DELETE
operations on the underlying base table via the view itself.

So, instead of going directly to the table, you can modify the data through the view — which
can simplify your queries and add extra layers of abstraction.

🛠️ When does it work?


●​ Simple Views: If the view only uses basic columns from a table without complex
joins, groupings, or calculations, it’s usually updatable.​
●​ Under certain conditions, you can update a view, but it’s often restricted if the view
involves:​

○​ Aggregations (e.g., COUNT, SUM)​

○​ DISTINCT keyword​

○​ Joins​

○​ GROUP BY

❌ When is it not updatable?


●​ Complex Views: If the view involves multiple tables, aggregations, or joins, it typically
won’t be updatable.​

●​ For instance, if your view combines sales data and customer info from two tables,
and you try to update the customer_name directly via the view — it won’t work.

Example of an Updatable View:

You have an employee table:

emp_id full_name salary

101 John 3000

102 Alice 3500

Create a simple view to track employees' salaries:

CREATE VIEW employee_salary AS


SELECT emp_id, full_name, salary
FROM employees;

You can now update the salary via the view:

UPDATE employee_salary
SET salary = 3800
WHERE emp_id = 101;

This works because it’s a simple query.

🔒 2. Limitations of Views
While views are super useful, they come with some limitations:

🚧 Performance:
●​ Views are not always fast, especially for complex queries. They have to re-run the
underlying query every time you access them.
●​ If your view involves large joins or aggregations, it might slow down performance.

🔄 Updatability:
●​ Some views are not updatable (especially complex ones), so you might need to work
directly with the base tables.
🔑 Security:
●​ Views can expose sensitive data. If you're not careful, you might accidentally allow
users to access too much data (like via a SELECT * view).

🔄 Read-only:
●​ Views are read-only if they’re created from multiple tables or contain aggregation
operations. You can’t directly modify the underlying data via them.​

📌 What is a Materialized View?


A materialized view is like a snapshot of a query result that’s saved as a real table.​
Unlike normal views (which run the query every time), materialized views store the data
inside them.

🧠 Think of it like:
“Run this heavy query once, store the result, and use it many times fast.”

📊 Real-Life Use Cases of Materialized Views


🏢 1. Weekly Sales Dashboard (e-commerce)
You join millions of rows across orders, products, customers, etc.

●​ You only need updated data once a day/week


●​ Materialized view helps avoid running complex joins each time someone opens the
dashboard

CREATE MATERIALIZED VIEW weekly_sales_summary AS


SELECT product_id, SUM(total_price) AS total_sales
FROM orders
WHERE order_date >= current_date - INTERVAL '7 days'
GROUP BY product_id;

Use REFRESH MATERIALIZED VIEW weekly_sales_summary; once a week!


🟨 What’s a Query Language Function?
A Query Language Function (usually SQL-language function) can take parameters and return
a table — so it works like a parameterized view.

✅ You can pass input like this:


SELECT * FROM get_employees_by_department('HR');

This is very much like querying a view, but with dynamic filtering thanks to parameters.

✅ So Why Not Call It a Parameterized View?


Because views don’t officially support parameters in SQL standards.

So instead:

●​ We use Query Language Functions


●​ They return table-like results
●​ And feel like "smart views"

👉 That’s why people informally call them parameterized views — but in SQL terms, they’re
functions.

🔍 PART 2: Query Language Functions


✅ What is a Query Language Function?
●​ It’s a user-defined function written purely in SQL.
●​ It allows you to encapsulate (wrap) a query or group of queries.
●​ The function is created using CREATE FUNCTION, and you define what it returns (like
a value or a table).​

✅ Why use it?


●​ To reuse logic: If you run the same query often, put it in a function.
●​ To modularize your SQL code: Break down big logic into manageable pieces.
●​ To accept parameters: Unlike views, functions can accept input to make queries
dynamic.

✅ Key Characteristics
Feature Explanation

SQL-only logic You can only use SQL statements (no IFs, loops, etc.).

Reusable Define once, use many times with different inputs.

Returns values Must have a RETURNS clause — can return a single value (e.g.,
INT) or a table.

Real-time execution Function runs when called, just like a view does.
Can accept You define inputs in the function signature.
parameters

No flow control No IF/ELSE or loops — for that, use procedural functions.

No exception If something goes wrong, error is thrown directly.


handling

🏢 Real-Life Example
🛒 Scenario: E-Commerce Company
You work in an e-commerce company. The business team frequently asks:

“How many orders did a customer place this month?”

🧠 Problem:
Running this query every time with different customer IDs is repetitive.

✅ Solution: SQL Function


You create a function called get_monthly_order_count(customer_id) that returns an integer
count of orders for that customer in the current month.

Now business analysts can call the function like:

SELECT get_monthly_order_count(105);

Instead of writing a full SELECT COUNT(*) FROM orders... query each time.

🗣️ How to Explain in Assessment:


"At an e-commerce company, we used a SQL function called
get_monthly_order_count that takes a customer ID and returns how many orders
they made this month. This made our reporting much easier and more dynamic,
since we didn’t need to write the same SQL logic repeatedly. Unlike views, this
function accepted parameters, which made it more flexible."

so can"t i run if and while loops in sql without function?

ChatGPT сказал:

Great question! The short answer is: No, you can’t run IF or WHILE loops directly in plain
SQL — they only work inside a procedural function or block.

Let me explain clearly 👇


🧾 Basic SQL (outside functions):
Plain SQL is declarative — it just asks for results like:
SELECT * FROM employees WHERE department = 'IT';

But it can’t "think" like:

●​ “If this happens, then do that.”


●​ “Repeat this 5 times.”

There are no IF, WHILE, FOR in normal SQL statements.

✅ Inside Procedural Language (like PL/pgSQL):


You can use IF, WHILE, LOOP, etc. but only inside:

●​ DO blocks (anonymous code)​

●​ FUNCTIONs​

●​ PROCEDUREs​

Example:

DO $$
BEGIN
IF EXISTS (SELECT 1 FROM users WHERE email = '[email protected]') THEN
RAISE NOTICE 'User exists!';
END IF;
END;
$$ LANGUAGE plpgsql;

🎓 Simple Rule to Remember:


Can I use it in plain SQL? Only inside function/procedure?

SELECT, INSERT, UPDATE ✅ Yes everywhere


IF, WHILE, FOR, LOOP ❌ Only inside procedural code
So in short:

If you want logic and control flow like a real program, you need to write it inside
a procedural function.
PART 3. Procedural Language Function — Theory Summary

✅ Definition:
A Procedural Language Function is a user-defined function written using a
programming-style language like PL/pgSQL (in PostgreSQL). It allows you to perform
step-by-step operations, use control flow (like IF, WHILE, LOOP), and handle errors — all
from within the database.

🎯 Purpose:
Used to perform complex business logic that:

●​ Needs multiple steps


●​ Includes conditions (if-else)
●​ Requires loops
●​ Needs error handling​

Plain SQL cannot do this.

🧩 Key Features:
Feature Explanation

Step-by-step logic Runs like a program, one line at a time

Control flow Supports IF, CASE, WHILE, FOR, LOOP, etc.

Error handling Can catch and manage errors using EXCEPTION

Variables You can declare and use variables

Accepts parameters You can pass inputs like numbers, strings, etc.

Returns values Can return a value, row, or table

Uses SQL + logic Combines SQL statements with programming


logic

🏦 Real-Life Example:
Bank Transfer Function

●​ Checks if a sender has enough balance​

●​ Deducts money from sender​

●​ Adds money to receiver​

●​ Logs the transaction​

●​ If anything fails → it cancels the whole operation (safe!)


🔐 Why It's Useful:
●​ Keeps logic inside the database (faster, more secure)​

●​ Ensures data accuracy and safe transactions​

●​ Makes code reusable and easier to manage​

●​ Great for things like payroll, order processing, or inventory checks

🧠 Simple Analogy:
It’s like a recipe you follow step-by-step in the kitchen, including what to do if
you run out of eggs (error handling).

🔑 What does LANGUAGE plpgsql; mean?


This tells PostgreSQL what language the function is written in.

●​ plpgsql stands for Procedural Language/PostgreSQL.​

●​ It's an extension of SQL that supports:​

○​ Variables​

○​ Control flow like IF/ELSE, LOOP, WHILE, etc.​

So by saying LANGUAGE plpgsql;, you're telling the database:

“Hey, this isn’t just plain SQL — it’s SQL with programming logic.”
✅ First — What is DDL?
DDL (Data Definition Language) is the part of SQL used to define and manage the structure
of database objects — not the data itself.

Common DDL commands:

●​ CREATE
●​ ALTER
●​ DROP
●​ TRUNCATE

These affect how the database is structured, not what data is inside.

✅ Why are Views and Functions DDL?


Let’s look at each one:

🧱 Views → CREATE VIEW


When you create a view, you're defining a virtual table — a structure that doesn't hold data
itself, but shows data in a specific shape.

📌 You are defining a new object (a view) in the database — so it's a DDL action.
Example:

CREATE VIEW high_salary_employees AS


SELECT name, salary FROM employees WHERE salary > 60000;

You're not inserting data — you're defining something new.


🔁 Functions (SQL or Procedural) → CREATE FUNCTION
A function is a named, reusable block of logic that performs a task and returns a result.

When you create a function, you're also defining a new object (the function itself), which
becomes part of the database's schema.

📌 Since you're creating something that changes the structure of the database (by adding a
function object), it's DDL.

Example:

CREATE FUNCTION get_bonus(salary NUMERIC) RETURNS NUMERIC AS $$


BEGIN
RETURN salary * 0.10;
END;
$$ LANGUAGE plpgsql;

Again — you’re not inserting, updating, or selecting data — you're defining logic structure.

🎯 Why It Matters
Even though views and functions use SELECT or DML-like logic inside them, the CREATE
action is what classifies them under DDL.

It's not what's inside the function or view — it's the fact that you're defining a named object
in the schema.

🧠 Quick Recap:
Feature Is It DDL? Why?

CREATE
TABLE
✅ Defines a new table structure

CREATE VIEW ✅ Defines a new virtual table

CREATE
FUNCTION
✅ Defines a new logical object

SELECT,
INSERT
❌ These are DML (Data Manipulation) — they deal with data,
not structure
🔍 LANGUAGE SQL vs LANGUAGE plpgsql
Feature LANGUAGE SQL LANGUAGE plpgsql

Simpler logic ✅ Yes ✅ Yes


Loops, IFs, WHILE ❌ Not supported ✅ Yes — fully
procedural

BEGIN...END block Optional / rare Required

Use of OUT, INOUT ✅ Supported (for simple cases) ✅ Fully supported


Return table from
function
✅ Yes (via RETURNS TABLE or
OUT)
✅ Yes
What is the difference between Query Language Functions and Procedural Language
Functions? When would you use each?

Query Language Functions are best when I need to return results from a simple SQL
query, like generating a monthly sales report, getting top customers, or filtering data
based on parameters like dates or product categories. They’re written using
LANGUAGE SQL, and they don’t support loops or conditional logic. I think of them like
"smart, reusable queries" — almost like parameterized views.

On the other hand, Procedural Language Functions (like LANGUAGE plpgsql) are
useful when I need to handle complex business logic — for example, applying bonuses
based on performance, looping through customers to apply updates, or using IF,
WHILE, and exception handling. These functions behave more like mini-programs
inside the database, with full control flow support.

🔹 For example, if I need to return top 10 selling categories in a given quarter — I’d use

🔸
a Query Language Function.​
But if I need to check each employee’s sales and calculate bonuses differently —
I’d use a Procedural Function with IF logic.

In short, I choose based on the complexity of logic. If it's just one SQL query: use SQL
function. If it needs step-by-step logic or loops: go with procedural.

You might also like