I’d like to select data from a table with the following rule, but I’m having trouble writing the query. I’m using PostgreSQL and I can’t create a UDF. The table looks like this:
id | user_id | account_number
-------------------------------
1 | 1 | 12345671
2 | 4 | 12356673
3 | 7 | 12325678
The id and user_id are integers whereas the account number is a string. I’d like to select the account numbers that match the following conditions:
- Account number string contains exactly 8 digits
- Validation scheme
- Take the first 7 digits
- Multiply the first digit by 1, the second by 2, the third by 3, the fourth by 1, the fifth by 2, the sixth by 3 and the seventh by 1
- Sum the result of multiplying each digit by the relevant number
- If the 8th digit is the same as mod(sum, 10) then select this number
In this table above, I should only return the first two rows with the query.
Just to repeat, I can’t create a UDF, so am looking to find out whether this is possible using ordinary SQL in a query.
Thanks!
Yes, you can do it. Basically, use SIMILAR TO to check for exactly 8 digits, then substring and cast to do the math. Something like this:
Of course, this returns no rows in your example, because:
PS: You do realize the UDFs can be written in languages other than C. E.g., you can write one in PL/pgSQL.