SQLite LIKE and ESCAPE: Search a Literal Drone Record Prefix Without Expanding Wildcards
Compare an unescaped LIKE pattern with a literal-prefix pattern on constructed record codes, preserving underscore, percent, escape characters, and default ASCII case behavior.

Separate a literal identifier fragment from a search pattern
An underscore in a drone-review record code can be ordinary data, while the same character in an SQL LIKE pattern means something else. A search intended to find a literal prefix can therefore return additional rows even though the query was parameterized correctly. Before describing those rows as incorrectly labeled assets or duplicate records, preserve the submitted text and identify the matching policy. Ask whether the interface accepts a pattern language or treats every supplied character as literal identifier text.
This tutorial compares two searches on invented printable ASCII codes in a temporary in-memory SQLite database. It does not open a customer register, alter identifiers, or describe a NiVO product database. The catalogue photograph provides separate product context. The function shows an unescaped pattern beside a pattern built for a literal prefix, retaining row positions and both bound strings. It is a focused explanation of wildcard interpretation, not a complete search interface, an asset identity rule, or a report of completed inspections.
Read wildcard escaping separately from SQL parameter binding
SQLite documents percent as matching any sequence of characters and underscore as matching one character in a LIKE pattern. An explicit ESCAPE character lets a pattern represent literal percent, underscore, and the escape character itself. Parameter binding supplies a value to the SQL statement; it does not turn those pattern operators into literal text. The example therefore uses parameter binding in both searches, then applies an additional pattern-escaping rule only in the literal-prefix version.
With the requested prefix P followed by an underscore, the unescaped pattern P_% can match both P_01 and PX01. The literal-prefix version uses an exclamation mark as its declared escape character and builds P!_%, so the underscore must actually occur in the matched text. The final percent remains an intentional suffix wildcard. Default SQLite LIKE also folds ASCII letter case, so a lowercase p_03 still matches this uppercase prefix. Literal punctuation handling does not automatically make the search case sensitive.

Product context only; this photograph does not depict the constructed examples in this article.
Run both matching policies against the same small list
Run the following Python example locally. It accepts at most sixty-four codes and a prefix of up to thirty-two printable ASCII characters. Empty strings are allowed; missing values, non-ASCII text, control characters, and other types are outside this teaching profile. Those restrictions isolate the wildcard question without implying that real identifiers are always ASCII. Each code keeps its supplied position, and the function returns both search patterns so a reviewer can reproduce the exact query interpretation.
The literal pattern is assembled character by character. An exclamation mark, percent, or underscore in the supplied prefix receives a preceding escape character; other characters pass through unchanged. Only after that step is a suffix percent appended. This avoids accidentally re-escaping characters added during an earlier replacement. The fixed SQL statement declares ESCAPE explicitly and receives the complete pattern through a parameter. Neither the prefix nor the codes are interpolated into SQL syntax, and no production data is opened or changed.
import sqlite3
def compare_prefix_search(codes, prefix):
def teaching_text(x):
return type(x) is str and len(x) <= 32 and all(32 <= ord(c) <= 126 for c in x)
if not isinstance(codes, (list, tuple)) or len(codes) > 64:
raise ValueError("Expected at most 64 teaching codes")
if not teaching_text(prefix) or any(not teaching_text(x) for x in codes):
raise ValueError("Expected short printable ASCII strings")
raw_pattern = prefix + "%"
literal_pattern = "".join("!" + c if c in "!%_" else c for c in prefix) + "%"
con = sqlite3.connect(":memory:")
try:
con.execute("CREATE TABLE sample(pos INTEGER PRIMARY KEY, code TEXT)")
con.executemany("INSERT INTO sample VALUES(?, ?)", enumerate(codes))
raw_rows = con.execute(
"SELECT pos, code FROM sample WHERE code LIKE ? ORDER BY pos",
(raw_pattern,)).fetchall()
literal_rows = con.execute(
"SELECT pos, code FROM sample WHERE code LIKE ? ESCAPE '!' ORDER BY pos",
(literal_pattern,)).fetchall()
return {"raw_pattern": raw_pattern, "literal_pattern": literal_pattern,
"raw_rows": raw_rows, "literal_rows": literal_rows}
finally:
con.close()
# Constructed codes; default SQLite ASCII case behavior is retained.
print(compare_prefix_search(["P_01", "PX01", "P%02", "p_03", "P_!", "P_"], "P_"))Test wildcard and escape characters as actual input data
Start with the displayed underscore case, then test a prefix containing a literal percent. Include the chosen escape character itself, repeated escape characters, and combinations such as exclamation followed by underscore. The literal search should behave like a case-insensitive ASCII prefix comparison for this restricted input set. It must not broaden because punctuation happens to resemble a pattern operator. Compare row positions as well as text values so repeated codes remain separate supplied observations.
Also test a blank prefix, a blank code, a prefix longer than the code, mixed ASCII letter case, and punctuation such as an apostrophe. Parameter binding should preserve the apostrophe as data without changing the SQL statement. A blank prefix intentionally produces a suffix wildcard alone and selects every supplied text code, including blank text. That may be unsuitable for an actual interface, but it is the declared behavior of this example rather than an undocumented missing-input policy.
Preserve case policy and identifier meaning outside the example
A literal-prefix search still needs a case policy. The function uses an ordinary fresh SQLite connection and does not change LIKE settings or load a replacement implementation. Its ASCII case behavior belongs in the expected results. Do not promise identical behavior for unrestricted Unicode text or a database with customized matching functions. The exercise rejects those inputs rather than claiming to solve every locale, normalization, collation, or user-interface requirement with one escaping expression.
The selected text is also not proof of physical asset identity. Two matching codes might describe repeated observations, different passes, or unrelated records under an incomplete naming convention. This function makes no such decision. It does not trim spaces, normalize spelling, deduplicate rows, or repair a code that failed to match. Preserve the exact stored values and record positions. Any authorized cleanup needs its own identity rules and evidence, separate from the question of which strings satisfy the chosen prefix policy.
For a real handoff review, retain the original search input even when the application displays an escaped pattern for diagnostics. The displayed pattern is an implementation value, not a corrected identifier that should be written back to the dataset. Store the matching policy beside it and keep original codes unchanged. Confusing those two roles can turn a successful search investigation into an unintended data edit, particularly when percent signs or exclamation marks are legitimate characters in a local naming scheme.
Deliver the reproducible matching rule with the result
A useful review record includes dataset identity, selected column and type, original prefix, constructed bound pattern, declared escape character, case behavior, database and reader versions, row identity rule, and the selected positions. Add a small independently checked punctuation example. If another tool returns different rows, compare these assumptions before deciding that one system lost data. The interface may intentionally support user-entered wildcards while this example intentionally treats its prefix punctuation literally; those are different documented search contracts.
In a NiVO-related record discussion, the method explains why P_01 and PX01 can both appear under an unescaped LIKE prefix while only the first satisfies the literal underscore requirement. It makes no claim about actual customer records or product search behavior. The useful result is a reproducible query whose punctuation and case assumptions remain visible, with original identifiers preserved for the independent checks required by the real task.



