query: SELECT DISTINCT (IF(?_val = "header", ?_row, "qid,Lpl,Dpl,P31,S143,P910,S143") AS ?__row) WHERE {
    {
      SELECT * WHERE {
          hint:Query hint:optimizer "None".
   { SERVICE <https://query.wikidata.org/bigdata/namespace/categories/sparql> {
    SERVICE mediawiki:categoryTree {
        bd:serviceParam mediawiki:start <https://pl.wikipedia.org/wiki/Kategoria:Polskie_rody_szlacheckie> .
        bd:serviceParam mediawiki:direction "Reverse" .
        bd:serviceParam mediawiki:depth 5 .
    }}
   }union
     { SERVICE <https://query.wikidata.org/bigdata/namespace/categories/sparql> {
    SERVICE mediawiki:categoryTree {
        bd:serviceParam mediawiki:start <https://be.wikipedia.org/wiki/%D0%9A%D0%B0%D1%82%D1%8D%D0%B3%D0%BE%D1%80%D1%8B%D1%8F:%D0%92%D1%8F%D0%BB%D1%96%D0%BA%D0%B0%D0%BB%D1%96%D1%82%D0%BE%D1%9E%D1%81%D0%BA%D0%B0%D1%8F_%D0%B0%D1%80%D1%8B%D1%81%D1%82%D0%B0%D0%BA%D1%80%D0%B0%D1%82%D1%8B%D1%8F> .
        bd:serviceParam mediawiki:direction "Reverse" .
        bd:serviceParam mediawiki:depth 5 .
    }}
   }    
        ?out schema:name ?t;
          schema:about ?k.
        OPTIONAL { ?p wdt:P910 ?k. }
        FILTER(!(BOUND(?p)))
      }
    }
    ?k rdfs:label ?pl.
    FILTER((LANG(?pl)) = "pl")
    FILTER(CONTAINS(?pl, " herbu "))
    FILTER(!(REGEX(?pl, "(Urzędnicy)|(Fundacje)|(miasta )|(ordynacje )|(pałace )|(wsie )|(zamki )", "i")))
    #BIND(STRAFTER(?pl, "herbu ") AS ?herb)
    #?h wdt:P31 ?hi.
    #FILTER(?hi IN(wd:Q5650788))
    #?h rdfs:label ?hl.
    #FILTER((LANG(?hl)) = "pl")
    #FILTER(?hl = ?herb)
    
    VALUES (?_val) {("header") ("row")}
    
    BIND(CONCAT(",", strafter(?pl, "Kategoria:"), ",ród szlachecki,",
                "Q27062351,Q1551807,",
                #STRAFTER(STR(?h), '/entity/'), ",", 
                #"Q1551807,",
                STRAFTER(STR(?k), '/entity/'), ",",
                "Q1551807") AS ?_row)
  }
  ORDER BY DESC(?__row)