Problem Description / Requirement

The software manufacturer’s database uses the [SQL_Latin1_General_CP1_CI_AS] collation for the application. The development team wrote a custom function that can be used to find customers based on an address search. The department had requested that the search must be case sensitive.

The development team created a User Defined Function dbo.get_customer_address() for the business to find addresses with case sensitive conditions.

Code of the User Defined Function

CREATE FUNCTION dbo.get_customer_address(@address VARCHAR(40))
RETURNS TABLE
AS
RETURN
(
   SELECT *
   FROM   dbo.customers
   WHERE  c_address LIKE @address + '%' COLLATE Latin1_General_100_BIN
);

Challenge

The business is not satisfied with the performance when using the User Defined Function. They complain that even searching for a single customer takes a long time.

Examine the query and optimize query performance. The following rules apply:

  • The metadata of the tables must NOT be adjusted according to manufacturer requirements
  • Indexing can be used freely
  • The User Defined Function can be rewritten as desired
  • You can create and use your own objects.
Category
  • Optimization of code
  • Level: 200
Technical Information

When creating the challenge, one table will be created. The table has a Primary Key ([pk_customers]) on [c_custkey]. An additional nonclustered index ([nix_customers_c_address]) has been implemented to support wildcard searches in the c_address attribute.

Table Name Number of Rows Storage Space
dbo.customers 1.607.957 219 MB
How to start the challenge

When you are connected to the SQL Server instance…

EXECUTE sqlchallenge.dbo.create_challenge 'list';
will give you a list of open challenges
EXECUTE sqlchallenge.dbo.create_challenge 'name_of_challenge';
will create the challenge for you

After the creation just get into the database for your challenge

Solution

The problem can be solved by seeking all affected rows independent from the collation and afterwards taking the few found records and filter them by case sensitive searches.

https://www.sqlchallenges.de/sql-challenge-3-solution

Connect to Microsoft SQL Server

SQL Server: sqlchallenges.germanywestcentral.cloudapp.azure.com
Port: 1433
Version:
16.0.4165.4
Edition: Developer Edition
Authentication Type: SQL Server Authentication
Login Name: sqlchallenge
Password: sqlchallenge#2025!
Encryption Mandatory
Trust Server Certificate: True

 

Associated Workshops

Improve your skills as a database developer

In this workshop, we will cover a wide range of topics and techniques that are essential for modern database developers working with SQL Server. From fundamental concepts to advanced best practices, you’ll gain the knowledge and practical experience needed to excel in your role.