| Lesson 8 | Using OPENQUERY |
| Objective | Use the OPENQUERY function to retrieve remote data through a linked server in SQL Server 2025. |
The OPENQUERY function sends a SQL command through an existing linked server and exposes the returned rows to a local query. It is a built-in Transact-SQL rowset function. For example, a reporting query running on instance A can request selected orders from instance B, then work with those rows on A. The connection comes from A's linked-server definition, so the reporting statement does not repeat a server address, login name, or password.
This lesson continues the Orders example from the OPENROWSET lesson. The business request remains the same: retrieve up to 20 orders for customer 42. Here, a configured link supplies the connection. Understanding the two query layers helps you decide where filtering, grouping, and ordering belong, and why a local variable cannot simply be placed inside the remote command.
Assume your query window is connected to SQL Server 2025 instance A. A already has a linked server named [RemoteB] that targets instance B. On B, the illustrative database SalesDB contains dbo.Orders, with integer columns OrderID and CustomerID. OrderID is unique. The remote identity selected by the login mapping has permission to read this table.
These names describe an example environment, not a sample database installed automatically with SQL Server. Substitute approved objects when adapting the lesson. The link name is an identifier registered on A; it need not match B's network hostname. Creating a link in the opposite direction would not provide this connection. Likewise, registering B in an SSMS client does not create a linked-server definition on A.
An administrator or suitably authorized user can inspect the definition on A without changing it:
SELECT name, product, provider, data_source,
is_data_access_enabled, is_rpc_out_enabled
FROM sys.servers
WHERE name = N'RemoteB'
AND is_linked = 1;
Compare name, the local alias, with data_source, the provider's destination. Catalog visibility depends on permissions and login mappings. For SQL Server 2022 and later, Microsoft documents VIEW SERVER SECURITY STATE for this catalog view. An access error or missing row under a restricted account should be investigated by the administrator, not treated as proof that the link is absent. See the sys.servers permissions reference.
The two option flags answer different questions. is_data_access_enabled concerns distributed queries such as the OPENQUERY SELECT below. is_rpc_out_enabled concerns outgoing remote command or procedure execution. The latter becomes relevant to the optional EXECUTE AT example later; it is not a blanket requirement for OPENQUERY reads. An administrator manages these settings through the linked-server options.
Authentication and authorization also remain separate. The linked-server login mapping determines which identity reaches B. B then checks that identity's access to SalesDB and its objects. A successful connection alone does not establish permission to select from Orders. A successful direct query under your administrator login does not prove that an application's mapped identity has the same rights. Windows authentication across client, A, and B may require delegation. Review the login-mapping lesson and Microsoft's mapping and delegation documentation when configuring this path.
SQL Server 2025 adds a relevant provider consideration: Microsoft documents MSOLEDBSQL linked-server configuration using OLE DB Driver 19 and requiring an explicit encryption choice. The intended setup here uses mandatory encryption and a valid certificate trusted by A that matches the destination name. These belong to the link configuration; OPENQUERY has no encryption argument. Follow the current sp_addlinkedserver documentation, rather than mechanically copying the provider string from a different interface. An existing-link OPENQUERY request does not require enabling the Ad Hoc Distributed Queries option used for provider-based OPENROWSET.
The function takes a linked-server identifier followed by a quoted command string. Use brackets for the identifier, as in [RemoteB]. Do not copy the legacy form that supplied the server name as a single-quoted string. Run this statement while connected to A:
SELECT r.OrderID, r.CustomerID
FROM OPENQUERY([RemoteB], '
SELECT TOP (20) OrderID, CustomerID
FROM SalesDB.dbo.Orders
WHERE CustomerID = 42
ORDER BY OrderID
') AS r
ORDER BY r.OrderID;
Read the statement from the inside outward. B evaluates the command inside the quotes against its own SalesDB database. That command restricts the customer, orders matching rows by OrderID, and selects at most 20 of them. A receives a rowset with OrderID and CustomerID columns. The local alias r gives those returned columns a name that the outer SELECT can reference.
The remote object uses three parts: database, schema, and table. Do not insert [RemoteB] before SalesDB inside the quoted command. B receives that text, and the link alias defined on A has no automatic meaning there. Outside the string, RemoteB identifies the route; inside it, SalesDB.dbo.Orders identifies the destination object.
The two ORDER BY clauses have distinct jobs. The inner one determines which rows qualify for TOP. The outer one establishes the final presentation order. Because OrderID is unique in this example, it also supplies a deterministic tie breaker for selecting the subset. The TOP documentation explains why ordering matters when selecting a limited result.
No matching orders means an empty rowset. Seven matches means seven rows. Twenty returned rows means the limit was reached, not that the customer has exactly 20 orders. Nothing here counts all matching orders. These are expected interpretations of the statement, not output from a database execution performed for this lesson.
Predicate placement can change the answer as well as the amount of transferred data. Suppose the remote command instead selected the first 20 orders across every customer, and only the outer query restricted CustomerID to 42. The result would contain that customer's orders within the initial subset. It would not necessarily contain the first 20 orders belonging to that customer. Keeping the customer predicate inside the command expresses the intended selection before the remote row limit is applied.
When reviewing this example, write down the expected result contract: two named integer columns, every returned CustomerID equal to 42, no more than 20 rows, and ascending OrderID. These checks distinguish the requested behavior from an arbitrary result that happens to look plausible. They also explain why reaching the row limit is not a completeness guarantee. A report that needs every order would require a different request, rather than treating the demonstration's limit as an implicit pagination mechanism.
Suppose the report now needs customers ranked by their number of orders. Request grouped counts from B instead of asking A to receive every order and perform the grouping locally:
SELECT r.CustomerID, r.OrderCount
FROM OPENQUERY([RemoteB], '
SELECT TOP (20) CustomerID, COUNT_BIG(*) AS OrderCount
FROM SalesDB.dbo.Orders
GROUP BY CustomerID
ORDER BY OrderCount DESC, CustomerID
') AS r
ORDER BY r.OrderCount DESC, r.CustomerID;
The requested result is now up to 20 customer groups, not 20 individual orders. B calculates each count, ranks the groups, and returns the selected rows. CustomerID provides a consistent order when counts tie. COUNT_BIG produces a bigint count; keep that type in mind if a local application or destination table consumes the result.
A small returned rowset does not necessarily mean inexpensive remote work. B may need to examine many Orders rows before it can identify the largest groups. Indexes, data distribution, concurrent activity, and the remote execution plan all affect the cost. The useful distinction is that the command asks B to perform the aggregation and return its result.
Column names and types form part of the boundary between the two instances. The explicit OrderCount alias makes the calculated value accessible to the local SELECT without depending on an unnamed expression. Listing only required columns also makes the reporting dependency easier to review when the remote schema changes. If another application later adds an Orders column, this report still asks for its specified projection instead of silently widening a SELECT-star result. Schema changes affecting those specified columns still require coordinated maintenance.
A four-part-name query might also obtain an efficient distributed plan. Compare equivalent requests using representative data, the same effective identity, and matching predicates. Review transferred rows, elapsed time, and work on both instances. Do not assume OPENQUERY always outperforms an optimizer-generated distributed query, or change collation compatible merely to improve a benchmark. That setting asserts compatibility of character comparison rules and requires verification.
String literals inside the remote command need escaping because the entire command is already a local string literal. This small example isolates the issue without requiring another table:
SELECT r.ExampleName
FROM OPENQUERY([RemoteB],
'SELECT ''O''''Brien'' AS ExampleName;'
) AS r;
A removes the outer string delimiters and interprets each doubled quote as one quote character. B therefore receives SELECT 'O''Brien' AS ExampleName;. When B evaluates that command, the doubled quote inside its literal becomes an apostrophe. The expected value is O'Brien. Distinguish the source text on A, the command text received by B, and the final character value.
This is a static illustration, not a recommendation to assemble commands from arbitrary input. When an application supplies customer identifiers or other values, use an interface that binds values separately from command structure. Repeated manual escaping becomes difficult to review as statements grow.
OPENQUERY accepts a command string of at most 8 KB and does not accept variables for either argument. The size limit concerns query text, not result rows, and should not be restated as a universal 8,000-character allowance. Only the first result set is returned. These restrictions are part of the OPENQUERY function contract.
A local @CustomerID written inside the quoted command is just part of that command's text; it does not refer back to a variable declared on A. Wrapping the surrounding statement in sp_executesql does not automatically bind variables inside that nested string. Similarly, a variable containing a server name is not a substitute for OPENQUERY's linked-server identifier argument.
These constraints should influence interface selection early. A short, stable reporting command fits the examples here. A large command with many changing values suggests a parameterized remote command or an appropriately designed stored procedure. Splitting oversized SQL into several OPENQUERY calls is not automatically equivalent: each call is a separate request, and combining its results introduces additional reasoning about filters and consistency.
Consider a dashboard that requests detailed orders and customer totals separately while new orders are being entered. Treat agreement between those requests as a requirement to design and test, not an automatic property of using the same linked-server alias. Specify the intended consistency and transaction behavior before relying on the figures together. The examples here demonstrate individual reads; they do not establish a common snapshot across separate requests or a transaction policy for an application.
For a SQL Server destination and a provider supporting parameter binding, EXECUTE AT can send a command with a value placeholder. This alternative requires appropriate remote permissions and administrator-approved outgoing RPC on the link. It uses a different execution interface from the preceding OPENQUERY SELECT statements:
DECLARE @CustomerID int = 42;
EXECUTE (
'SELECT TOP (20) OrderID, CustomerID
FROM SalesDB.dbo.Orders
WHERE CustomerID = ?
ORDER BY OrderID;',
@CustomerID
) AT [RemoteB];
The question mark represents a value parameter, supplied here by the integer variable. It does not stand for a table name or linked-server identifier. The command returns its result to the caller; it is not an OPENQUERY table expression that can simply occupy a FROM clause. Microsoft's EXECUTE reference documents pass-through commands and provider parameter binding.
For a recurring business operation, a remote procedure with typed parameters can provide a maintained interface. The application then requests an operation whose implementation resides with the remote database. Choose that design when it fits ownership and deployment responsibilities; do not assume a procedure is faster merely because it is stored remotely. Revisit remote procedures and linked-server queries for the related execution context.
OPENQUERY can also be an INSERT, UPDATE, or DELETE target when the provider supports the requested operation and the remote identity is authorized. This does not make every returned rowset writable. Aggregated results such as the customer counts above should not be treated as a general update interface.
Separate OPENQUERY calls are evaluated independently. A filter on one source call does not constrain a different call used as a modification target, even when their arguments look identical. A future modification exercise must define its own target restrictions, permissions, and transaction behavior. The examples in this lesson retrieve information and make no remote data changes.
Connection ownership and the kind of result needed provide a practical starting point for choosing among the module's techniques:
| Interface | Connection information | Typical distinction |
|---|---|---|
OPENQUERY | Existing linked-server definition | Remote command returns a rowset for a local query. |
Provider-based OPENROWSET | Provider and connection values in the statement | Ad hoc provider access, subject to its configuration gates. |
| Four-part object reference | Existing linked-server definition | Distributed query whose execution plan determines work placement. |
Remote procedure or EXECUTE AT | Existing link and outgoing RPC configuration | Suitable interface for parameterized remote operations. |
For a non-SQL Server destination, the command inside OPENQUERY must use that destination's SQL dialect and supported objects. Do not assume the TOP syntax in this lesson works unchanged against another database engine. Provider availability, supported data types, and result metadata also need checking for the particular source.
Keep those provider decisions separate from the reporting requirement. First establish the columns, selection rules, ordering, and acceptable result size. Then choose the supported interface that expresses them clearly. This makes a later provider or deployment change easier to evaluate against the same business expectation.
Start by confirming that your query window is connected to A and that the intended link is visible to an authorized administrator. Check data access next. If connection initialization fails, investigate the endpoint, provider installation, encryption configuration, and certificate trust before changing SQL predicates.
Once connectivity works, identify the effective remote account and confirm its access to SalesDB.dbo.Orders. Then inspect the command as B receives it, including quotation marks and object qualification. Record both SQL Server and provider error details. Testing the inner SELECT directly on B can help isolate syntax problems, but a test under a different identity cannot validate A's login mapping.
For an initial acceptance check in a prepared environment, choose a customer whose expected orders are known. Compare the returned identifiers with that controlled expectation, then check a customer with no matching orders. This separates successful execution from verified selection behavior. Repeat the check through the intended application identity before depending on the query in a report.
Finally, separate incorrect results from slow results. Check the customer predicate, row limit, grouping, and ordering before tuning execution. For performance problems, compare equivalent workloads and inspect both sides of the connection. The module conclusion brings these querying choices together with linked-server setup and authentication.