Twitter (X) API to MySQL: Schema, utf8mb4, Upserts and Search

- Use
utf8mb4everywhere: 26.8% of 1,344 real posts (360) and 13 of 218 profiles contain emoji or other 4-byte characters. Autf8mb3column rejects them in strict mode (error 1366) and stores?in their place without it. Set it on the database, the table and the connection (charset="utf8mb4"). - Tweet ids are
BIGINT UNSIGNED: every id in the sample has 19 digits; all 1,344 overflowINT UNSIGNED(max 4,294,967,295) and aDOUBLEcolumn changed 1,341 of 1,344 on the way back. User ids too: 48.2% are above theINTrange. - Upsert with the row alias:
INSERT ... VALUES (...) AS new ON DUPLICATE KEY UPDATE like_count = new.like_count.VALUES()in that clause is deprecated. A re-poll of 188 posts returned affected-rows 2 (updated) for 54.3%, 0 (unchanged) for 45.2% and 1 (new) for 1. - FULLTEXT beats
LIKEby two orders of magnitude: on 86,080 rows,MATCH ... AGAINSTtook 0.44 ms and 0.07 ms,LIKE '%...%'62 to 64 ms. But FULLTEXT matches whole words of 3+ characters: "AI" found 0 posts whereLIKEcounted 576. - Typed columns, not one JSON blob: keeping the whole API payload in a
JSONcolumn took 12,583 KB per 1,000 posts against 1,298 KB for typed tables with indexes, about 9.7x. For hashtags, an edge table answered in 0.70 ms, a multi-valued JSON index in 5.99 ms, aJSON_CONTAINSscan in 26.73 ms. - Cost of the data: $0.15 per 1,000 posts on twitterapi.io ($0.003 per full 20-post page; an empty poll is the $0.00015 minimum) against $0.005 per post read on the official X API, about 33x. This whole study read 1,546 posts in 90 requests for $0.23. See /pricing.
This guide is about MySQL specifically: the character set, integer width, upsert syntax and index types that decide whether tweets from the X (Twitter) API land in a MySQL table intact. If you run PostgreSQL, read our Twitter API to PostgreSQL guide instead (JSONB, GIN indexes, ON CONFLICT, COPY); if you want a document store, the MongoDB guide covers that. The pitfalls here do not exist in those two: Postgres has no 3-byte utf8, and MongoDB stores BSON strings and 64-bit integers natively. MySQL has both traps, plus a FULLTEXT index that ignores words shorter than three characters by default.
Search results for this topic are still dominated by Tweepy streaming tutorials and Python 2 gists written for an API access model that no longer exists. Many stop at four columns and a plain INSERT. Here you get a complete schema (tweets, users, a hashtag edge table and an optional raw-JSON table), an idempotent upsert you can re-run every few minutes, a polling loader in Python with PyMySQL that reads from twitterapi.io without an X developer account, and the queries you will want afterwards.
Every recommendation comes from a real run, not from habit. We pulled the latest posts of 10 organization accounts (@MySQL, @github, @vercel, @Docker, @OpenAIDevs, @nvidia, @NASA, @awscloud, @googlecloud, @CloudflareDev), 1,344 distinct posts and 218 profiles, loaded them into a local MySQL server with default settings, and measured what each choice does: rows rejected under utf8mb3, ids broken by INT and DOUBLE, affected-rows on a re-poll, bytes on disk for JSON versus typed columns, and query times for LIKE, FULLTEXT, JSON_CONTAINS, a multi-valued index and an edge table.
26.8% (360 of 1,344)
What a MySQL tweet pipeline needs, and the four MySQL-specific traps
A tweet pipeline into MySQL has three moving parts: a fetcher that asks an X API for new posts and follows the pagination cursor, a loader that maps the JSON fields onto columns, and the tables. The fetcher and the loader are the same for any database. The tables are where MySQL differs, and where tutorials written years ago go wrong.
The rest of this guide takes those four in order, then covers table design (typed columns versus a JSON column), the polling loader, and the queries. If you already have a table and it says utf8mb3 in SHOW CREATE TABLE, jump to the fix at the end of the FULLTEXT section.
Trap 1 in MySQL: utf8 is not UTF-8, use utf8mb4 for emoji
Per the MySQL reference manual, utf8mb4 "requires a maximum of four bytes per multibyte character" and supports supplementary characters, while utf8mb3 supports only the Basic Multilingual Plane, using up to three bytes per character, and "cannot store the character at all" when it is a supplementary one. Emoji live outside the Basic Multilingual Plane. So do some CJK ideographs, mathematical letters and the styled bold or italic letters people paste into bios.
The name utf8 is the trap. When we created a table with CHARACTER SET utf8, the server answered with this warning, quoted verbatim, and SHOW CREATE TABLE printed utf8mb3:
'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.
How often does it matter for tweets? In our sample, 26.8% of posts (360 of 1,344) and 6.0% of profile names or bios (13 of 218) contained at least one 4-byte character. Inserting every post into two identical tables, one utf8mb3 and one utf8mb4, in the server's default strict SQL mode: the utf8mb3 table rejected exactly those 360 posts with error 1366 (Incorrect string value: '\xF0\x9F...'), the utf8mb4 table rejected 0.
Strict mode is the friendlier failure. With sql_mode set to an empty string (common on older installs and some hosted servers), the same insert into a utf8mb3 column succeeded with only a warning 1366, and the stored text had a ? where the emoji had been. Nothing fails, the data is just wrong, and you find out months later when someone searches for it.
The share varies a lot by account. @MySQL's own posts were the heaviest emoji users in the sample at 77.4%, @Docker the lightest at 3.4%. Do not decide the character set by sampling one account you like.
Three places to set it. The database (CREATE DATABASE ... CHARACTER SET utf8mb4), so new tables inherit it; the table or column, for tables created elsewhere; and the client connection (charset="utf8mb4" in PyMySQL, and the equivalent option in other drivers). A utf8mb4 column is useless if the connection converts the text to utf8mb3 on the way in. Our server's default collation was utf8mb4_0900_ai_ci, which is accent- and case-insensitive: right for search, but it means a UNIQUE key on user_name treats NASA and nasa as the same value.

