Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL justify_hours Function: Setup and Usage Guide

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL does not have a built-in justify_hours function, but you can create one using PL/pgSQL to convert a total number of minutes or seconds into a formatted "X hours Y minutes" string. This is essential for reporting systems where raw durations (like 135 minutes) need to be displayed in a human-readable format (2 hours 15 minutes).

What You'll Need

  • A PostgreSQL database instance.
  • A database user account with permissions to create functions (superuser or owner of the schema).
  • A SQL client such as pgAdmin, psql, or DBeaver.

Step-by-Step

  1. Connect to your database: Open your preferred SQL editor and connect to the specific database where you want the function to reside.
  2. Define the function logic: You must write a function that takes an integer (the total minutes) and calculates the quotient (hours) and the remainder (minutes).
  3. Execute the CREATE FUNCTION command: Copy and run the following SQL code in your query tool. This example creates a function that accepts total minutes and returns a formatted text string.
    CREATE OR REPLACE FUNCTION justify_hours(total_minutes INTEGER) 
        RETURNS TEXT AS $$
        DECLARE
            hours INTEGER;
            mins INTEGER;
        BEGIN
            hours := total_minutes / 60;
            mins := total_minutes % 60;
            RETURN hours || ' hours ' || mins || ' minutes';
        END;
        $$ LANGUAGE plpgsql;
  4. Verify the function creation: Check your "Functions" list in your database browser or run \df justify_hours in the psql command line to ensure it was created successfully.
  5. Test the function with a simple query: Run a SELECT statement to verify the math is working correctly.
    SELECT justify_hours(135); 
        -- Expected Output: 2 hours 15 minutes
  6. Apply the function to a table: Use the function within a SELECT statement to format data from an existing column.
    SELECT task_name, justify_hours(duration_minutes) 
        FROM project_tasks;

Common Mistakes

  • Integer Division Confusion: In PostgreSQL, dividing an integer by an integer results in an integer. If you try to use total_minutes / 60.0, the result becomes a numeric/decimal, which will cause a type mismatch error when assigning it to an INTEGER variable. Keep the divisor as 60 to ensure the decimal is truncated.
  • Null Handling: If the input column contains NULL values, the function will return NULL. If you prefer a default value (like "0 hours 0 minutes"), you must wrap the input in a COALESCE function.
  • Schema Issues: Creating the function in the public schema is common, but if you use a custom schema, you must call the function using the schema prefix (e.g., SELECT my_schema.justify_hours(120);) or update your search path.

Tips

  • Handle Singular/Plural: To make the output more professional, you can add IF statements to the function to return "1 hour" instead of "1 hours" when the value is exactly one.
  • Use Intervals: For more complex time calculations, consider using the native PostgreSQL INTERVAL type. You can convert minutes to an interval using (total_minutes || ' minutes')::interval, which allows for easier addition and subtraction of time.
  • Indexing: Remember that calling a custom function in a WHERE clause can slow down queries because the database must execute the function for every row. If you need to filter by "justified" hours frequently, consider creating a generated column or a materialized view.

Troubleshooting

If the function does not work as expected, follow these steps in order:

  • Check Permissions: If you get a "permission denied" error, ensure your user has CREATE privileges on the schema. Use GRANT CREATE ON SCHEMA public TO your_username; if necessary.
  • Verify Data Types: If you receive a "function does not exist" error, check that you are passing an INTEGER. If your column is a BIGINT or NUMERIC, you must either cast the input justify_hours(column::integer) or redefine the function to accept BIGINT.
  • Clear Cache/Reconnect: If you updated the function using CREATE OR REPLACE but the output hasn't changed, ensure your transaction was committed and refresh your SQL client connection.

Frequently Asked Questions

Can I modify this function to handle seconds instead of minutes?

Yes. Change the divisor from 60 to 3600 for hours and use a second modulo operation (% 60) to extract the remaining seconds.

Is there a way to do this without creating a custom function?

Yes, you can perform the math directly in a SELECT statement: SELECT (mins / 60) || 'h ' || (mins % 60) || 'm' FROM table;

Will this function work on all versions of PostgreSQL?

Yes, this uses standard PL/pgSQL syntax that is compatible with almost all modern versions of PostgreSQL.

How do I delete the function if I no longer need it?

Use the command DROP FUNCTION justify_hours(INTEGER);. You must include the argument type in the drop command because PostgreSQL supports function overloading.

Can I return the result as a time object instead of text?

It is better to return an INTERVAL type. This allows the database to treat the result as a duration rather than a simple string, making it possible to perform further calculations on the result.