How to Copy a Resultset Column as an IN Statement


In the realm of software engineering, we often work with data (stored in databases). On my team this is especially true. We are primarily a Microsoft shop (SQL Server, .NET, Visual Studio).

When performing data operations, it is often the case that you must find a batch of data, verify that’s the data that you need to update, and then update only those records that you have verified. This tip may help streamline these efforts.

There is a feature of Microsoft SQL Server Management Studio that allows you to “Copy as IN clause”!

This means after you’ve built a query and identified the records you need (most likely including an ID field), you can just copy the IDs you need preformatted as an IN clause. Noice!

How-To Steps

  • Run a query in SQL Server Management Studio
  • Select/highlight a list of GUID values (UNIQUEIDENTIFIER) in a single column of the result set.
  • Right-click
  • Copy as IN clause
  • Paste (CTRL+V) into your new query
  • Done!

Screenshots or it Didn’t Happen!

Screenshot of SQL Server Management Studio featuring the Right-Click Copy as IN clause functionality.
Right-click your selected ID column and click “Copy as IN clause”
Screenshot of SQL Server Management Studio featuring a SELECT statement with an IN clause.
Now you can just paste (CTRL+V) your new IN clause into a new query.

A Simple SQL Script

Here’s the test SQL script that I used in the above screenshots.

FROM master..spt_values
AND number < 10

FROM [dbo].[Sample]

Bonus Tip

You may not have picked up the bonus tip above, so I’ll draw your attention to it. The first portion of the test SQL script above contains a handy way of generating a set number of values from a function, like the NEWID() function, which generates UNIQUEIDENTIFIER (Guid) values.