Search code examples
sqlsql-servert-sqlwildcardsql-like

Can storing wildcard strings in a column (to be used with LIKE operator) cause unexpected query results or security issues?


Could storing wildcard strings in a table's column (to be used as the second operand of the LIKE operator in queries) cause any non-obvious behavior? I'm wondering especially about the possibility of unexpected query results or security issues.

Here's an example usage I'm wondering about:

Example table:

| ID        | String              |
|-----------|---------------------|
| 1         | A__XX____5__________|
| 2         | A__XX____6__________|
| 3         | A__YX____5__________|
| 4         | B__XX____5__________|
| 5         | A__XX____5__________|
| 6         | A__XX____7__________|
| 7         | A__YY____5__________|

Example query:

SELECT ID
FROM ExampleTable
WHERE 'AVVYXZZZZ5ABCDEFGHIJ' LIKE String;

Query result:

| ID        |
|-----------|
| 3         | 

Is this a valid and idiomatic way to use them? Are there any examples in some documentation or other reference material that uses SQL wildcards like this?


Solution

  • The security flaw would -- conceivably -- arise if user input is put directly into the table without validation and users are limited to what they can see.

    That is, if '%' could allow someone to see data they shouldn't.

    However, using a column name for the like pattern is not a SQL injection risk, in the sense that it cannot cause another command to "inadvertently" run. And if you are putting the patterns into the table for matching purposes, there is no additional risk.

    There might be a concern with performance, but that is another issue entirely.