Question

Hello i am using PostegreSQL and i want to constrain a certain number(tax ID number) to obey the following rules:

  • 9 Digits
  • The last digit (z) is calculated according to:

x = 8th * 2 + 7th * 3 + 6th * 4 + 5th * 5 + 4th * 6 + 3rd * 7 + 2nd * 8 + 1st + 9

y = x % 11  
if (y == 0 || x == 1) z = 0;
else z = 11 - y

Is this possible in sql?

Was it helpful?

Solution

Yes, it is possible although cumbersome. It looks something like this:

check ((col regexp_matches '^[0-9]{9}$) and
       (case when (substring(col, 1, 1) * 9 + substring(col, 2, 1) * 8 + substring(col, 3, 1) * 7 +
                   substring(col, 4, 1) * 6 + substring(col, 5, 1) * 5 + substring(col, 6, 1) * 4 +
                   substring(col, 7, 1) * 3 + substring(col, 8, 1) * 2 
                  ) % 11 = 0 or
                  (substring(col, 1, 1) * 9 + substring(col, 2, 1) * 8 + substring(col, 3, 1) * 7 +
                   substring(col, 4, 1) * 6 + substring(col, 5, 1) * 5 + substring(col, 6, 1) * 4 +
                   substring(col, 7, 1) * 3 + substring(col, 8, 1) * 2 
                  ) = 1
             then 0
             else 11 -
                  ((substring(col, 1, 1) * 9 + substring(col, 2, 1) * 8 + substring(col, 3, 1) * 7 +
                    substring(col, 4, 1) * 6 + substring(col, 5, 1) * 5 + substring(col, 6, 1) * 4 +
                    substring(col, 7, 1) * 3 + substring(col, 8, 1) * 2 
                   ) % 11
                  )
        end) = substring(col, 9, 1) + 0
    )

Personally, I would encapsulate it in a function and use the function instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top