Store Multiple NULL values with unique data in SQL Server

Hello friends,

Sometimes we get the data that needs to be unique but can also get NULL records. Existing ways to achieve uniqueness doesn’t allow NULLs (Primary Key) or allow max one NULL (Unique Constraint).

Let’s take an example to understand this better. Suppose, you have an Employee table with fields like Id, FirstName, MiddleName, LastName, Email etc. As per requirement, email needs to be unique (if supplied), however, users are also allowed to register without entering email and hence in the database Email is a nullable field.

So how would you achieve the Email uniqueness along with having more than one NULLs.

CREATE UNIQUE NONCLUSTERED INDEX [UX_Employee_Email] ON [dbo].Employee WHERE Email IS NOT NULL

Above code will ensure that Email doesn’t have duplicate data however it may store more than one NULLs.

I hope you may have liked the tip. You share your comments.

Enable CORS in ASP.NET Core Web API

Hello friends,

As we know that in Web API, CORS is by default disabled due to security reasons. and hence if a client tries to access API in different server and port, you can end up with error as “Origin http://localhost:xxxx is not allowed by Access-Control-Allow-Origin

To enable it in ASP.NET Core Web API, there are few steps involved as following.

Go to startup.cs

Put code as follows inside ConfigureServices method

services.AddCors();

Put code as follows inside Configure method

app.UseCors(
options => options.WithOrigins("http://localhost", "https://localhost")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);

In the WithOrigins array, you can add or remove the client URL based on your local machine domain and port settings.

Hope you found the post useful. Please let me know your comment below.