Explain Codes LogoExplain Codes Logo

Howto? Parameters and LIKE statement SQL

sql
sql-injection
stored-procedures
performance-tuning
Anton ShumikhinbyAnton Shumikhin·Nov 26, 2024
TLDR

Using parameters with LIKE clause in SQL? Here's how it goes:

SELECT * FROM your_table WHERE your_column LIKE CONCAT('%', ?, '%');

? represents your input parameter, and CONCAT makes sure the column includes that parameter. Save the % for the query, don't smuggle it with the parameter.

Bulletproofing your SQL Queries

Strangle the SQL injection

It's 2022 and SQL injection is still a threat. Dodge this bullet by sticking with SqlCommand and parameters.

// When you don't want strangers to know what you bought last summer var command = new SqlCommand("SELECT * FROM Customers WHERE Name LIKE @NamePattern", connection); command.Parameters.Add(new SqlParameter("@NamePattern", $"%{searchString}%"));

Fuzzy Search Dynamics

Add the SQL wildcard % to the parameter before passing it to the query, because who doesn't love a good ol' fashioned wild card hunt?!

VB.NET Orcish

VB.NET syntax is slightly different, make sure to tackle AddWithValue method right to keep the pesky type goblins away.

// Keep calm and VB.NET Dim command As New SqlCommand("SELECT * FROM Customers WHERE Name LIKE @NamePattern", connection) command.Parameters.AddWithValue("@NamePattern", "%" & searchString & "%")

The charm of Stored Procedures

For more manageability, wrap your LIKE queries in a cozy stored procedure blanket. This keeps your code neat, and your queries swift and safe.

Troubleshooting Chronicles

Where's Waldo: Parameter Edition

Before running your query, check your parameter for wildcards that could play hide and seek with your query's intentions.

Dry Run sans Parameters

Peace of mind is a query without parameters just to check if results are indeed hiding in the data jungle.

What's Behind the Curtain?

To unravel the mystery behind your query's performance, peek under SQL Server's hood. Tools like SQL Server Management Studio (SSMS) spill the beans on execution plans.

Tuning the SQL Machine

The Name Game

Recheck your field names because there's little that your_column can fetch if it doesn't exist in your_table.

Concatenation Rollercoaster

Use || for concatenation instead of %, while dealing with the Oracle of SQL dialects.

The Need for Speed

LIKE statements, especially with leading wildcards, can be slowpokes. A full-text search might just be the turbo boost need for your large datasets.

The Sensitivity Training

Certain databases tend to see the world in black and white. If you're looking for a case insensitive query, make sure to have that talk with your database.