1

I am going over my database and I wanted to know how many primary keys are missing from my tables. Now sometime I have only one primary key which is integer, which is easy, I looked at this SQL: find missing IDs in a table but it was for numeric column.

I got the below solution from SO itself and it helps in case the PK was integer. selecting only the PK into a file I awk through it to find the next missing sequence

gawk '$1!=p+1{print p+1}{p=$1}' 

Now My question revolves around the varchar Primary keys. like a Order reference number perhaps which is not a sequentially increasing integer but a string/varchar/alphanumeric column has anybody tried this already. (a value like A123Z43), in integer/numeric it was easy, I add 1 and I get the next sequence.

I am not sure but it just struck me, would the hash of one key and the next have anything to do with it. I will see if I can try that.

this will get more complex if i got two columns as Primary Keys one being numeric and the other being varchar.

I am working with SQL server and Postgres at the moment.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sarmahdi
  • 1,098
  • 4
  • 21
  • 61

1 Answers1

0

you were checking not missing PK values, but rather sequence gaps. In case of PK on text - only you can define rule for default value. If you have no default value for PK column, you can't check gaps. Eg you have two values in PK: "C12" and "$D" - so what you miss here?.. Does it start from literal? from digit? are spaces allowed? and so on.

Now if you have some sort of rule defined, you can generate_serie and then join it - checking for gaps. eg:

t=# select chr(g)||n,pk from generate_series(65,100,1) g join generate_series(1,9,1) n on true left outer join (values ('A4'),('B3')) as v (pk) on pk=chr(g)||n limit 19;
 ?column? | pk
----------+----
 A1       |
 A2       |
 A3       |
 A4       | A4
 A5       |
 A6       |
 A7       |
 A8       |
 A9       |
 B1       |
 B2       |
 B3       | B3
 B4       |
 B5       |
 B6       |
 B7       |
 B8       |
 B9       |
 C1       |
(19 rows)

Time: 0.392 ms
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132