Skip to content

Instantly share code, notes, and snippets.

@woehrl01
Last active August 29, 2015 09:53
Show Gist options
  • Save woehrl01/ee1e35789067e00ddc8e to your computer and use it in GitHub Desktop.
Save woehrl01/ee1e35789067e00ddc8e to your computer and use it in GitHub Desktop.
Generation of a sequential GUID on Sqlite
-- Sequential GUID generation for SQLite (3.8.3 or greater)
-- Can be used in DEFAULT expression (remember to suround with "()" )
-- see http://www.codeproject.com/Articles/388157/GUIDs-as-fast-primary-keys-under-multiple-database
select
substr(printf('%014X', (strftime('%s', 'now') * 1000 + substr(strftime('%f','now'), 4, 3))), 3, 8)
|| '-'
|| substr(printf('%014X', (strftime('%s', 'now') * 1000 + substr(strftime('%f','now'), 4, 3))), 11, 4)
|| '-'
|| hex(randomblob(2)) || '-'
|| hex(randomblob(2)) || '-'
|| hex(randomblob(6)) as 'sequentialguid'
from sqlite_master
-- Hint:
-- >> "The 'now' argument to date and time functions always returns exactly the same
-- >> value for multiple invocations within the same sqlite3_step() call"
-- see: https://www.sqlite.org/lang_datefunc.html
-- This can be problematic (because of using the same exact same time) if you fill a table with a
-- recursive call, or other special cases. But should be compensated due to using randomblob.
-- see also: https://msdn.microsoft.com/en-us/library/system.datetime.utcnow
-- >> "Windows NT 3.5 and later have a aproximate resolution of 10 milliseconds"
-- Which leads to a similar behaviour (kind of) in the implementation of the code project article
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment