Build an Application-Ready Marketing Transactions Schema with Sequences
Notebook
Note
This notebook requires a Standard or Premium cluster. Sequences are not available on Free Starter Clusters.
Prerequisite: Generate the Real-Time Digital Marketing dataset
This notebook reads source data from the martech database populated by the RTDM demo. Complete the steps below before running any code cells.
Two databases — know which is which
| Database | Owner | What this notebook does with it |
|---|---|---|
martech | RTDM demo | Read-only. Never dropped or modified by this notebook. |
mktx_sequences_demo | This notebook | Created here. All DDL and application tables go here. |
Steps to populate martech
Make sure you are on a Standard or Premium cluster — the RTDM demo requires it.
Open the Real-Time Digital Marketing demo: https://digital-marketing.labs.singlestore.com/
Enter your cluster host, username
admin, your cluster password, and database namemartech.Click Connect, then Setup Database.
Keep the simulator running until the dashboard shows purchases and offers being generated.
Return to this notebook.
Before running DDL cells
Select mktx_sequences_demo from the database dropdown at the top of this notebook. The DDL creates tables in mktx_sequences_demo — not in martech.
Action Required
Select mktx_sequences_demo from the database drop-down at the top of this notebook before running any table-creation cells.
The application scenario
A subscriber just made a purchase through the RTDM platform. Your application needs to:
Record the purchase as a marketing transaction with a compact, unique identifier
Create a linked order record and derive a human-readable invoice display number
Attach one or more line items to that order
Do all of this safely under concurrent writes — without using
MAX(id) + 1
By the end of this notebook your application tables will produce output like this:
| txn_id | display_ref | invoice_display | advertiser | vendor | bid_cents |
|---|---|---|---|---|---|
| 1 | TXN-00001 | INV-000001 | Quatz | quatz.biz | 10 |
| 2 | TXN-00002 | INV-000002 | Topiclounge | topiclounge.com | 10 |
Sequence values are database-generated — your actual
txn_idandorder_idvalues will differ.
Reference: A Developer's Guide to SingleStore Sequences
How the pieces fit together
RTDM purchase event (subscriber_id, vendor_name, ts)
│
▼
marketing_txns txn_id ← sequence-generated
│
▼
mktx_orders order_id ← sequence-generated
invoice_display = CONCAT('INV-', LPAD(order_id, 6, '0'))
│
▼
txn_line_items line_id ← sequence-generated
The source event columns travel with each transaction row for lineage. Sequence columns are generated by the database — the application never computes them.
Section 1 — Environment setup
Installs dependencies, connects to SingleStore, and creates mktx_sequences_demo.
Two SQL patterns used in this notebook:
%%sql— DDL, control statements, and display SELECTs.run_sql()— where Python is needed: parameterized queries, polling loops, and DataFrame results.
In [1]:
1%pip install singlestoredb pandas --quiet
In [2]:
1import random2import time3import pandas as pd4import singlestoredb as s25 6pd.set_option("display.max_colwidth", 120)7random.seed(42)8 9# ── Database names ────────────────────────────────────────────────────────────10SOURCE_DB = "martech" # read-only — populated by the RTDM demo11WORKING_DB = "mktx_sequences_demo" # this notebook's database — all DDL goes here12USE_DB = None13 14# ── Connection helpers ────────────────────────────────────────────────────────15# run_sql is used where Python control flow, parameters, or DataFrame consumption16# is needed. Simple user-facing SQL cells use %%sql (see below).17def connect():18 global conn19 conn = s2.connect(database=USE_DB) if USE_DB else s2.connect()20 conn.autocommit(True)21 if USE_DB:22 with conn.cursor() as cur:23 cur.execute(f"USE {USE_DB}")24 25def _query(query, params=None):26 with conn.cursor() as cur:27 cur.execute(query, params)28 if cur.description:29 cols = [d[0] for d in cur.description]30 return pd.DataFrame(cur.fetchall(), columns=cols)31 return None32 33def run_sql(query, params=None):34 for attempt in range(4):35 try:36 return _query(query, params)37 except Exception as e:38 msg = str(e)39 if getattr(e, "errno", None) in (2006, 2013) or "Lost connection" in msg or "gone away" in msg:40 connect()41 else:42 raise43 44def try_sql(query, params=None, label="Step"):45 try:46 return run_sql(query, params)47 except Exception as e:48 print(f"{label} skipped: {e}")49 return None50 51connect()52 53shared = run_sql("SHOW VARIABLES LIKE 'is_shared_tier'")54IS_SHARED = shared is not None and len(shared) > 0 and shared.iloc[0, 1] == "ON"55 56if IS_SHARED:57 print("Free Starter Cluster detected — using the current database.")58 USE_DB = run_sql("SELECT DATABASE() AS db").iloc[0, 0]59else:60 run_sql(f"CREATE DATABASE IF NOT EXISTS {WORKING_DB}")61 USE_DB = WORKING_DB62 run_sql(f"USE {WORKING_DB}")63 64connect()65active_db = run_sql("SELECT DATABASE() AS db").iloc[0, 0]66print(f"Source database : {SOURCE_DB}")67print(f"Working database : {active_db}")68print(f"SingleStore version: {run_sql('SELECT @@memsql_version AS v').iloc[0, 0]}")
Section 2 — Inspect the Real-Time Digital Marketing purchase data
Reads a bounded sample from martech and copies it into notebook-owned tables in mktx_sequences_demo (up to 10,000 purchases and 500 offers). Stops with a clear message if martech is empty.
Create the RTDM source tables
Drops and recreates the three source tables scoped to this notebook. Safe to rerun.
In [3]:
1%%sql2DROP TABLE IF EXISTS rtdm_purchases;3DROP TABLE IF EXISTS rtdm_offers;4DROP TABLE IF EXISTS rtdm_vendors;5 6CREATE TABLE rtdm_purchases (7 subscriber_id BIGINT,8 vendor_name VARCHAR(100),9 ts DATETIME(6) DEFAULT NOW(6),10 SORT KEY (ts),11 KEY (vendor_name) USING HASH12);13 14CREATE ROWSTORE TABLE rtdm_offers (15 offer_id BIGINT PRIMARY KEY,16 customer VARCHAR(100),17 enabled BOOL,18 notification_zone TEXT,19 segment_ids JSON,20 notification_content TEXT,21 notification_target VARCHAR(200),22 maximum_bid_cents BIGINT23);24 25CREATE ROWSTORE REFERENCE TABLE rtdm_vendors (26 domain VARCHAR(200) PRIMARY KEY,27 vendor VARCHAR(100),28 category VARCHAR(50),29 popularity DOUBLE30);
Load RTDM data
Loads purchases, offers, and vendor reference data from martech. Because one vendor name can appear under multiple domains (e.g. dabshots.mil, dabshots.edu), a rtdm_vendor_canonical view picks exactly one domain per vendor name — preventing duplicate rows when we join purchases to vendors. This is a demo convenience, not a verified match between a purchase and an advertising campaign.
In [4]:
1MAX_ROWS = 10_0002 3# ── Validate martech source tables ───────────────────────────────────────────4def _table_row_count(db, table):5 try:6 n = run_sql(7 "SELECT COUNT(*) AS n FROM information_schema.TABLES "8 "WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s", (db, table)9 ).iloc[0, 0]10 if int(n) == 0:11 return 0 # table does not exist12 return int(run_sql(f"SELECT COUNT(*) AS n FROM {db}.{table}").iloc[0, 0])13 except Exception:14 return 015 16purchases_n = _table_row_count(SOURCE_DB, "purchases")17offers_n = _table_row_count(SOURCE_DB, "offers")18 19if purchases_n == 0 or offers_n == 0:20 missing = []21 if purchases_n == 0:22 missing.append("purchases")23 if offers_n == 0:24 missing.append("offers")25 print("━" * 60)26 print(f"⛔ STOP: martech.{' and martech.'.join(missing)} {'is' if len(missing) == 1 else 'are'} empty or missing.")27 print()28 print("The martech database exists but has not been populated yet.")29 print("To fix this:")30 print(" 1. Go to https://digital-marketing.labs.singlestore.com/")31 print(" 2. Connect using your cluster host, username admin, and password.")32 print(" 3. Set database name to: martech")33 print(" 4. Click Setup Database.")34 print(" 5. Keep the simulator running until purchases and offers appear.")35 print(" 6. Return here and rerun this cell.")36 print("━" * 60)37 raise RuntimeError(f"martech source tables not ready: {missing}")38 39print(f"martech source validated — purchases: {purchases_n:,}, offers: {offers_n:,}")40 41# ── Vendors (always loaded from the RTDM GitHub repo) ────────────────────────42vdf = pd.read_json(43 "https://raw.githubusercontent.com/singlestore-labs/demo-realtime-digital-marketing/main/data/vendors.json"44)45vdf["domain"] = (vdf["vendor"].str.lower() + "." + vdf["tld"])46vdf = vdf.drop_duplicates("domain")47with conn.cursor() as cur:48 cur.executemany(49 "INSERT INTO rtdm_vendors VALUES (%s, %s, %s, %s)",50 vdf[["domain", "vendor", "category", "popularity"]].values.tolist(),51 )52print(f"Vendors loaded: {len(vdf)} rows ({vdf['vendor'].nunique()} unique names)")53 54# One canonical domain per vendor name (demo enrichment, not confirmed attribution).55run_sql("DROP VIEW IF EXISTS rtdm_vendor_canonical")56run_sql("""57 CREATE VIEW rtdm_vendor_canonical AS58 SELECT v.vendor, v.domain, v.category59 FROM rtdm_vendors v60 JOIN (SELECT vendor, MIN(domain) AS domain FROM rtdm_vendors GROUP BY vendor) m61 ON m.vendor = v.vendor AND m.domain = v.domain62""")63print("Canonical vendor view created.")64 65# ── Load bounded sample from martech into mktx_sequences_demo ────────────────66run_sql(f"""67 INSERT INTO rtdm_purchases (subscriber_id, vendor_name, ts)68 SELECT subscriber_id, vendor, ts69 FROM {SOURCE_DB}.purchases70 ORDER BY ts DESC71 LIMIT {MAX_ROWS}72""")73run_sql(f"""74 INSERT IGNORE INTO rtdm_offers75 SELECT offer_id, customer, enabled, notification_zone,76 segment_ids, notification_content, notification_target, maximum_bid_cents77 FROM {SOURCE_DB}.offers78 ORDER BY offer_id79 LIMIT 50080""")81print("Loaded from martech.")82 83# ── Post-load verification ────────────────────────────────────────────────────84counts = run_sql('''85 SELECT86 (SELECT COUNT(*) FROM rtdm_purchases) AS rtdm_purchases,87 (SELECT COUNT(*) FROM rtdm_offers) AS rtdm_offers,88 (SELECT COUNT(*) FROM rtdm_vendors) AS rtdm_vendors89''')90 91p_loaded = int(counts["rtdm_purchases"].iloc[0])92o_loaded = int(counts["rtdm_offers"].iloc[0])93 94if p_loaded == 0 or o_loaded == 0:95 print("━" * 60)96 print("⛔ STOP: Working tables loaded zero rows.")97 print(" rtdm_purchases:", p_loaded)98 print(" rtdm_offers :", o_loaded)99 print("Check that martech is populated and rerun from Section 2.")100 print("━" * 60)101 raise RuntimeError("Working tables are empty after load.")102 103display(counts)104print("✔ Source data loaded into mktx_sequences_demo.")
Inspect a sample
Confirm the source columns the transaction layer will consume.
In [5]:
1print("--- purchases (source event: decoded vendor name) ---")2display(run_sql(3 "SELECT subscriber_id, vendor_name, ts FROM rtdm_purchases ORDER BY ts DESC LIMIT 5"4))5 6print("\n--- canonical vendor enrichment (one domain per vendor name, demo only) ---")7display(run_sql(8 "SELECT vendor, domain, category FROM rtdm_vendor_canonical ORDER BY vendor LIMIT 5"9))10 11print("\n--- row-count check: purchases after canonical enrichment join ---")12display(run_sql('''13 SELECT14 COUNT(*) AS purchase_rows,15 COUNT(DISTINCT p.subscriber_id) AS unique_subscribers,16 COUNT(DISTINCT vc.domain) AS distinct_enriched_domains,17 COUNT(DISTINCT o.offer_id) AS distinct_offers18 FROM rtdm_purchases p19 JOIN rtdm_vendor_canonical vc ON vc.vendor = p.vendor_name20 JOIN rtdm_offers o ON o.notification_target = vc.domain21'''))22 23print("\n--- offers sample ---")24display(run_sql(25 "SELECT offer_id, customer, notification_target AS domain, maximum_bid_cents "26 "FROM rtdm_offers ORDER BY offer_id LIMIT 5"27))
Setup verification
Confirm both databases are visible and working tables contain data before proceeding.
In [6]:
1print(f"Active working database : {run_sql('SELECT DATABASE() AS db').iloc[0, 0]}")2print(f"Source database : {SOURCE_DB}")3print()4 5display(run_sql(f"""6 SELECT7 '{SOURCE_DB}' AS source_db,8 (SELECT COUNT(*) FROM {SOURCE_DB}.purchases) AS source_purchases,9 (SELECT COUNT(*) FROM {SOURCE_DB}.offers) AS source_offers10"""))11 12display(run_sql(f"""13 SELECT14 '{WORKING_DB}' AS working_db,15 (SELECT COUNT(*) FROM rtdm_purchases) AS rtdm_purchases,16 (SELECT COUNT(*) FROM rtdm_offers) AS rtdm_offers,17 (SELECT COUNT(*) FROM rtdm_vendors) AS rtdm_vendors18"""))19 20rp = int(run_sql("SELECT COUNT(*) AS n FROM rtdm_purchases").iloc[0, 0])21ro = int(run_sql("SELECT COUNT(*) AS n FROM rtdm_offers").iloc[0, 0])22 23if rp > 0 and ro > 0:24 print("✔ Ready — working tables contain data.")25else:26 print("⚠ Working tables are empty. Rerun from Section 2 after populating martech.")
Section 3 — Why sequences instead of MAX(id) + 1
A common pattern is to compute the next ID in application code:
next_id = SELECT MAX(txn_id) + 1 FROM marketing_txns
INSERT INTO marketing_txns (txn_id, ...) VALUES (next_id, ...)
This breaks under concurrent writes: two sessions can read the same MAX simultaneously and both try to insert the same ID, producing a duplicate key error. AUTO_INCREMENT AS SEQUENCE lets the database generate IDs — each aggregator pre-caches a block of values, so every insert gets a unique ID with no coordination required.
Section 4 — Create application-owned tables with sequences
Three tables form the application boundary, each using INT AUTO_INCREMENT AS SEQUENCE as its primary key.
| Table | Purpose | Sequence column |
|---|---|---|
marketing_txns | One row per accepted purchase event | txn_id |
mktx_orders | One order per transaction; source of the invoice display number | order_id |
txn_line_items | One row per vendor line within a transaction | line_id |
A sequence PK is incompatible with a separate composite unique key in SingleStore. Idempotency is handled at the application layer with
TRUNCATEbefore each full load.
Action Required
Make sure mktx_sequences_demo is selected from the database drop-down at the top of this notebook before running the cells below. The DDL creates tables in mktx_sequences_demo — not in martech. The martech source database is never dropped or modified by this notebook.
One sequence per table
SingleStore supports exactly one AUTO_INCREMENT AS SEQUENCE column per table. Do not add a second sequence column to the same table.
In [7]:
1%%sql2DROP TABLE IF EXISTS txn_line_items;3DROP TABLE IF EXISTS mktx_orders;4DROP TABLE IF EXISTS marketing_txns;5 6-- Note: with a sequence PK, a separate composite unique key is not supported.7-- Idempotency is handled at the application layer (see Section 5).8CREATE ROWSTORE TABLE marketing_txns (9 txn_id INT AUTO_INCREMENT AS SEQUENCE PRIMARY KEY,10 subscriber_id BIGINT NOT NULL,11 event_ts DATETIME(6) NOT NULL,12 offer_id BIGINT NOT NULL,13 customer VARCHAR(100),14 domain VARCHAR(200),15 category VARCHAR(50),16 bid_cents BIGINT,17 created_at DATETIME(6) DEFAULT NOW(6),18 KEY idx_src (subscriber_id, event_ts, offer_id) USING HASH19);20 21CREATE ROWSTORE TABLE mktx_orders (22 order_id INT AUTO_INCREMENT AS SEQUENCE PRIMARY KEY,23 txn_id INT NOT NULL,24 customer VARCHAR(100),25 domain VARCHAR(200),26 bid_cents BIGINT,27 created_at DATETIME(6) DEFAULT NOW(6),28 KEY idx_txn (txn_id) USING HASH29);30 31CREATE ROWSTORE TABLE txn_line_items (32 line_id INT AUTO_INCREMENT AS SEQUENCE PRIMARY KEY,33 txn_id INT NOT NULL,34 vendor VARCHAR(100),35 category VARCHAR(50),36 bid_cents BIGINT,37 KEY idx_txn (txn_id) USING HASH38);
Verify the sequence columns
SHOW CREATE TABLE confirms that txn_id uses AUTO_INCREMENT AS SEQUENCE.
In [8]:
1%%sql2-- Confirm the active database and that txn_id uses AUTO_INCREMENT AS SEQUENCE3SELECT DATABASE();4SHOW CREATE TABLE marketing_txns;
Section 5 — Sequence demonstration: insert transactions and link child records
This section shows sequences in action across three tables:
Bulk insert — 200 purchase events are inserted into
marketing_txns. Notxn_idis supplied; the sequence generates one for each row automatically.Linked orders — one
mktx_ordersrow is created per transaction, copying the sequence-generatedtxn_idas a foreign key.Parent-child linking — a single event is inserted step-by-step to show how
LAST_INSERT_ID()captures the generatedtxn_idand passes it to the childtxn_line_itemsrow.
The tables are truncated first so this section is safe to rerun.
In [9]:
1%%sql2TRUNCATE TABLE txn_line_items;3TRUNCATE TABLE mktx_orders;4TRUNCATE TABLE marketing_txns;
In [10]:
1MAX_ROWS = 2002 3# Parameterized — uses Python variable for LIMIT, so run_sql() is needed here.4run_sql(f"""5 INSERT INTO marketing_txns6 (subscriber_id, event_ts, offer_id, customer, domain, category, bid_cents)7 SELECT8 p.subscriber_id,9 p.ts,10 o.offer_id,11 o.customer,12 vc.domain,13 COALESCE(vc.category, 'general'),14 o.maximum_bid_cents15 FROM rtdm_purchases p16 JOIN rtdm_vendor_canonical vc ON vc.vendor = p.vendor_name17 JOIN rtdm_offers o ON o.notification_target = vc.domain18 ORDER BY p.ts DESC19 LIMIT {MAX_ROWS}20""")21run_sql("""22 INSERT INTO mktx_orders (txn_id, customer, domain, bid_cents)23 SELECT txn_id, customer, domain, bid_cents24 FROM marketing_txns25""")26print(f"Inserted up to {MAX_ROWS} transactions and linked orders.")
In [11]:
1%%sql2SELECT3 (SELECT COUNT(*) FROM marketing_txns) AS txns_loaded,4 (SELECT COUNT(*) FROM mktx_orders) AS orders_created;
Inspect the generated identifiers
The source event columns travel alongside the database-generated txn_id and serve different purposes:
| Column | Purpose |
|---|---|
txn_id | Compact application identifier — generated by the sequence, never supplied by the caller |
subscriber_id, event_ts, offer_id | Source identity — used for lineage and duplicate detection |
In [12]:
1%%sql2SELECT txn_id, subscriber_id, event_ts,3 offer_id, customer, category, bid_cents4FROM marketing_txns5ORDER BY txn_id6LIMIT 10;
Using LAST_INSERT_ID() to link a parent row to its children
After the database generates a txn_id for an inserted transaction, LAST_INSERT_ID() returns that exact value for the current session. This is how you safely pass a sequence-generated ID from a parent row to its child rows — without doing a follow-up SELECT MAX(txn_id) that could return a different session's row under concurrent writes.
In [13]:
1# Insert one conversion event and link its order and line items via LAST_INSERT_ID()2sample = run_sql('''3 SELECT p.subscriber_id,4 p.ts AS event_ts,5 o.offer_id, o.customer,6 vc.domain,7 COALESCE(vc.category, 'general') AS category,8 o.maximum_bid_cents9 FROM rtdm_purchases p10 JOIN rtdm_vendor_canonical vc ON vc.vendor = p.vendor_name11 JOIN rtdm_offers o ON o.notification_target = vc.domain12 ORDER BY p.ts13 LIMIT 114''')15 16row = sample.iloc[0]17 18with conn.cursor() as cur:19 # Insert the parent transaction — no txn_id supplied20 cur.execute('''21 INSERT INTO marketing_txns22 (subscriber_id, event_ts, offer_id, customer, domain, category, bid_cents)23 VALUES (%s, %s, %s, %s, %s, %s, %s)24 ''', (int(row.subscriber_id), row.event_ts, int(row.offer_id),25 row.customer, row.domain, row.category, int(row.maximum_bid_cents)))26 27 # Retrieve the sequence value generated for this session28 cur.execute('SELECT LAST_INSERT_ID() INTO @parent_txn_id')29 30 cur.execute('''31 INSERT INTO mktx_orders (txn_id, customer, domain, bid_cents)32 VALUES (@parent_txn_id, %s, %s, %s)33 ''', (row.customer, row.domain, int(row.maximum_bid_cents)))34 35 cur.execute('''36 INSERT INTO txn_line_items (txn_id, vendor, category, bid_cents)37 VALUES (@parent_txn_id, %s, %s, %s)38 ''', (row.domain, row.category, int(row.maximum_bid_cents)))39 40run_sql('''41 SELECT t.txn_id,42 CONCAT('INV-', LPAD(ord.order_id, 6, '0')) AS invoice_ref,43 t.subscriber_id, t.customer, t.category,44 l.line_id, l.vendor, l.bid_cents45 FROM marketing_txns t46 JOIN mktx_orders ord ON ord.txn_id = t.txn_id47 JOIN txn_line_items l ON l.txn_id = t.txn_id48 ORDER BY t.txn_id DESC49 LIMIT 550''')
Preventing duplicate transactions
Because txn_id is sequence-generated, you cannot add a composite unique constraint to block re-inserts at the database level. Instead, check whether a transaction already exists for the source event key (subscriber_id, event_ts, offer_id) before inserting — and skip if one is found. The next cell demonstrates this guard.
In [14]:
1# Attempt to insert the same purchase event a second time.2# The guard checks whether a transaction already exists for this source event3# before inserting, so no duplicate application record is created.4sample = run_sql('''5 SELECT subscriber_id, event_ts, offer_id6 FROM marketing_txns7 ORDER BY txn_id8 LIMIT 19''')10row = sample.iloc[0]11 12existing = run_sql('''13 SELECT txn_id FROM marketing_txns14 WHERE subscriber_id = %s AND event_ts = %s AND offer_id = %s15''', (int(row.subscriber_id), row.event_ts, int(row.offer_id)))16 17if len(existing) > 0:18 print(f"Source event already recorded as txn_id={existing.iloc[0,0]} — skipping insert.")19 print("The source event key (subscriber_id, event_ts, offer_id) is the idempotency key.")20 print("The sequence-generated txn_id is the application key — these are separate concerns.")21else:22 run_sql('''23 INSERT INTO marketing_txns24 (subscriber_id, event_ts, offer_id, customer, domain, category, bid_cents)25 VALUES (%s, %s, %s, '', '', '', 0)26 ''', (int(row.subscriber_id), row.event_ts, int(row.offer_id)))27 print("Inserted (event was new).")
Validate the generated identifiers
Confirm every sequence-generated key is unique and no line items are orphaned.
In [15]:
1checks = {}2 3# Primary key uniqueness4dup_pk = run_sql('''5 SELECT txn_id, COUNT(*) AS cnt6 FROM marketing_txns7 GROUP BY txn_id8 HAVING cnt > 19''')10checks["duplicate txn_id"] = len(dup_pk)11 12# Order uniqueness (one order per transaction)13dup_ord = run_sql('''14 SELECT order_id, COUNT(*) AS cnt15 FROM mktx_orders16 GROUP BY order_id17 HAVING cnt > 118''')19checks["duplicate order_id"] = len(dup_ord)20 21# Orphaned line items (no parent txn)22orphans = run_sql('''23 SELECT COUNT(*) AS n24 FROM txn_line_items l25 LEFT JOIN marketing_txns t ON t.txn_id = l.txn_id26 WHERE t.txn_id IS NULL27''')28checks["orphaned line_items"] = int(orphans.iloc[0, 0])29 30for k, v in checks.items():31 status = "PASS" if v == 0 else "FAIL"32 print(f"[{status}] {k}: {v}")
Section 6 — Sequence properties and the invoice display number
Key properties of SingleStore sequences:
| Property | Behaviour |
|---|---|
| Unique | Every generated value is guaranteed unique |
| Not gapless | Rolled-back transactions leave unused values; gaps are normal |
| Cached per aggregator | Each aggregator pre-fetches a block of values; jumps in the sequence are expected |
| One per table | Only one AUTO_INCREMENT AS SEQUENCE column is allowed per table |
| Not an idempotency key | The sequence does not block duplicates; use the source event key for that |
CONCAT('INV-', LPAD(order_id, 6, '0')) builds the invoice display number on the fly from order_id. It is a presentation label — not a stored column and not a gapless accounting sequence.
In [16]:
1%%sql2-- Invoice display number derived in SQL — not stored as a column3SELECT t.txn_id,4 CONCAT("TXN-", LPAD(t.txn_id, 5, "0")) AS display_ref,5 ord.order_id,6 CONCAT("INV-", LPAD(ord.order_id, 6, "0")) AS invoice_display_number,7 t.customer, t.category, t.bid_cents8FROM marketing_txns t9JOIN mktx_orders ord ON ord.txn_id = t.txn_id10ORDER BY t.txn_id11LIMIT 8;
Manual override warning
Manually supplying a value for a sequence column (e.g. INSERT INTO marketing_txns (txn_id, ...) VALUES (99, ...)) can desynchronise the aggregator caches. If you ever do this, run:
AGGREGATOR SYNC AUTO_INCREMENT ON marketing_txns ALL;
This notebook does not perform manual overrides in the main path.
Section 7 — API and support lookup
The query an API endpoint, support workflow, or AI assistant would run to retrieve full transaction context: purchase event, subscriber info, vendor enrichment, generated identifiers, and line items.
In [17]:
1%%sql2SELECT3 t.txn_id,4 CONCAT("TXN-", LPAD(t.txn_id, 5, "0")) AS display_ref,5 ord.order_id,6 CONCAT("INV-", LPAD(ord.order_id, 6, "0")) AS invoice_display_number,7 t.subscriber_id,8 t.event_ts,9 t.customer AS advertiser,10 t.category,11 t.domain AS vendor_domain,12 t.bid_cents,13 l.line_id,14 l.vendor,15 l.bid_cents AS line_bid_cents16FROM marketing_txns t17JOIN mktx_orders ord ON ord.txn_id = t.txn_id18LEFT JOIN txn_line_items l ON l.txn_id = t.txn_id19ORDER BY t.txn_id DESC20LIMIT 5;
Extending the lookup
Replace the LIMIT 5 clause with WHERE txn_id = N to look up a single transaction. All context is stored in the application tables — no external credentials required.
In [18]:
1%%sql2-- Runnable lookup by transaction ID — replace LIMIT with a WHERE txn_id = N clause to look up a single transaction.3SELECT4 t.txn_id,5 CONCAT("INV-", LPAD(ord.order_id, 6, "0")) AS invoice_display_number,6 t.subscriber_id,7 t.event_ts,8 t.customer AS advertiser,9 t.category,10 t.domain AS vendor_domain,11 t.bid_cents,12 l.line_id,13 l.vendor,14 l.bid_cents AS line_bid_cents15FROM marketing_txns t16JOIN mktx_orders ord ON ord.txn_id = t.txn_id17LEFT JOIN txn_line_items l ON l.txn_id = t.txn_id18ORDER BY t.txn_id DESC19LIMIT 5;
Key takeaways
| Concept | What this notebook showed |
|---|---|
AUTO_INCREMENT AS SEQUENCE | Database-generated identifiers — unique, sequential, no application coordination needed |
| Source event identity | (subscriber_id, event_ts, offer_id) travels with each row for lineage and duplicate detection |
| Parent-child linking | LAST_INSERT_ID() returns the sequence value generated for the current session — safe under concurrent writes |
| Sequence gaps | Rolled-back transactions leave gaps; non-contiguous values are normal and expected |
| Invoice display number | CONCAT('INV-', LPAD(order_id, 6, '0')) is a presentation-layer label, not an accounting invoice sequence |
| Idempotency | With a sequence PK, composite unique constraints are not supported; guard duplicate events at the application layer |
Section 8 — Cleanup and rerun guidance
The cleanup cell below drops the entire mktx_sequences_demo database on Standard/Premium clusters — not just the tables this notebook created. If you have other objects in that database, they will be deleted too. Check before running.
To rerun the notebook from scratch: run this cleanup cell, then re-execute from Section 1 (not Section 2). Section 1 recreates the mktx_sequences_demo database and re-establishes the connection — Section 2's DDL cells will fail without it. Select mktx_sequences_demo from the database dropdown again before running the DDL cells.
martech is never modified.
In [19]:
1app_tables = ["txn_line_items", "mktx_orders", "marketing_txns"]2src_tables = ["rtdm_purchases", "rtdm_offers", "rtdm_vendors"]3 4if not IS_SHARED:5 run_sql(f"DROP DATABASE IF EXISTS {WORKING_DB}")6 print(f"Database '{WORKING_DB}' dropped.")7else:8 for t in app_tables + src_tables:9 run_sql(f"DROP TABLE IF EXISTS {t}")10 print(f"Dropped table: {t}")11 12print("Cleanup complete. martech was not modified.")

Details
About this Template
Use Real-Time Digital Marketing purchase events as source data to build an application-owned transactions layer backed by SingleStore Sequences. Learn why MAX(id)+1 is unsafe and how AUTO_INCREMENT AS SEQUENCE generates compact, unique identifiers for transactions and orders.
This Notebook can be run in Standard and Enterprise deployments.
Tags
See Notebook in action
Launch this notebook in SingleStore and start executing queries instantly.
License
This Notebook has been released under the Apache 2.0 open source license.