Reputation: 3081
I'm working on a database where I retrieve the ID of my record after I've added it by saving and retrieving a known GUID. My application runs on both SQL Server and Oracle, so I can't use @@IDENTITY*.
Say for example, I add a new address:
ID (identity column in SQL Server;sequenced/trigger column in Oracle)
... address data... (street, town, postcode, etc.)
GUID
I get the ID back by doing the following:
1. INSERT INTO ADDRESS (... address details, GUID = {some new GUID value})
2. SELECT ID FROM ADDRESS WHERE GUID = {my GUID value}
3. UPDATE ADDRESS SET GUID = NULL WHERE GUID = {my GUID value}
At part 1, I'm adding the address details and setting the GUID value in the database; at part 2, I'm getting my ID back and at part 3, I'm removing the GUID value from the database (to avoid the very unlikely event of a duplicate GUID).
When I look at the SQL Server 2008 Estimated Execution Plan for the third bit, it shows the following path if I have no index on the GUID column:
and the following path if I have an index on the GUID column:
My question is: I realise that the scan shown in the first image is not as good as the seek shown in the second image, but would the fact that the GUID column is essentially empty 99.999% of the time mean that I shouldn't index the field, because it would be fragmented all the time and would waste resources? Or would the index still help because it would easily show me where my one-and-only GUID is that I just added, rather than having to do a whole scan for it?
In summary: Given the fact that the GUIDs are added and then immediately removed, is there any point in indexing the GUID column?
*In fact, the design is not my own, so I'm unable to use a different method; however, you should see that the design of my particular database does not affect my overall question.
Upvotes: 0
Views: 1468
Reputation: 294217
Yes, you absolutely need to index your column for what you're doing. Use a filtered index in SQL Server (not sure what is the Oracle equivalent):
create index AddressGuid on ADDRESS(GUID) where GUID is not NULL;
But there is abetter way: use OUTPUT/RETURNING clause of INSERT. Both SQL Server and Oracle supports it (each its own flavour) and you no longer need the GUID workaround.
Upvotes: 2
Reputation: 86708
If you don't index that column, each of those SELECT
and UPDATE
statements will have to scan the whole table to find your row. If that's not what you want, you'll have to index. I wouldn't bother setting that GUID
column to NULL, though.
Upvotes: 0