<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Swapniln on Medium]]></title>
        <description><![CDATA[Stories by Swapniln on Medium]]></description>
        <link>https://medium.com/@swapniln1612?source=rss-d41a4531d729------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YTfefOB_o4gRT-4E</url>
            <title>Stories by Swapniln on Medium</title>
            <link>https://medium.com/@swapniln1612?source=rss-d41a4531d729------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:57:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swapniln1612/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SQL Meets Logic: A Practical PL/SQL Guide]]></title>
            <link>https://medium.com/@swapniln1612/sql-meets-logic-a-practical-pl-sql-guide-2110b70ab661?source=rss-d41a4531d729------2</link>
            <guid isPermaLink="false">https://medium.com/p/2110b70ab661</guid>
            <category><![CDATA[oracle-pl-sql]]></category>
            <category><![CDATA[plsql-triggers]]></category>
            <dc:creator><![CDATA[Swapniln]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 05:29:47 GMT</pubDate>
            <atom:updated>2026-10-17T05:29:47.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you are building an employee management system. You need to retrieve employee details, calculate salaries, update records, and handle errors when an employee does not exist.</p><p>SQL helps you work with data, but what if you need conditions, loops, variables, and error handling along with SQL queries?</p><p>This is where PL/SQL comes in.</p><p>In this article, we will learn the fundamentals of PL/SQL through simple explanations and practical examples.</p><p>## 1. What Is PL/SQL?</p><p>PL/SQL stands for Procedural Language extensions to SQL. It is Oracle’s programming language that combines SQL with programming features such as variables, conditions, loops, procedures, functions, and exception handling.</p><p>SQL executes database operations, while PL/SQL allows you to combine multiple operations into a program.</p><p>### SQL vs. PL/SQL</p><p>| SQL | PL/SQL |<br>| — -| — -|<br>| Works with database data | Combines SQL with programming logic |<br>| Supports conditions within queries | Supports `IF`, `ELSIF`, and `CASE` |<br>| Executes SQL statements | Executes blocks of statements |<br>| Supports database objects | Supports procedures, functions, and packages |</p><p>Remember: SQL works with data. PL/SQL adds programming logic.</p><p>## 2. PL/SQL Block Structure</p><p>A PL/SQL program is organized into blocks.</p><p>A block contains these sections:</p><p>```sql<br>DECLARE<br> — Variable declarations<br>BEGIN<br> — Executable statements<br>EXCEPTION<br> — Error handling<br>END;<br>/<br>```</p><p>`DECLARE` and `EXCEPTION` are optional. `BEGIN` and `END` are mandatory. The `/` is a client command commonly used to execute a block in SQL*Plus and SQL Developer.</p><p>### Example: Display a message</p><p>```sql<br>SET SERVEROUTPUT ON;</p><p>BEGIN<br> DBMS_OUTPUT.PUT_LINE(‘Welcome to PL/SQL’);<br>END;<br>/<br>```</p><p>Output:</p><p>```text<br>Welcome to PL/SQL<br>```</p><p>`DBMS_OUTPUT.PUT_LINE` displays a message when server output is enabled.</p><p>## 3. Variables and Data Types</p><p>A variable stores a value that a program can use or modify.</p><p>Common PL/SQL data types include:</p><p>| Data type | Purpose |<br>| — -| — -|<br>| `NUMBER` | Numeric values |<br>| `VARCHAR2(n)` | Variable-length text |<br>| `CHAR(n)` | Fixed-length text |<br>| `DATE` | Date and time values |<br>| `BOOLEAN` | `TRUE`, `FALSE`, or `NULL` in PL/SQL |</p><p>### Example: Declare variables</p><p>```sql<br>DECLARE<br> v_name VARCHAR2(30) := ‘SMITH’;<br> v_salary NUMBER := 30000;<br>BEGIN<br> DBMS_OUTPUT.PUT_LINE(v_name);<br> DBMS_OUTPUT.PUT_LINE(v_salary);<br>END;<br>/<br>```</p><p>Output:</p><p>```text<br>SMITH<br>30000<br>```</p><p>The `:=` operator assigns a value to a variable.</p><p>### Using `%TYPE` and `%ROWTYPE`</p><p>`%TYPE` uses the data type of an existing column, while `%ROWTYPE` creates a record that can hold an entire row.</p><p>Example using `%TYPE`:</p><p>```sql<br>DECLARE<br> v_salary emp.sal%TYPE;<br>BEGIN<br> SELECT sal INTO v_salary<br> FROM emp<br> WHERE empno = 7369;</p><p>DBMS_OUTPUT.PUT_LINE(v_salary);<br>END;<br>/<br>```</p><p>Here, `v_salary` uses the data type defined for the `sal` column.</p><p>These examples assume the traditional Oracle `EMP` table exists.</p><p>## 4. Conditional Statements</p><p>Conditional statements allow a program to make decisions based on a condition.</p><p>PL/SQL supports `IF`, `IF-ELSE`, `ELSIF`, and `CASE`.</p><p>### Example: IF-ELSE</p><p>```sql<br>DECLARE<br> v_salary NUMBER := 40000;<br>BEGIN<br> IF v_salary &gt;= 30000 THEN<br> DBMS_OUTPUT.PUT_LINE(‘Eligible’);<br> ELSE<br> DBMS_OUTPUT.PUT_LINE(‘Not eligible’);<br> END IF;<br>END;<br>/<br>```</p><p>Output:</p><p>```text<br>Eligible<br>```</p><p>If the condition is true, the first message is displayed. Otherwise, the `ELSE` block executes.</p><p>## 5. Loops in PL/SQL</p><p>Loops execute statements repeatedly. PL/SQL provides `FOR LOOP`, `WHILE LOOP`, and simple `LOOP`.</p><p>### Example: FOR LOOP</p><p>```sql<br>BEGIN<br> FOR i IN 1..3 LOOP<br> DBMS_OUTPUT.PUT_LINE(i);<br> END LOOP;<br>END;<br>/<br>```</p><p>Output:</p><p>```text<br>1<br>2<br>3<br>```</p><p>A `FOR LOOP` is useful when the number of iterations is known.</p><p>## 6. SQL Statements Inside PL/SQL</p><p>PL/SQL allows you to execute SQL statements such as `SELECT`, `INSERT`, `UPDATE`, and `DELETE` inside a program.</p><p>### Example: SELECT INTO</p><p>```sql<br>DECLARE<br> v_name emp.ename%TYPE;<br>BEGIN<br> SELECT ename INTO v_name<br> FROM emp<br> WHERE empno = 7369;</p><p>DBMS_OUTPUT.PUT_LINE(v_name);<br>END;<br>/<br>```</p><p>Output:</p><p>```text<br>SMITH<br>```</p><p>`SELECT INTO` retrieves a query result into a variable. It expects exactly one row.</p><p>- No rows: Oracle raises `NO_DATA_FOUND`.<br>- Multiple rows: Oracle raises `TOO_MANY_ROWS`.</p><p>### Example: UPDATE</p><p>```sql<br>BEGIN<br> UPDATE emp<br> SET sal = sal + 1000<br> WHERE empno = 7369;</p><p>DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ‘ row(s) updated’);<br>END;<br>/<br>```</p><p>`SQL%ROWCOUNT` returns the number of rows affected by the most recent SQL statement.</p><p>## 7. Cursors</p><p>A cursor provides a way to process query results.</p><p>There are two main types:</p><p>- Implicit cursor: Managed automatically by Oracle.<br>- Explicit cursor: Declared and controlled by the developer.</p><p>### Example: Cursor FOR LOOP</p><p>```sql<br>BEGIN<br> FOR r IN (SELECT ename, sal FROM emp) LOOP<br> DBMS_OUTPUT.PUT_LINE(r.ename || ‘ ‘ || r.sal);<br> END LOOP;<br>END;<br>/<br>```</p><p>This program displays each employee’s name and salary.</p><p>The cursor `FOR LOOP` automatically manages opening, fetching, and closing the cursor.</p><p>## 8. Procedures and Functions</p><p>Procedures and functions are reusable PL/SQL program units stored in the database.</p><p>A procedure performs an operation, while a function returns a value.</p><p>### Example: Stored procedure</p><p>```sql<br>CREATE OR REPLACE PROCEDURE get_emp_name (<br> p_empno IN emp.empno%TYPE<br>)<br>AS<br> v_name emp.ename%TYPE;<br>BEGIN<br> SELECT ename INTO v_name<br> FROM emp<br> WHERE empno = p_empno;</p><p>DBMS_OUTPUT.PUT_LINE(v_name);<br>END;<br>/<br>```</p><p>Execute the procedure:</p><p>```sql<br>SET SERVEROUTPUT ON;</p><p>EXEC get_emp_name(7369);<br>```</p><p>Output:</p><p>```text<br>SMITH<br>```</p><p>The procedure accepts an employee number and displays the corresponding name.</p><p>### Example: Function</p><p>```sql<br>CREATE OR REPLACE FUNCTION annual_salary (<br> p_salary IN NUMBER<br>)<br>RETURN NUMBER<br>AS<br>BEGIN<br> RETURN p_salary * 12;<br>END;<br>/<br>```</p><p>Call the function:</p><p>```sql<br>SELECT annual_salary(30000) AS annual_salary<br>FROM dual;<br>```</p><p>Output:</p><p>```text<br>360000<br>```</p><p>The function calculates annual salary from monthly salary and returns the result.</p><p>## 9. Exception Handling</p><p>An exception is an error or exceptional condition that interrupts normal execution.</p><p>Common predefined exceptions include:</p><p>| Exception | Meaning |<br>| — -| — -|<br>| `NO_DATA_FOUND` | A query returned no rows |<br>| `TOO_MANY_ROWS` | A single-row query returned multiple rows |<br>| `ZERO_DIVIDE` | Division by zero |<br>| `VALUE_ERROR` | A value or conversion error |</p><p>### Example: Handle division by zero</p><p>```sql<br>DECLARE<br> v_num NUMBER := 100;<br> v_den NUMBER := 0;<br> v_result NUMBER;<br>BEGIN<br> v_result := v_num / v_den;</p><p>DBMS_OUTPUT.PUT_LINE(v_result);</p><p>EXCEPTION<br> WHEN ZERO_DIVIDE THEN<br> DBMS_OUTPUT.PUT_LINE(‘Cannot divide by zero’);<br>END;<br>/<br>```</p><p>Output:</p><p>```text<br>Cannot divide by zero<br>```</p><p>The `EXCEPTION` section handles the error and displays a meaningful message.</p><p>## 10. Triggers and Packages</p><p>A trigger executes automatically when a specified database event occurs. Triggers can run before or after database operations and can be defined at the row or statement level.</p><p>### Example: Trigger</p><p>```sql<br>CREATE OR REPLACE TRIGGER trg_emp_insert<br>AFTER INSERT ON emp<br>BEGIN<br> DBMS_OUTPUT.PUT_LINE(‘Employee inserted’);<br>END;<br>/<br>```</p><p>This statement-level trigger runs after an insert statement on the `EMP` table. For production auditing, use an appropriate logging or audit mechanism rather than relying on `DBMS_OUTPUT`.</p><p>A package groups related PL/SQL program units. It contains a specification, which declares public elements, and a body, which contains their implementations.</p><p>For example, an employee management package can group procedures for updating salaries and functions for calculating bonuses.</p><p>## 11. Advanced PL/SQL Concepts</p><p>After learning the fundamentals, explore these concepts:</p><p>- **Records and collections:** Store related fields or multiple values.<br>- **Dynamic SQL:** Execute SQL constructed at runtime using `EXECUTE IMMEDIATE`.<br>- **BULK COLLECT:** Fetch multiple rows into collections.<br>- **FORALL:** Perform bulk DML operations using collection values.<br>- **Performance optimization:** Reduce unnecessary processing.<br>- **Debugging:** Identify and resolve errors using suitable tools.</p><p>## 12. Best Practices</p><p>1. Use `SELECT INTO` when one row is expected.<br>2. Use cursors when processing multiple rows.<br>3. Handle exceptions properly.<br>4. Use `%TYPE` and `%ROWTYPE` to align declarations with database definitions.<br>5. Prefer set-based SQL when it can replace unnecessary loops.<br>6. Use bind variables with dynamic SQL.<br>7. Manage transactions carefully.<br>8. Test invalid inputs and error conditions.</p><p>## Conclusion</p><p>PL/SQL extends SQL with programming logic, helping developers build reusable and maintainable database programs.</p><p>You have learned the basics of block structure, variables, conditions, loops, SQL statements, cursors, procedures, functions, exception handling, triggers, and packages.</p><p>To practise, build a simple employee management project using Oracle Database. Start with basic queries, then add procedures, functions, and exception handling.</p><p>Run the examples, modify the values, and observe the results. Practical experience is the best way to strengthen your PL/SQL skills.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2110b70ab661" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>