Showing posts with label Functions. Show all posts
Showing posts with label Functions. Show all posts

Tuesday, 26 August 2025

Functions & Operators in PostgreSQL: Mathematical Function & Operator | ...


In this video 📺, we explore Mathematical Functions and Operators in PostgreSQL in depth. PostgreSQL provides a wide range of built-in tools that make complex calculations easy to perform directly inside your SQL queries.

We’ll cover everything step by step with examples and demos, including:
✅ Arithmetic operators (+, -, *, /, %, ^)
✅ Absolute value, square root, cube root, power
✅ Rounding, truncation, logarithmic & exponential functions
✅ Factorials, GCD, LCM, and PI
✅ Random number generation and seeding
✅ Trigonometric functions (sin, cos, tan, atan2) in radians & degrees
✅ Hyperbolic functions (sinh, cosh, tanh, etc.)

By the end of this session, you’ll know how to use these functions in real-world cases like financial applications, GIS, scientific computations, and simulations. 🚀

👉 This is part of the PostgreSQL Full Playlist. Don’t forget to check out previous episodes to build a strong foundation!

🔔 Subscribe, like, and share this video to support the channel and stay updated with more PostgreSQL tutorials.

Friday, 22 August 2025

Functions and Operators in PostgreSQL: Comparison Function & Operator | ...



In this video, we’ll dive into Comparison Functions and Operators in PostgreSQL. These are essential for writing precise queries, handling null values, and performing safe comparisons in your database applications.

You’ll learn:

  • Basic comparison operators (<, >, =, <>, !=)

  • Range testing with BETWEEN and NOT BETWEEN

  • Using BETWEEN SYMMETRIC for unordered ranges

  • NULL-safe comparisons with IS DISTINCT FROM and IS NOT DISTINCT FROM

  • Checking for missing data with IS NULL, IS NOT NULL, and alternatives

  • Boolean checks like IS TRUE, IS FALSE, and IS UNKNOWN

  • Row-level null comparisons and their tricky behavior

  • Handy functions like num_nulls() and num_nonnulls() for analyzing null values

We’ll also cover best practices, pitfalls, and performance tips to ensure your queries run efficiently while avoiding common mistakes with null handling and cross-type comparisons.

📌 This is part of the PostgreSQL Full Playlist, so make sure to check out the other videos if you want to master PostgreSQL step by step.

Tuesday, 15 July 2025

Data Types in PostgreSQL: Date/Time/Interval Data Types || PostgreSQL Fu...


Welcome to Episode 49 of the PostgreSQL Full Playlist! In this tutorial, we explore one of the most important areas of database development — Date/Time and Interval Data Types in PostgreSQL.

PostgreSQL provides highly flexible and powerful temporal data types including DATE, TIME, TIMESTAMP, TIMESTAMPTZ, and INTERVAL. Whether you're handling simple dates, calculating durations, or dealing with timezone-aware timestamps, this video will guide you through all the critical concepts with real-world use cases, hands-on SQL examples, and expert-level insights.

You will learn:

  • The difference between TIMESTAMP and TIMESTAMPTZ

  • How to use and format INTERVAL for date arithmetic

  • How time zone conversion works using AT TIME ZONE

  • Date formatting with datestyle and intervalstyle

  • Special constants like now, epoch, today, and yesterday

  • Functions like CURRENT_DATE, DATE_TRUNC, EXTRACT, and more!

💡 This video is perfect for:

  • Students learning databases

  • Backend developers handling temporal data

  • Data engineers dealing with time-series data

  • Anyone preparing for SQL interviews or certifications

👉 Don’t forget to LIKE, SUBSCRIBE, and SHARE if you find this helpful. Drop your questions or feedback in the comments — I’d love to help out!

🔔 Subscribe for more PostgreSQL and Database tutorials.

Friday, 23 May 2025

Select Lists in PostgreSQL || Queries in PostgreSQL || Best PostgreSQL T...


