Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8093871
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T20:36:25+00:00 2026-06-05T20:36:25+00:00

I have been fruitlessly trying for several hours to make a function that filter

  • 0

I have been fruitlessly trying for several hours to make a function that filter array subscripts based upon a criteria on the array from which the subscripts and then create an array of those subscripts.

The data structure I am dealing with is similar to the following sample (except with many more columns to compare and more complicated rules and mixed data types):

id hierarchy abbreviation1 abbreviation2
1  {1}       SB            GL
2  {2,1}     NULL          NULL
3  {3,2,1}   NULL          TC
4  {4,2,1}   NULL          NULL

I need to run a query that takes the next non-null value closest to the parent for abbreviation1 and abbreviation2 and compares them based upon the hierarchical distance from the current record in order to get a single value for an abbreviation. So, for example, if the first non-null values of abbreviation1 and abbreviation2 are both on the same record level abbreviation1 would take priority; on the other hand, if the first non-null abbreviation2 is closer to the current record then the corresponding non-null value for abbreviation1, then abbreviation2 would be used.

Thus the described query on the above sample table would yield;

id abbreviation
1  SB
2  SB
3  TC
4  SB

To accomplish this task I need to generate a filtered array of array subscripts (after doing an array_agg() on the abbreviation columns) which only contain subscripts where the value in an abbreviation column is not null.

The following function, based on all the logic in my tired mind, should work but does not

CREATE OR REPLACE FUNCTION filter_array_subscripts(rawarray anyarray,criteria anynonarray,dimension integer, reverse boolean DEFAULT False) 
  RETURNS integer[] as 
$$
DECLARE
  outarray integer[] := ARRAY[]::integer[];
  x integer;
  BEGIN
    for i in array_lower(rawarray,dimension)..array_upper(rawarray,dimension) LOOP
      IF NOT criteria IS NULL THEN
        IF NOT rawarray[i] IS NULL THEN
          IF NOT rawarray[i] = criteria THEN
            IF reverse = False THEN
              outarray := array_append(outarray,i);
            ELSE
              outarray := array_prepend(i,outarray);
            END IF;
         ELSE
            IF reverse = False THEN
              outarray := array_append(outarray,i);
            ELSE
              outarray := array_prepend(i,outarray);
            END IF;
         END IF;
        END IF;
      ELSE
        IF NOT rawarray[i] is NULL THEN
          IF reverse = False THEN
            outarray := array_append(outarray,i);
          ELSE
            outarray := array_prepend(i,outarray);
          END IF;
        END IF;
      END IF;
    END LOOP;
    RETURN outarray;
  END; 
$$ LANGUAGE plpgsql;

For example, the below query returns {5,3,1} when it should return {5,4,2,1}

select filter_array_subscripts(array['This',NULL,'is',NULL,'insane!']::text[]
                               ,'is',1,True);

I have no idea why this does not work, I have tried using the foreach array iteration syntax but I cannot figure out how to cast the iteration value to the scalar type contained within the anyarray.

What can be done to fix this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T20:36:26+00:00Added an answer on June 5, 2026 at 8:36 pm

    You can largely simplify this whole endeavor with the use of a RECURSIVE CTE, available in PostgreSQL 8.4 or later:

    Test table (makes it easier for everyone to provide test data in a form like this):

    CREATE TEMP TABLE tbl (
        id int
      , hierarchy int[]
      , abbreviation1 text
      , abbreviation2 text
    );
    
    INSERT INTO tbl VALUES
     (1, '{1}',     'SB', 'GL')
    ,(2, '{2,1}',   NULL, NULL)
    ,(3, '{3,2,1}', NULL, 'TC')
    ,(4, '{4,2,1}', NULL, NULL);
    

    Query:

    WITH RECURSIVE x AS (
        SELECT id
             , COALESCE(abbreviation1, abbreviation2) AS abbr
             , hierarchy[2] AS parent_id
        FROM   tbl
    
        UNION ALL
        SELECT x.id
             , COALESCE(parent.abbreviation1, parent.abbreviation2) AS abbr
             , parent.hierarchy[2] AS parent_id
        FROM   x
        JOIN   tbl AS parent ON parent.id = x.parent_id
        WHERE  x.abbr IS NULL  -- stop at non-NULL value
        )
    SELECT id, abbr
    FROM   x
    WHERE  abbr IS NOT NULL  -- discard intermediary NULLs
    ORDER  BY id
    

    Returns:

    id | abbr
    ---+-----
    1  | SB
    2  | SB
    3  | TC
    4  | SB
    

    This presumes that there is a non-null value on every path, or such rows will be dropped from the result.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

have been trying couple of hours now to make my iphone app universal. The
Have have been trying to make a validator for my xml files. I have
I have been tasked with refactoring some components that used xmlbeans to now make
Have been struggling all day trying to make this simple example work using socket.io.
Have been working on this question for a couple hours and have come close
I have been trying very hard to achieve rounded corners with IE6+jquery ui tabs.
I have been trying to us CALayers as sprites in an iPhone application I'm
I have an array of arrays that I want to use KVC on (at
Have been trying to fix this problem I have here. Basically I have a
Have been trying the whole day long and googled the **** out of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.