Trap 2 in MySQL: tweet ids need BIGINT UNSIGNED, not INT or DOUBLE
X post ids are 64-bit integers. Every id in our sample had 19 digits. The MySQL integer reference lists INT UNSIGNED with a maximum of 4,294,967,295 and BIGINT UNSIGNED with a maximum of 18,446,744,073,709,551,615 (8 bytes). In strict mode, inserting the ids into an INT UNSIGNED column failed for 1,344 of 1,344 with an out-of-range error.
DOUBLE is the quieter failure. A double has 53 bits of integer precision, and 100.0% of the post ids are above 2^53. We wrote all 1,344 into a DOUBLE column and read them back: 1,341 came back as a different number. The same thing happens before the database if your code parses JSON into a float (JavaScript's Number, or a pandas column that picked up a NaN). The API returns id as a string; keep it a string in code until you hand it to the driver, or convert with int() in Python.
User ids look safer and are not: 48.2% of the 218 user ids in the sample were above the INT UNSIGNED range and 47.2% above 2^53. Older accounts have short ids, newer ones have 19 digits. Use BIGINT UNSIGNED for author_id, conversation_id and in_reply_to_id too.
Primary key choice. Use the tweet id itself as the InnoDB primary key, not an AUTO_INCREMENT surrogate. It is unique, it is what the upsert needs, and because ids grow roughly with time, new rows append near the end of the clustered index instead of splitting pages in the middle.
-- MySQL: database and tables for tweets (InnoDB, utf8mb4)
CREATE DATABASE twitter CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
USE twitter;
CREATE TABLE users (
id BIGINT UNSIGNED PRIMARY KEY, -- X user ids reach 19 digits
user_name VARCHAR(50) NOT NULL,
name VARCHAR(100),
description TEXT,
followers INT UNSIGNED,
following INT UNSIGNED,
created_at DATETIME,
is_blue_verified BOOLEAN,
KEY (user_name)
) ENGINE=InnoDB;
CREATE TABLE tweets (
id BIGINT UNSIGNED PRIMARY KEY, -- never INT, never DOUBLE
author_id BIGINT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL, -- stored as UTC
text TEXT NOT NULL, -- long posts exceed 280 characters
lang VARCHAR(8),
conversation_id BIGINT UNSIGNED,
in_reply_to_id BIGINT UNSIGNED,
like_count INT UNSIGNED,
retweet_count INT UNSIGNED,
reply_count INT UNSIGNED,
quote_count INT UNSIGNED,
view_count BIGINT UNSIGNED,
bookmark_count INT UNSIGNED,
hashtags JSON, -- e.g. ["mysql", "heatwave"], lowercased
fetched_at DATETIME NOT NULL,
KEY author_time (author_id, created_at),
FULLTEXT KEY ft_text (text),
KEY tags_mv ((CAST(hashtags AS CHAR(64) ARRAY))) -- multi-valued index for MEMBER OF
) ENGINE=InnoDB;
CREATE TABLE tweet_hashtags (
tag VARCHAR(64) NOT NULL,
tweet_id BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (tag, tweet_id)
) ENGINE=InnoDB;
-- Optional: keep the full API payload too (about 10x the disk, see below)
CREATE TABLE tweets_raw (
id BIGINT UNSIGNED PRIMARY KEY,
doc JSON NOT NULL
) ENGINE=InnoDB;Trap 3 in MySQL: re-polls need INSERT ... ON DUPLICATE KEY UPDATE
A poller asks for posts since its last run with a small overlap, so the same post comes back more than once. A plain INSERT fails on the duplicate key; INSERT IGNORE keeps the first copy and throws away the like, repost and view counts that changed since. ON DUPLICATE KEY UPDATE keeps the row and refreshes the counters.
The manual now marks the older form, like_count = VALUES(like_count), as "deprecated, and subject to removal in a future version of MySQL". Use a row alias instead: VALUES (...) AS new ON DUPLICATE KEY UPDATE like_count = new.like_count. The alias cannot share the table's name.
Per the same page, the affected-rows value is 1 for a new row, 2 for an updated row and 0 when the existing row already had the same values (1 instead of 0 if the client sets CLIENT_FOUND_ROWS). PyMySQL's cursor.execute() returns that number, so a loader can count all three for free. We re-polled one page per account after the main load: of 188 posts returned, 102 (54.3%) came back as 2, 85 (45.2%) as 0, and 1 as 1, a post published between the two passes. Re-inserting an identical row returned 0, confirming the driver was not setting CLIENT_FOUND_ROWS.
In other words, about half of re-polled posts had moved counts within minutes. If those numbers matter to you (engagement tracking), the upsert is not optional. If they do not, update only fetched_at and skip the counters, which keeps the 0 case cheap.
-- row alias syntax; VALUES() in the UPDATE clause is deprecated
INSERT INTO tweets (id, author_id, created_at, text, lang, conversation_id, in_reply_to_id,
like_count, retweet_count, reply_count, quote_count, view_count,
bookmark_count, hashtags, fetched_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) AS new
ON DUPLICATE KEY UPDATE
like_count = new.like_count,
retweet_count = new.retweet_count,
reply_count = new.reply_count,
quote_count = new.quote_count,
view_count = new.view_count,
bookmark_count = new.bookmark_count;
-- affected rows per row: 1 = inserted, 2 = updated, 0 = already identical
-- Python side: cursor.execute(...) returns that number, so a re-poll can count all three
-- n = cur.execute(UPSERT, row) # 1, 2 or 0Trap 4 in MySQL: FULLTEXT search, and the three-letter minimum
LIKE '%word%' cannot use a B-tree index, so every keyword search reads the whole table. MySQL's FULLTEXT index (InnoDB or MyISAM, on CHAR, VARCHAR or TEXT columns, per the manual) builds an inverted word index queried with MATCH(text) AGAINST(...) in natural-language, boolean or query-expansion mode.
To time it, we copied the 1,344 real posts 64 times with new ids (86,080 rows; same text, so result counts scale by 64) and ran each query 20 times. Building the FULLTEXT index on that table took 4.9 s.
The counts differ for a reason. LIKE matches substrings, and with the case-insensitive default collation '%database%' also hits "databases" and '%GPU%' hits "GPUs"; FULLTEXT matches whole words, so it found fewer. Use a trailing wildcard in boolean mode (AGAINST ('GPU*' IN BOOLEAN MODE)) if you want the plural.
The last pair is the trap. Our server's innodb_ft_min_token_size was 3, so words shorter than three characters are never indexed: FULLTEXT found 0 posts for "AI". LIKE '%AI%' found 576, but that number is inflated too, because a case-insensitive substring match also hits "said", "email" and "maintain". On tech accounts two-letter terms (AI, ML, UI, JS, Go) matter. The manual's fix: set innodb_ft_min_token_size=2 in the option file, restart the server, rebuild the FULLTEXT indexes. InnoDB also skips a built-in stopword list (INFORMATION_SCHEMA.INNODB_FT_DEFAULT_STOPWORD; stopwords were enabled on our server).
# my.cnf: index two-letter words such as AI, ML, UI, JS (then restart mysqld)
[mysqld]
innodb_ft_min_token_size = 2
-- then rebuild the FULLTEXT index (InnoDB: drop and add)
ALTER TABLE tweets DROP INDEX ft_text;
ALTER TABLE tweets ADD FULLTEXT INDEX ft_text (text);
-- fix an existing utf8mb3 table in place (rewrites the table)
ALTER TABLE tweets CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
Table design in MySQL: typed columns, a JSON column, or both
MySQL has a native JSON type, so it is tempting to store each API response as one document and query it with doc->>'$.likeCount'. We loaded the same posts both ways and compared the InnoDB data_length plus index_length after ANALYZE TABLE (estimates, in 16 KB pages).
The JSON table was about 9.7x larger. The raw payload is big: median 4,710 bytes per post, p95 13,463, and MySQL's binary JSON format was larger still (JSON_STORAGE_SIZE averaged 6,595 bytes, maximum 32,795). Much of that is the embedded author profile, repeated on every post, and the quoted or reposted post nested inside. Typed tables store the author once in users.
Hashtags: three options. We stored hashtags as a lowercased JSON array on the tweet and in an edge table, then counted posts for the sample's top hashtag (92 real posts) on 86,080 rows. JSON_CONTAINS without an index scanned the table: 26.73 ms. A multi-valued index (KEY ((CAST(hashtags AS CHAR(64) ARRAY))), used by MEMBER OF(), JSON_CONTAINS() and JSON_OVERLAPS() per the manual) cut that to 5.99 ms. The edge table's primary key (tag, tweet_id) answered from the index alone in 0.70 ms. The manual lists the limits of multi-valued indexes: they cannot be covering, cannot be built online (ALGORITHM=COPY), and string arrays use the case-sensitive utf8mb4_0900_as_cs collation, which is why we lowercase tags before storing them.
What we recommend. Typed columns for anything you filter, sort or aggregate on; an edge table for hashtags (and mentions, if you need them); and, only if you may want fields later that you did not map today, a separate tweets_raw table with the JSON document, which you can drop or archive without touching the working tables.
The polling loader (twitterapi.io to MySQL in Python) and the queries afterwards
The loader at the bottom of this page does one thing per run: it builds a search such as (from:MySQL OR from:github OR from:Docker) since_time:<unix>, calls /twitter/tweet/advanced_search with queryType=Latest, follows next_cursor while has_next_page is true, upserts the author into users, the post into tweets and its hashtags into tweet_hashtags, and commits once at the end. It prints how many rows were inserted, updated and unchanged, using the affected-rows values above.
Field mapping. The response puts posts in a top-level tweets array. Each post has id (a string), createdAt in the form Thu Oct 16 12:34:56 +0000 2026 (parse it and store UTC in a DATETIME), text, lang, likeCount, retweetCount, replyCount, quoteCount, viewCount, bookmarkCount, conversationId, inReplyToId, entities.hashtags[].text and an author object with id, userName, name, description, followers, following, createdAt and isBlueVerified. There is no public_metrics object; that is the official X API v2 shape.
Scheduling. Run it from cron every 5 to 15 minutes with a since_time that overlaps the previous run by a minute or two; the upsert absorbs the overlap. For a fixed list of accounts with history you need once, /twitter/user/last_tweets with userName= returns the timeline newest first, 20 per page, which is what this study used. For the same pipeline with Postgres or a warehouse instead, see the BigQuery guide; for full-text search at larger scale than one MySQL server, the Elasticsearch guide.
Transactions and batches. With InnoDB, commit per run (or per few hundred rows), not per row; one transaction per row spends its time on log flushes. Keep the connection's autocommit off, as in the code, and wrap the run in a retry that rolls back on error so a half-written batch never stays behind.
With typed tables, the questions people usually ask of a tweet archive are short SQL: latest posts per account through the (author_id, created_at) index, keyword search through FULLTEXT, hashtag counts through the edge table, daily engagement with a GROUP BY on DATE(created_at). If you kept the raw payload, MySQL's -> and ->> operators reach any field in it without a schema change.
For analysis beyond SQL, pull a query result into a DataFrame with pandas.read_sql and continue there; our pandas guide for Twitter data picks up from that point.
-- 1. Latest posts of one account (uses KEY author_time)
SELECT t.id, t.created_at, t.like_count, LEFT(t.text, 80) AS preview
FROM tweets t JOIN users u ON u.id = t.author_id
WHERE u.user_name = 'MySQL'
ORDER BY t.created_at DESC
LIMIT 20;
-- 2. Keyword search with the FULLTEXT index (whole words, 3+ characters by default)
SELECT id, like_count FROM tweets
WHERE MATCH(text) AGAINST ('+database -webinar' IN BOOLEAN MODE);
-- 3. Hashtag: multi-valued index on the JSON array ...
SELECT COUNT(*) FROM tweets WHERE 'mysql' MEMBER OF (hashtags);
-- ... or the edge table (fastest in our run)
SELECT COUNT(*) FROM tweet_hashtags WHERE tag = 'mysql';
-- 4. Engagement per account per day
SELECT u.user_name, DATE(t.created_at) AS day, COUNT(*) AS posts,
SUM(t.like_count) AS likes, ROUND(AVG(t.view_count)) AS avg_views
FROM tweets t JOIN users u ON u.id = t.author_id
GROUP BY u.user_name, day
ORDER BY day DESC, likes DESC;
-- 5. Reach into the raw payload when you kept it (JSON path operators)
SELECT id, doc->>'$.lang' AS lang, JSON_LENGTH(doc->'$.extendedEntities.media') AS media
FROM tweets_raw
WHERE doc->>'$.isReply' = 'false'
LIMIT 10;
-- Sanity checks
SHOW CREATE TABLE tweets; -- must say utf8mb4, not utf8mb3
SELECT @@innodb_ft_min_token_size; -- 3 by default on our serverWhat it costs: MySQL storage and the price of the data
Storage is small. At the measured 1,298 KB per 1,000 posts with indexes, a million posts in typed tables is on the order of 1.3 GB on disk, comfortably inside any managed MySQL tier. The raw-JSON table would be roughly 9.7x that, which is the main reason to keep it optional.
The data itself is billed per post returned. On twitterapi.io, tweet endpoints cost 15 credits per tweet returned, $0.15 per 1,000 posts; a full 20-post page costs $0.003, and a poll that finds nothing costs the minimum of 15 credits ($0.00015). No X developer account is needed to read. On the official X API pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing), a post read is $0.005 and a user read $0.010, with pay-per-usage capped at 3 million post reads a month before Enterprise.
A poller that checks every 5 minutes and usually finds nothing costs about $1.30 a month in empty checks, about $6.48 at every 60 seconds, plus $0.15 per 1,000 posts it actually stores. Rate limits are 20 requests per second once you have paid (0.2 before the first payment). New accounts get free starter credits (no card, one per person or network, expiring after 31 days); see pricing for the current amount and plans.
How we collected this
Question. What do the MySQL-specific choices (character set, id type, upsert form, search index, JSON versus typed columns) do to real tweets from the API, in rows rejected, values altered, bytes and milliseconds?
Accounts and window. The latest timeline posts of 10 organization accounts (@MySQL, @github, @vercel, @Docker, @OpenAIDevs, @nvidia, @NASA, @awscloud, @googlecloud, @CloudflareDev) via /twitter/user/last_tweets, up to 8 pages each, collected in 2026: 1,344 distinct posts and 218 distinct profiles (authors plus authors of quoted and reposted posts). A second pass of one page per account after the load gave the 188-post re-poll. In total 90 requests returned 1,546 posts, about $0.23 of credits.
Method. Everything ran against a throwaway local MySQL server (26.7.0 from the Homebrew package already on the machine, fresh data directory, default settings, default strict sql_mode) on an Apple silicon laptop, through PyMySQL 2.2.8. Rejections and round trips were counted row by row. Sizes are InnoDB data_length + index_length after ANALYZE TABLE, which are page-level estimates. Query times are the median of 20 runs on a table of 64 copies of the real posts with new ids (86,080 rows), so absolute times reflect that size, one laptop and a warm buffer pool, not your server.
What the sample cannot show. Organization accounts post more emoji-light, link-heavy text than many personal accounts or non-English communities, so the 4-byte share for your sources may be higher or lower; measure it on your own data with the same test. Timings on a networked, busy server will be higher across the board; the ratios are the useful part. We did not test MySQL 5.7, MariaDB or managed services, whose defaults can differ (check @@character_set_server and @@innodb_ft_min_token_size on yours).
Privacy. Aggregates only. Organization accounts are named; authors of quoted or reposted posts are counted but never listed. Raw API pages stayed in a temporary directory on the test machine and are not published; the published sample holds de-identified rows (no id, URL, text, author id or handle). Analysis code, results and charts are in the repository under data/studies/twitter-api-mysql/.
"""Poll X (Twitter) accounts with twitterapi.io and upsert the posts into MySQL.
pip install requests pymysql
Env: TWITTERAPI_KEY, MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD (database `twitter`, tables from the DDL above).
"""
import json
import os
import time
from datetime import datetime, timezone
import pymysql
import requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_KEY"]}
ACCOUNTS = ["MySQL", "github", "Docker"]
db = pymysql.connect(
host=os.environ.get("MYSQL_HOST", "127.0.0.1"),
user=os.environ["MYSQL_USER"],
password=os.environ["MYSQL_PASSWORD"],
database="twitter",
charset="utf8mb4", # the connection must be utf8mb4 too, or emoji break in transit
autocommit=False,
)
cur = db.cursor()
UPSERT_TWEET = """
INSERT INTO tweets (id, author_id, created_at, text, lang, conversation_id, in_reply_to_id,
like_count, retweet_count, reply_count, quote_count, view_count,
bookmark_count, hashtags, fetched_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) AS new
ON DUPLICATE KEY UPDATE like_count = new.like_count, retweet_count = new.retweet_count,
reply_count = new.reply_count, quote_count = new.quote_count,
view_count = new.view_count, bookmark_count = new.bookmark_count"""
UPSERT_USER = """
INSERT INTO users (id, user_name, name, description, followers, following, created_at, is_blue_verified)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s) AS new
ON DUPLICATE KEY UPDATE name = new.name, description = new.description,
followers = new.followers, following = new.following"""
def parse_time(s):
# "Thu Oct 16 12:34:56 +0000 2026" -> naive UTC datetime for a DATETIME column
return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y").astimezone(timezone.utc).replace(tzinfo=None)
def as_int(v):
return int(v) if v not in (None, "") else None
def search(query, max_pages=10):
"""Yield tweets for an advanced_search query, following next_cursor."""
cursor = ""
for _ in range(max_pages):
r = requests.get(
f"{BASE}/twitter/tweet/advanced_search",
headers=HEADERS,
params={"query": query, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
r.raise_for_status()
body = r.json()
for t in body.get("tweets", []):
yield t
if not body.get("has_next_page"):
break
cursor = body.get("next_cursor", "")
time.sleep(1) # fixed pacing
def store(t, now):
a = t["author"]
cur.execute(UPSERT_USER, (
int(a["id"]), a["userName"], a.get("name"), a.get("description"),
a.get("followers"), a.get("following"),
parse_time(a["createdAt"]) if a.get("createdAt") else None, bool(a.get("isBlueVerified")),
))
tags = sorted({h["text"].lower() for h in (t.get("entities") or {}).get("hashtags") or []})
n = cur.execute(UPSERT_TWEET, (
int(t["id"]), int(a["id"]), parse_time(t["createdAt"]), t.get("text") or "", t.get("lang"),
as_int(t.get("conversationId")), as_int(t.get("inReplyToId")),
t.get("likeCount"), t.get("retweetCount"), t.get("replyCount"), t.get("quoteCount"),
t.get("viewCount"), t.get("bookmarkCount"), json.dumps(tags), now,
))
cur.executemany("INSERT IGNORE INTO tweet_hashtags (tag, tweet_id) VALUES (%s, %s)",
[(g, int(t["id"])) for g in tags])
return n # 1 inserted, 2 updated, 0 unchanged
def run(since_unix):
query = "(" + " OR ".join(f"from:{a}" for a in ACCOUNTS) + f") since_time:{since_unix}"
now = datetime.now(timezone.utc).replace(tzinfo=None, microsecond=0)
counts = {1: 0, 2: 0, 0: 0}
for t in search(query):
counts[store(t, now)] += 1
db.commit()
print(f"inserted {counts[1]}, updated {counts[2]}, unchanged {counts[0]}")
if __name__ == "__main__":
# First run: last 24 hours. Schedule it (cron, every 5 to 15 minutes) with an overlap window.
run(int(time.time()) - 24 * 3600)
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
How do I store tweets in a MySQL database?
Create InnoDB tables with CHARACTER SET utf8mb4 and the tweet id as a BIGINT UNSIGNED primary key, fetch posts from an X API endpoint such as /twitter/tweet/advanced_search, and write each one with INSERT ... AS new ON DUPLICATE KEY UPDATE so repeated polls refresh counts instead of failing. Store the author in a separate users table and hashtags in an edge table. The schema and a complete Python loader are on this page.
Why do emoji in tweets fail to insert into MySQL?
Because the column or the connection uses utf8, which in MySQL is an alias for utf8mb3 (up to three bytes per character). Emoji need four bytes. In strict mode the insert fails with error 1366 Incorrect string value; without strict mode the emoji becomes ?. In our sample 26.8% of posts were affected. Use utf8mb4 on the database, table and connection, and convert old tables with ALTER TABLE ... CONVERT TO CHARACTER SET utf8mb4.
What data type should a tweet id be in MySQL?
BIGINT UNSIGNED. Post ids are 19-digit 64-bit integers, far above the INT UNSIGNED maximum of 4,294,967,295; all 1,344 ids in our sample overflowed it. Avoid DOUBLE and FLOAT: in our test a DOUBLE column changed 1,341 of 1,344 ids. VARCHAR(20) also works but sorts as text and takes more space.
Should I store tweets as JSON in MySQL?
Keep the fields you query in typed columns and, if you want the full payload, put it in a separate table with a JSON column. In our run the full-payload JSON table took about 9.7x the disk of typed tables with indexes (12,583 KB versus 1,298 KB per 1,000 posts). A JSON array of hashtags with a multi-valued index is a reasonable middle ground for tags.
How do I search tweet text in MySQL?
Add a FULLTEXT index on the text column and query with MATCH(text) AGAINST('term' IN BOOLEAN MODE). On 86,080 rows it took under 2 ms in our test, against about 62 ms for LIKE '%term%'. By default InnoDB does not index words shorter than three characters (innodb_ft_min_token_size), so set it to 2 and rebuild the index if you need terms such as AI or ML.
How do I avoid duplicate tweets in MySQL?
Make the tweet id the primary key and insert with ON DUPLICATE KEY UPDATE. Use the row alias form (VALUES (...) AS new ... like_count = new.like_count); the VALUES() function in that clause is deprecated. Affected rows tell you what happened: 1 new, 2 updated, 0 unchanged.
Do I need an X developer account to save tweets to MySQL?
Not with twitterapi.io: reads need only an API key, sent in the X-API-Key header. Posts cost $0.15 per 1,000 returned, against $0.005 per post read on the official X API pay-per-usage rate card. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the amount.
Is MySQL or PostgreSQL better for storing tweets?
Both work well at the scale of a tweet archive. PostgreSQL has a single UTF-8 encoding with no 3-byte trap, JSONB with GIN indexes and built-in full-text search with configurable dictionaries; MySQL has the simpler replication and hosting story many teams already run, plus FULLTEXT and multi-valued JSON indexes. Pick the one you already operate; our PostgreSQL guide covers the Postgres version of this pipeline.
Continue
- MySQL reference manual: the utf8mb4 character set (4-byte UTF-8)
- MySQL reference manual: INSERT ... ON DUPLICATE KEY UPDATE, row aliases, affected rows
- MySQL reference manual: fine-tuning full-text search (innodb_ft_min_token_size)
- MySQL reference manual: CREATE INDEX and multi-valued indexes
- MySQL reference manual: integer types (INT, BIGINT ranges)
- X developer docs: pay-per-usage pricing
- X (Twitter) API overview and endpoints
- Store tweets in PostgreSQL (JSONB, GIN, ON CONFLICT)
- Store tweets in MongoDB
- Store tweets in Supabase
- Load tweets into BigQuery
- Index tweets in Elasticsearch
- Analyze Twitter data with pandas
- TwitterAPI.io pricing and plans
- TwitterAPI.io API reference
- 01Twitter (X) Fake News Detection: Datasets, Features and Code
- 02Twitter (X) Topic Modeling in Python: BERTopic vs LDA on Real Tweets
- 03How to Make a Twitter (X) Word Cloud from Tweets in Python
- 04Twitter (X) Hate Speech Detection in Python: Models, Thresholds and a Real Reply Study
- 05Spark Streaming Twitter (X) Data in 2026: PySpark Structured Streaming Without TwitterUtils
- 06Get Twitter (X) Data in Python (2026 Tutorial)
- 07Twitter (X) API to Neo4j: model, import and query a real follower and mention graph
- 08Twitter (X) to Apache Kafka: a Python Producer Keyed by Tweet ID
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.