Code Generator | SQL

SQL Function to Summarize a Table

This SQL function allows users to summarize a table by providing the table name as an argument. It returns the column names, minimum values, maximum values, and average values for each column in the specified table.


Empty image or helper icon

Prompt

summarize a table

Answer

SQL Function to Summarize a Table

--Function to summarize a table
CREATE OR REPLACE FUNCTION summarize_table(table_name VARCHAR)
RETURNS TABLE(column_name VARCHAR, minimum_value FLOAT, maximum_value FLOAT, average_value FLOAT) AS
$$
BEGIN
    EXECUTE 'SELECT column_name, MIN(column_name) AS minimum_value, MAX(column_name) AS maximum_value, AVG(column_name) AS average_value 
    FROM ' || table_name || ' GROUP BY column_name' INTO column_name, minimum_value, maximum_value, average_value;
    
    RETURN NEXT;
END;
$$ 
LANGUAGE plpgsql;

Usage Example:

To use the function, simply call it and provide the name of the table you want to summarize as an argument:

SELECT * FROM summarize_table('sales_data');

This will return a result set with columns for the column name, minimum value, maximum value, and average value for each column in the specified table.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

The SQL function summarize_table is designed to provide an easy way to summarize the values in a table. It takes the name of the table as an argument and returns a result set with the column names, minimum values, maximum values, and average values for each column in the specified table. This function can be especially useful when working with large datasets and needing to quickly analyze the data. By calling summarize_table and providing the name of the table, users can obtain a summary of the data without having to manually write separate queries for each column. This function saves time and effort by automating the process of summarizing a table.