Table-Valued Functions ua-cam.com/video/9aXD69xBvMs/v-deo.html How to write Scalar Function ua-cam.com/video/2DtPEXjnxs4/v-deo.html Use ENUMS in a function ua-cam.com/video/_B-ctj7zPno/v-deo.html Dynamic Function to ALTER TABLE ua-cam.com/video/iwsMjLtaxaY/v-deo.html Validate Email Address ua-cam.com/video/x5w-TIh3reI/v-deo.html Convert IP->BigInt, BigInt->IP ua-cam.com/video/SVlWmjM4sWk/v-deo.html Return SETOF-json ua-cam.com/video/NAUZW-_hf7I/v-deo.html Function to Generate XML ua-cam.com/video/nCC1OyZs-PE/v-deo.html
Top notch tutorial. I don't usually create functions in Postgres because I used to find it daunting. Now, there's a need to. Declaring variables in T-SQL is so much easier. By far the best short course I've found. Thank you for helping us out!
@@SoftwareNuggets just if you can I would like to see more implementation of This function in solving more complex/ real world problem Also A Question: Can I use This user defined function to create a new column in the table
@@TheGladiator123 watch these video's I created using the function. I think you'll be impressed, and you'll become the master! --deck of cards (great skill to learn) ua-cam.com/video/7U129er3MYQ/v-deo.html --table valued function ua-cam.com/video/9aXD69xBvMs/v-deo.html --insert stored procedure ua-cam.com/video/jOyYhwxMGpg/v-deo.html --cursor in a function ua-cam.com/video/o4blx6Ij5S8/v-deo.html --how to write a scalar function ua-cam.com/video/2DtPEXjnxs4/v-deo.html --return a rowtype ua-cam.com/video/hOe3bi_nUYA/v-deo.html --convert ip address to big int ua-cam.com/video/SVlWmjM4sWk/v-deo.html
@@TheGladiator123 here is a function to allow you to add a column to a table. CREATE OR REPLACE FUNCTION fn_add_column_to_table(table_name VARCHAR, column_name VARCHAR, the_data_type VARCHAR, size INT) RETURNS VARCHAR AS $$ BEGIN IF size IS NOT NULL THEN EXECUTE format('ALTER TABLE %I ADD COLUMN %I %s(%s)', table_name, column_name, the_data_type, size); ELSE EXECUTE format('ALTER TABLE %I ADD COLUMN %I %s', table_name, column_name, the_data_type); END IF; RETURN 'Column added successfully'; END; $$ LANGUAGE plpgsql;
@@SoftwareNuggets hey king Just Your Opinion I wa trying to implement what I learned From You But got Stucked At This edge Case Where I let The User pass an arraay OF words To a Colum with The Type VARCHAR(225) I still Got errors and I can't change The Column Defination
Template Code for creating SQL Function create or replace function func_name(fieldName datatype) returns as $$ begin
end; $$ language plpgsql; --parameter type{in*|out|inout|VARIADIC**} *default **variable number of arguments create or replace function func_name({parameter type} fieldName datatype) as $$ begin
end; $$ language plpgsql; if then
elsif then
else
end if; create or replace function fn(field datatype) returns table ( field_name1 integer, field_name2 character varying(60), field_name3 varchar ) as $$ begin -- table alias is mandatory, or use tablename as alias RETURN QUERY select alias.field1, alias.field2, alias.field3 from table alias where alias.field1 = inputParameter;
at 12:15, my intro to the Range Type will be available. I hope to have Part 2, done tomorrow to discuss Overlapping. Please share you comments after you view this video if you have time.
Here is a few video that will teach you about postgresql functions: Please check out my postgresql Playlist and Postgresql Shorts: Table-Valued Function in PostgreSQL: How to write and consume. ua-cam.com/video/9aXD69xBvMs/v-deo.html PostgreSQL Function to Convert an IP Address into a Big Int, and from a BIG Int to an IP Address. ua-cam.com/video/SVlWmjM4sWk/v-deo.html PostgreSQL - Use Function to Generate XML from table data using XMLForest, XMLElement and XLMAgg. ua-cam.com/video/nCC1OyZs-PE/v-deo.html PostgreSQL - Write a Function that uses RETURNS SETOF json. ua-cam.com/video/NAUZW-_hf7I/v-deo.html PostgreSql Enum: A Beginner's guide to Implement and Use ENUMS in a function. ua-cam.com/video/_B-ctj7zPno/v-deo.html PostgreSQL - Create Function, use rowtype and return json object ua-cam.com/video/hOe3bi_nUYA/v-deo.html PostgreSQL: A table-valued function to Split Full Names into individual fields. ua-cam.com/video/G77v_FFo99A/v-deo.html PostgreSQL: Scalar Function. How to write and use a SQL Scalar function. ua-cam.com/video/2DtPEXjnxs4/v-deo.html
Can you use postgresql functions with NodeJs? Why are there no tutorials about how to do that? Could you pls make a tutorial to demonstrate how to do that?
Hey @LekkyDev, I will have a video out tonight, however, I could just upload the source to this problem to my github account earlier if you'd like. Please let me know. If no response, I'll just publish video ASAP.
@@SoftwareNuggets That would be great if you could upload the source but videos are always better because you get to see the build up as well. I really struggle to find any tutorial about plpgsql with nodejs. Thanks for reaching back and looking forward to the source and the video.
Hey there, god bless your efforts. I am still learning about sql by my own and having today a simple question. I learned that Processes (also known as “procedures”) may take values and give out parameters. Are processes opposite of a function? Is there any related functions used to execute a process? Thanks..
@@SoftwareNuggets Hello man, very clear and to the point, but still left with a major enquiry. You said that " functions are read-only, they can only get data" and then you said that "Functions can select data, update data, delete data". Are these two statements conflicting because I learned recently that we can not use Insert/Update/Delete statements with SQL Server functions.
Hey Hasan, i deleted all my messages, just so that I can give you ONE clear message about the difference between a Function and Stored Procedure. The main functional difference between a function and a stored procedure is: a function returns a result, whereas a stored procedure does not. Functions normally use the RETURNS keyword. you can return a single data type: varchar, integer, numeric, etc. Function can also return a TABLE(see video at 16:29), we can use tables for result queries. However, at (11:51), I write a function that DOES NOT, have a return value, but used the INOUT parameter type. In stored procedure, they can also have return values, but limited. [If you want a QUERY RESULT] use a function. procedure are NOT intended to return result sets. -- other databases behave differently - when you are searching for a feature, make sure the content is about "PostgreSQL" I hope this clears up your question.
very helpful and to the point, when dealing with tables, What if I need to save the result of the query in a variable, say the query returns only one value I need to convert this from msAccess VBA Holiday_start = DLookup("[Start_date]", "Public_att_holiday", "[Start_date] = #" & Format(DateCnt, "yyyy/mm/dd") & "#") where Start_date is a field in the Public_att_holiday table which I need to compare with DateCnt and return the start_date Value from the table if exists and save to Holiday_start Variable
Hey @adnanberki3869 , please let me know if this is what you are looking for. create or replace function DLookup(DateCnt date) returns date as $$ declare lookupValue date; begin select show.date_premiered into lookupValue from tv_show_v2 as show where show.date_premiered = DateCnt limit 1; return lookupValue; end; $$ language plpgsql; select DLookup('1969-10-26')
@@SoftwareNuggets Thank you for care, yes it gave me good idea of how to fix some issues, I still have some problems since I'm new to coding in postgresql, Thank you again for your time.
Hey @abdulrehmanjaved-rt8jq, Let me start of by showing you a very simple function that uses the INOUT clause: CREATE OR REPLACE FUNCTION update_value(INOUT num_param INT) AS $$ BEGIN num_param := num_param + 10; -- Increase the value by 10 END; $$ LANGUAGE plpgsql; -- NOTICE there is NOT a return clause on that function. --INOUT means, you send a value into that function (the IN) part, and (the out) part is available to the caller Here is how you call: SELECT * FROM update_value(5) AS result; notice the output of the call: num_param equals 15 Your question was, why do we use this. If you want to call a function, and want to set the behavior of a column to be both input and output, then use INOUT. CREATE TABLE IF NOT EXISTS orders ( id SERIAL PRIMARY KEY, total DECIMAL(10, 2) ); CREATE TABLE IF NOT EXISTS order_items ( id SERIAL PRIMARY KEY, order_id INT REFERENCES orders(id), price DECIMAL(10, 2), quantity INT ); -- Insert sample data INSERT INTO orders (id) VALUES (1), (2); INSERT INTO order_items (order_id, price, quantity) VALUES (1, 10.00, 2), (1, 15.50, 1), (2, 5.75, 3), (2, 20.00, 1); DROP FUNCTION calculate_total_cost(integer) CREATE OR REPLACE FUNCTION calculate_total_cost(inout order_id INT, OUT total_cost DECIMAL) AS $$ BEGIN SELECT SUM(price * quantity) INTO total_cost FROM order_items WHERE order_items.order_id = calculate_total_cost.order_id; -- Update the order with the calculated total UPDATE orders SET total = total_cost WHERE id = order_id; END; $$ LANGUAGE plpgsql; SELECT * FROM calculate_total_cost(1); in the function calculate_total_cost, change order_id from INOUT to IN; run this sql statement: SELECT * FROM calculate_total_cost(1); compare the return columns from the first function code, to the "change INOUT to IN" code results. Hope this helps. Scott
Hey so this is how the book "SQL for Data Analytics : Perform Fast and Efficient Data Analysis with the Power of SQL" teaches how to code the function equivalent. Bro this is soooo weird. CREATE OR REPLACE FUNCTION fn_mid(VARCHAR, INTEGER, INTEGER) RETURNS VARCHAR AS $new_substring$ DECLARE new_substring VARCHAR; BEGIN RETURN SUBSTRING($1, $2, $3); END; $new_substring$ LANGUAGE PLPGSQL;
Table-Valued Functions ua-cam.com/video/9aXD69xBvMs/v-deo.html
How to write Scalar Function ua-cam.com/video/2DtPEXjnxs4/v-deo.html
Use ENUMS in a function ua-cam.com/video/_B-ctj7zPno/v-deo.html
Dynamic Function to ALTER TABLE ua-cam.com/video/iwsMjLtaxaY/v-deo.html
Validate Email Address ua-cam.com/video/x5w-TIh3reI/v-deo.html
Convert IP->BigInt, BigInt->IP ua-cam.com/video/SVlWmjM4sWk/v-deo.html
Return SETOF-json ua-cam.com/video/NAUZW-_hf7I/v-deo.html
Function to Generate XML ua-cam.com/video/nCC1OyZs-PE/v-deo.html
What a tutorial man, literally u r an ironman with full fledged knowledge
Thanks the taking the time to leave this comment. Much appreciated.
Top notch tutorial. I don't usually create functions in Postgres because I used to find it daunting. Now, there's a need to.
Declaring variables in T-SQL is so much easier.
By far the best short course I've found. Thank you for helping us out!
Hey Sameer, glad to hear this video was helpful. I appreciate your kind words. Best of luck implementing a great solution.
very informative and easy to understand teaching style.
Hey @khizerhayyat549, thanks for the comment, much appreciated.
The best tutorial about this I have seen, thanks for that
Much appreciated
Very easy to understand and very helpful. Thank you!
Glad to hear this video was helpful. Appreciate you leaving a comment.
One of the best tutorial for function which can be practiced via open source application ❤❤
Thank you
Amazing lecture. Thanks Software Nuggets!
Much appreciated!
Very well explained. covered so many thing in such a easy way.
Hey @NirojMeshram, much appreciated.
Very useful and informative. Thank you.
Glad to hear this video was useful. I appreciate you leaving a comment.
my man is a absolutely wonderful
appreciate what you do man
Thanks a lot @TheGladiator123, appreciate you taking the time to write a comment, and hope this video was helpful.
@@SoftwareNuggets just if you can
I would like to see more implementation of This function in solving more complex/ real world problem
Also A Question:
Can I use This user defined function to create a new column in the table
@@TheGladiator123
watch these video's I created using the function. I think you'll be impressed, and you'll become the master!
--deck of cards (great skill to learn)
ua-cam.com/video/7U129er3MYQ/v-deo.html
--table valued function
ua-cam.com/video/9aXD69xBvMs/v-deo.html
--insert stored procedure
ua-cam.com/video/jOyYhwxMGpg/v-deo.html
--cursor in a function
ua-cam.com/video/o4blx6Ij5S8/v-deo.html
--how to write a scalar function
ua-cam.com/video/2DtPEXjnxs4/v-deo.html
--return a rowtype
ua-cam.com/video/hOe3bi_nUYA/v-deo.html
--convert ip address to big int
ua-cam.com/video/SVlWmjM4sWk/v-deo.html
@@TheGladiator123 here is a function to allow you to add a column to a table.
CREATE OR REPLACE FUNCTION fn_add_column_to_table(table_name VARCHAR, column_name VARCHAR, the_data_type VARCHAR, size INT)
RETURNS VARCHAR
AS
$$
BEGIN
IF size IS NOT NULL THEN
EXECUTE format('ALTER TABLE %I ADD COLUMN %I %s(%s)', table_name, column_name, the_data_type, size);
ELSE
EXECUTE format('ALTER TABLE %I ADD COLUMN %I %s', table_name, column_name, the_data_type);
END IF;
RETURN 'Column added successfully';
END;
$$
LANGUAGE plpgsql;
@@SoftwareNuggets
hey king Just Your Opinion
I wa trying to implement what I learned From You But got Stucked At This edge Case Where I let The User pass an arraay OF words To a Colum with The Type VARCHAR(225)
I still Got errors
and I can't change The Column Defination
Excellent stuff! Very helpful and useful tutorial.
Thanks for the comment, glad to hear this video was helpful.
This was very helpful Sir.
Hey @hamzas4117, glad to hear this video was very helpful. Thanks for letting me be part of your learning journey.
Very informative video, thank you!
You're very welcome!
most excellent stuff. thank you for doing these.
Glad you enjoy it! Appreciate you leaving a message as well as subscribing to my channel.
Template Code for creating SQL Function
create or replace function func_name(fieldName datatype)
returns
as
$$
begin
end;
$$
language plpgsql;
--parameter type{in*|out|inout|VARIADIC**} *default **variable number of arguments
create or replace function func_name({parameter type} fieldName datatype)
as
$$
begin
end;
$$
language plpgsql;
if then
elsif then
else
end if;
create or replace function fn(field datatype)
returns table
(
field_name1 integer,
field_name2 character varying(60),
field_name3 varchar
)
as
$$
begin
-- table alias is mandatory, or use tablename as alias
RETURN QUERY
select alias.field1,
alias.field2,
alias.field3
from table alias
where alias.field1 = inputParameter;
end;
$$
Language plpgsql;
Thank you so much for sharing!
thank you. I hope this video was helpful!
thanks it worked
Which solution helped you?
@@SoftwareNuggets including function procedure under $$ for creating function
Thanks
Your welcome
Thank you! Very useful vidio!
Glad it was helpful!
Great work, help me a lot. Thank you!
Glad to hear that! Thanks for leaving a comment.
@@SoftwareNuggets could you please make a video on postgres daterange type. i have some undrstanding issues
I’ll work on it tonight, publish as soon as I finish. Thanks for a great suggestion video.
@@SoftwareNuggets that sounds great, I am hurry to see that. I wonder how it could be tricky to use daterange instead of 2 date columns. Thanks🙏
at 12:15, my intro to the Range Type will be available. I hope to have Part 2, done tomorrow to discuss Overlapping. Please share you comments after you view this video if you have time.
Do you have more explanations about the functions in postgre
Here is a few video that will teach you about postgresql functions: Please check out my postgresql Playlist and Postgresql Shorts:
Table-Valued Function in PostgreSQL: How to write and consume.
ua-cam.com/video/9aXD69xBvMs/v-deo.html
PostgreSQL Function to Convert an IP Address into a Big Int, and from a BIG Int to an IP Address.
ua-cam.com/video/SVlWmjM4sWk/v-deo.html
PostgreSQL - Use Function to Generate XML from table data using XMLForest, XMLElement and XLMAgg.
ua-cam.com/video/nCC1OyZs-PE/v-deo.html
PostgreSQL - Write a Function that uses RETURNS SETOF json.
ua-cam.com/video/NAUZW-_hf7I/v-deo.html
PostgreSql Enum: A Beginner's guide to Implement and Use ENUMS in a function.
ua-cam.com/video/_B-ctj7zPno/v-deo.html
PostgreSQL - Create Function, use rowtype and return json object
ua-cam.com/video/hOe3bi_nUYA/v-deo.html
PostgreSQL: A table-valued function to Split Full Names into individual fields.
ua-cam.com/video/G77v_FFo99A/v-deo.html
PostgreSQL: Scalar Function. How to write and use a SQL Scalar function.
ua-cam.com/video/2DtPEXjnxs4/v-deo.html
wow! very useful!
Glad to hear you found this video useful. Thanks for the comment.
Can you use postgresql functions with NodeJs?
Why are there no tutorials about how to do that?
Could you pls make a tutorial to demonstrate how to do that?
Hey @LekkyDev, I will have a video out tonight, however, I could just upload the source to this problem to my github account earlier if you'd like. Please let me know. If no response, I'll just publish video ASAP.
@@SoftwareNuggets That would be great if you could upload the source
but videos are always better because you get to see the build up as well.
I really struggle to find any tutorial about plpgsql with nodejs.
Thanks for reaching back and looking forward to the source and the video.
@LekkyDev, I will upload the video at 7pm tonight. Look forward to hearing comments from you.
@@SoftwareNuggets Wow thanks in advance. Its past 9pm already central euro time. Still waiting.
I reschedule for 6pm.
Hey there, god bless your efforts.
I am still learning about sql by my own and having today a simple question.
I learned that Processes (also known as “procedures”) may take values and give
out parameters.
Are processes opposite of a function?
Is there any related functions used to execute a process? Thanks..
@@SoftwareNuggets Hello man, very clear and to the point, but still left with a major enquiry. You said that " functions are read-only, they can only get data" and then you said that "Functions can select data, update data, delete data". Are these two statements conflicting because I learned recently that we can not use Insert/Update/Delete statements with SQL Server functions.
Hey Hasan, i deleted all my messages, just so that I can give you ONE clear message about the difference between a Function and Stored Procedure.
The main functional difference between a function and a stored procedure is: a function returns a result, whereas a stored procedure does not.
Functions normally use the RETURNS keyword. you can return a single data type: varchar, integer, numeric, etc.
Function can also return a TABLE(see video at 16:29), we can use tables for result queries.
However, at (11:51), I write a function that DOES NOT, have a return value, but used the INOUT parameter type.
In stored procedure, they can also have return values, but limited. [If you want a QUERY RESULT] use a function.
procedure are NOT intended to return result sets.
-- other databases behave differently - when you are searching for a feature, make sure the content is about "PostgreSQL"
I hope this clears up your question.
please watch my CURSOR video, i show how a function can be used to UPDATE/DELETE
Here is a link: ua-cam.com/video/o4blx6Ij5S8/v-deo.html
Thank you
I hope this video was useful. Thanks for visiting software nuggets, watching this video and leaving a comment.
🙏🙏🙏
Thanks
very helpful and to the point, when dealing with tables, What if I need to save the result of the query in a variable, say the query returns only one value
I need to convert this from msAccess VBA
Holiday_start = DLookup("[Start_date]", "Public_att_holiday", "[Start_date] = #" & Format(DateCnt, "yyyy/mm/dd") & "#")
where Start_date is a field in the Public_att_holiday table which I need to compare with DateCnt and return the start_date Value from the table if exists and save to Holiday_start Variable
Hey @adnanberki3869 , please let me know if this is what you are looking for.
create or replace function DLookup(DateCnt date)
returns date
as
$$
declare
lookupValue date;
begin
select show.date_premiered into lookupValue
from tv_show_v2 as show
where show.date_premiered = DateCnt
limit 1;
return lookupValue;
end;
$$
language plpgsql;
select DLookup('1969-10-26')
i created a new video for scalar functions, here is a link if you'd like to check it out:
ua-cam.com/video/2DtPEXjnxs4/v-deo.html
@@SoftwareNuggets Thank you for care, yes it gave me good idea of how to fix some issues, I still have some problems since I'm new to coding in postgresql, Thank you again for your time.
I don't get it well my question did not answer,my question is out line six language in which function can be written in post Gre SQL? am a a student
Are you asking, other than LANGUAGE plpgsql, what other languages can you use?
why we use inout btw, you haven't explained.
Hey @abdulrehmanjaved-rt8jq,
Let me start of by showing you a very simple function that uses the INOUT clause:
CREATE OR REPLACE FUNCTION update_value(INOUT num_param INT)
AS
$$
BEGIN
num_param := num_param + 10; -- Increase the value by 10
END;
$$
LANGUAGE plpgsql;
-- NOTICE there is NOT a return clause on that function.
--INOUT means, you send a value into that function (the IN) part, and (the out) part is available to the caller
Here is how you call:
SELECT * FROM update_value(5) AS result;
notice the output of the call: num_param equals 15
Your question was, why do we use this.
If you want to call a function, and want to set the behavior of a column to be both input and output, then use INOUT.
CREATE TABLE IF NOT EXISTS orders (
id SERIAL PRIMARY KEY,
total DECIMAL(10, 2)
);
CREATE TABLE IF NOT EXISTS order_items (
id SERIAL PRIMARY KEY,
order_id INT REFERENCES orders(id),
price DECIMAL(10, 2),
quantity INT
);
-- Insert sample data
INSERT INTO orders (id) VALUES (1), (2);
INSERT INTO order_items (order_id, price, quantity) VALUES
(1, 10.00, 2),
(1, 15.50, 1),
(2, 5.75, 3),
(2, 20.00, 1);
DROP FUNCTION calculate_total_cost(integer)
CREATE OR REPLACE FUNCTION calculate_total_cost(inout order_id INT, OUT total_cost DECIMAL)
AS $$
BEGIN
SELECT SUM(price * quantity)
INTO total_cost
FROM order_items
WHERE order_items.order_id = calculate_total_cost.order_id;
-- Update the order with the calculated total
UPDATE orders SET total = total_cost WHERE id = order_id;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM calculate_total_cost(1);
in the function calculate_total_cost, change order_id from INOUT to IN; run this sql statement: SELECT * FROM calculate_total_cost(1); compare the return columns from the first function code, to the "change INOUT to IN" code results.
Hope this helps.
Scott
@@SoftwareNuggets Thanks for great explaination, appreciated.
Hey so this is how the book "SQL for Data Analytics : Perform Fast and Efficient Data Analysis with the Power of SQL" teaches how to code the function equivalent.
Bro this is soooo weird.
CREATE OR REPLACE FUNCTION fn_mid(VARCHAR, INTEGER, INTEGER)
RETURNS VARCHAR AS $new_substring$
DECLARE new_substring VARCHAR;
BEGIN
RETURN SUBSTRING($1, $2, $3);
END; $new_substring$
LANGUAGE PLPGSQL;
hey @MC-Minority,
in this statement, if you comment out --DECLARE new_substring VARCHAR. that variable is un-used.
Scott
i just watched that video, at position 02:54 has an example close to yours. Might be helpful.