🔍 Welcome to the Ultimate PostgreSQL Tutorial Series!
In this video (#37), we dive deep into one of the most crucial parts of any SQL query—the SELECT list. Whether you're a beginner or brushing up your database skills, this tutorial will guide you through the many ways PostgreSQL lets you customize the data you retrieve.

👨‍💻 What You'll Learn:

  • How to select all or specific columns

  • Using table aliases for cleaner queries

  • Creating computed columns with expressions

  • Renaming outputs with column aliases (AS)

  • Eliminating duplicates with DISTINCT and DISTINCT ON

  • Leveraging subqueries, functions, and CASE expressions

  • Working with JSON, arrays, and aggregate functions

  • Using LIMIT, OFFSET, and even SELECT without a FROM clause

  • Advanced techniques like CTEs (Common Table Expressions)

✨ With practical examples, best practices, and performance tips, this tutorial is your go-to guide for mastering SELECT lists in PostgreSQL!

🧠 Next Video: Combining Queries in PostgreSQL – UNION, INTERSECT, EXCEPT
👍 Don't forget to like, subscribe, and turn on notifications for more powerful PostgreSQL lessons.

Friday, 21 February 2025

How To Track Dependent Objects In PostgreSQL || Best PostgreSQL Tutorial...


Managing dependencies in PostgreSQL is crucial for maintaining database integrity. In this tutorial, we explore how PostgreSQL tracks dependent objects and prevents accidental deletions. 🔹 Understanding Dependency Tracking PostgreSQL ensures that if an object (like a table, function, or type) has dependencies, it cannot be dropped unless explicitly handled. This mechanism prevents orphaned objects and data inconsistencies. 🔹 Foreign Key Dependency Example Consider a products table and an orders table where orders.product_no references products.product_id. If we attempt to drop the products table, PostgreSQL throws an error, warning us about the foreign key constraint. 🔹 Using CASCADE and RESTRICT CASCADE: Automatically removes all dependent objects when dropping a parent object. RESTRICT: Prevents dropping an object if dependencies exist, ensuring safe deletion. 🔹 Function and Type Dependencies Functions can depend on tables and types. PostgreSQL tracks dependencies for types but may not track tables unless the function is written in a SQL-standard format using BEGIN ATOMIC. Dropping a type will force PostgreSQL to remove dependent functions. 🔹 Best Practices ✅ Always check dependencies before dropping objects. ✅ Use CASCADE with caution to avoid unintended deletions. ✅ Write SQL-standard functions if table dependencies need tracking. Watch the full video to see practical demonstrations and error-handling strategies in PostgreSQL! 🚀 📌 Next Up: Data Manipulation in PostgreSQL – Inserting Data 📢 Subscribe for more PostgreSQL tutorials! 👍

Monday, 13 May 2024

Dynamic SQL In PostgreSQL || Use Cases And Usage Of Dynamic SQL With Exa...



Dynamic SQL in PostgreSQL | Use Cases and Examples Explained in pgAdmin

In this video, we'll dive into the world of dynamic SQL in PostgreSQL using pgAdmin, exploring various use cases and providing detailed examples to enhance your understanding. Dynamic SQL allows you to construct and execute SQL statements at runtime, offering flexibility and power in database management and manipulation. Here's what we'll cover:

  1. Run-Time DDL Example

    • Creating a sample table and a stored procedure to add columns dynamically.
    • Example: Adding a new column email to the employees table.
  2. Run-Time SCL (Session Control)

    • Setting session variables and roles dynamically.
    • Examples: Setting the session timezone and changing roles within a session.
  3. Dynamic Columns with Conditions

    • Filtering data dynamically based on various conditions.
    • Example: Filtering employees by department using a dynamic WHERE clause.
  4. Dynamic SELECT INTO Queries

    • Using dynamic SQL to fetch specific column values.
    • Examples: Fetching salaries based on employee names and dynamically constructing queries with multiple column retrieval.
  5. OPEN Refcursor RETURN Query

    • Executing dynamic queries and returning results using refcursors.
    • Example: Returning all employee details using a dynamic query.
  6. Dynamic Multiple-Row Query with Open Loop

    • Creating and executing queries that return multiple rows using loops.
    • Example: Fetching all employees from a specific department.
  7. Dynamic DML (Data Manipulation Language)

    • Updating table data dynamically.
    • Example: Updating the salary of an employee based on their ID.

By the end of this video, you'll have a solid grasp of how to leverage dynamic SQL in PostgreSQL to perform a wide range of database operations efficiently. Whether you're adding new columns on the fly, setting session parameters, or filtering and updating data dynamically, these examples will provide you with the tools and knowledge to implement dynamic SQL in your own projects.

PostgreSQL, dynamic SQL, dynamic SQL examples, pgAdmin, dynamic SQL usage, PostgreSQL tutorial, advanced SQL, SQL scripting, database management, SQL use cases, dynamic queries

Don't forget to like, share, and subscribe for more in-depth tutorials on PostgreSQL and other database technologies!


Run Time DDL Example
-------------------------------
-- Create a sample table
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(100),
    salary NUMERIC(10, 2)
);

-- Sample stored procedure for dynamic DDL command
CREATE OR REPLACE FUNCTION alter_table(column_name VARCHAR, data_type VARCHAR) RETURNS VOID AS $$
BEGIN
    EXECUTE format('ALTER TABLE employees ADD COLUMN %I %s', column_name, data_type);
END;
$$ LANGUAGE plpgsql;

-- Call the stored procedure to add a new column dynamically
SELECT alter_table('email', 'VARCHAR(255)');


Run Time SCL, Session Control
------------------------------

-- Create a custom function to set session variables
CREATE OR REPLACE FUNCTION set_session_variable(var_name TEXT, var_value TEXT) RETURNS VOID AS $$
BEGIN
    EXECUTE format('SET SESSION %s TO %L', var_name, var_value);
END;
$$ LANGUAGE plpgsql;

