← Back to PostgreSQL Course | Chapter 10: Advanced Features | Lesson 3 of 7

Stored Procedures क्या हैं

Stored procedures और functions database के अंदर reusable logic store करते हैं, PL/pgSQL या दूसरी languages में लिखे गए।

In this page:

  1. Stored Procedures
Syntax
sql
CREATE FUNCTION function_name(param type) RETURNS type AS $$
BEGIN
  RETURN expression;
END;
$$ LANGUAGE plpgsql;

CREATE PROCEDURE procedure_name(param type) AS $$
BEGIN
  -- statements
END;
$$ LANGUAGE plpgsql;
CALL procedure_name(value);

Stored Procedures

CREATE FUNCTION एक value return करता है और queries के अंदर इस्तेमाल हो सकता है, जबकि CREATE PROCEDURE (PostgreSQL 11 और बाद में) CALL से invoke होता है और transactions control कर सकता है।

PL/pgSQL variables, IF, loops, और exceptions add करता है। इन्हें data के करीब data-heavy logic के लिए इस्तेमाल करें, लेकिन business logic testable रखें।

Note: Functions queries में इस्तेमाल होते हैं; procedures CALL से चलाए जाते हैं।

उदाहरण: Stored procedures

bash
shop=# CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2) RETURNS numeric
shop-# LANGUAGE sql IMMUTABLE AS $$ SELECT round(price * (1 + rate), 2) $$;
shop=# SELECT add_tax(100), add_tax(100, 0.1);
 add_tax | add_tax
---------+---------
  120.00 |  110.00
shop=# CREATE PROCEDURE archive_old_orders(cutoff date) LANGUAGE plpgsql AS $$
shop$# BEGIN
shop$#   INSERT INTO orders_archive SELECT * FROM orders WHERE created_at < cutoff;
shop$#   DELETE FROM orders WHERE created_at < cutoff;
shop$# END $$;
shop=# CALL archive_old_orders('2023-01-01');
CALL

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. सारा business logic database में डालना
  2. variables declare करना भूल जाना
  3. functions और procedures confuse करना
चैप्टर सारांश
  • FUNCTION एक value return करता है
  • PROCEDURE CALL से चलता है
  • PL/pgSQL control flow add करता है
  • Logic testable रखें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.