-- Create a custom function to set session role
CREATE OR REPLACE FUNCTION set_session_role(role_name TEXT) RETURNS VOID AS $$
BEGIN
    EXECUTE format('SET ROLE %s', role_name);
END;
$$ LANGUAGE plpgsql;

select now();

-- Set a session variable
SELECT set_session_variable('timezone', 'UTC');

select now();

-- Set session role
SELECT set_session_role('dvdrental');

SELECT set_session_role('postgres');




Dynamic Columns at run time + Where Condition
------------------------------------------------

Drop table employees;

-- Create a sample table
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(100),
    salary NUMERIC(10, 2)
);

-- Insert some sample data
INSERT INTO employees (name, department, salary) VALUES 
('John Doe', 'HR', 50000.00),
('Jane Smith', 'IT', 60000.00),
('Alice Johnson', 'Finance', 55000.00);

-- Create a stored procedure for dynamic WHERE condition
CREATE OR REPLACE FUNCTION filter_employees(attr_name TEXT, attr_value TEXT) RETURNS SETOF employees AS $$
BEGIN
    RETURN QUERY EXECUTE format('SELECT * FROM employees WHERE %I = %L', attr_name, attr_value);
END;
$$ LANGUAGE plpgsql;

-- Filter employees dynamically by department
SELECT * FROM filter_employees('department', 'IT');




Select INTO query
--------------------

-- Create a stored procedure for dynamic WHERE condition
CREATE OR REPLACE FUNCTION filter_employees2(attr_name TEXT, attr_value TEXT) RETURNS numeric AS $$
DECLARE
lv_salary numeric(10,0);
BEGIN
EXECUTE format('SELECT salary FROM employees WHERE %I = %L', attr_name, attr_value) INTO lv_salary;
return lv_salary;
END;
$$ LANGUAGE plpgsql;

-- Filter employees dynamically by department
SELECT * FROM filter_employees2('name', 'John Doe');


Select INTO Using query
-------------------------

-- Create a stored procedure for dynamic WHERE condition
CREATE OR REPLACE FUNCTION filter_employees3(attr_name TEXT, attr_value TEXT) RETURNS char AS $$
DECLARE
lv_salary numeric(10,0);
lv_name char(30);
BEGIN
EXECUTE 'SELECT salary, name FROM employees WHERE '||$1||' = '||$2||''
USING attr_name, attr_value INTO lv_salary,lv_name;
   
   return lv_name||' Having Salary: '||lv_salary;
END;
$$ LANGUAGE plpgsql;

-- Filter employees dynamically by department
SELECT * FROM filter_employees3('id', '1');



OPEN Refcursor RETURN Query
--------------------------

CREATE OR REPLACE FUNCTION get_employee_details(output_refcursor refcursor) RETURNS refcursor AS $$
DECLARE
    dynamic_query TEXT;
BEGIN
    dynamic_query := 'SELECT * FROM employees'; -- Your dynamic query here

    OPEN output_refcursor FOR EXECUTE dynamic_query;
    RETURN output_refcursor;
END;
$$ LANGUAGE plpgsql;

select get_employee_details('output_refcursor');
fetch all in output_refcursor;




Dynamic Multiple-Row Query, Open loop
-------------------------------------

Drop table employees;

-- Create a sample table
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(100)
);

-- Insert some sample data
INSERT INTO employees (name, department) VALUES 
('John Doe', 'HR'),
('Jane Smith', 'IT'),
('Alice Johnson', 'Finance');

-- Create a function to dynamically execute query and return multiple rows
CREATE OR REPLACE FUNCTION dynamic_query(condition TEXT) RETURNS TABLE (id INT, name TEXT, department TEXT) AS $$
DECLARE
    emp_record employees%ROWTYPE;
    query TEXT;
BEGIN
    query := 'SELECT * FROM employees WHERE ' || condition;
    FOR emp_record IN EXECUTE query LOOP
        id := emp_record.id;
        name := emp_record.name;
        department := emp_record.department;
        RETURN NEXT;
    END LOOP;
    RETURN;
END;
$$ LANGUAGE plpgsql;

SELECT * FROM dynamic_query('department = ''IT''');




DML
----

Drop table employees;

-- Create a sample table
CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(100),
    salary NUMERIC(10, 2)
);

-- Insert some sample data
INSERT INTO employees (name, department, salary) VALUES 
('John Doe', 'HR', 50000.00),
('Jane Smith', 'IT', 60000.00),
('Alice Johnson', 'Finance', 55000.00);

CREATE OR REPLACE FUNCTION update_column_value(table_name TEXT, column_name TEXT, column_value TEXT, condition_column TEXT, condition_value TEXT) RETURNS VOID AS $$
DECLARE
    sql_statement TEXT;
BEGIN
    sql_statement := format('UPDATE %I SET %I = %L WHERE %I = %L', table_name, column_name, column_value, condition_column, condition_value);
    EXECUTE sql_statement;
END;
$$ LANGUAGE plpgsql;


SELECT update_column_value('employees', 'salary', '58700', 'id', '1');

select * from employees;