Query External Data Sources

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 9 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Querying External Data Sources in Azure Synapse Analytics

Introduction: Bridging the Gap Between Storage and Insight

In the modern data landscape, organizations rarely keep all their information in a single, centralized database. Instead, data is spread across various storage solutions, ranging from data lakes and cloud storage accounts to third-party APIs and legacy systems. Azure Synapse Analytics provides a powerful capability to query this distributed data without needing to move it into a dedicated data warehouse first. This process, often referred to as "querying external data," is fundamental for data engineers and analysts who need to perform exploratory analysis, build data pipelines, or create virtualized data layers.

Why does this matter? Moving massive volumes of data (the Extract-Load-Transform or ELT process) is time-consuming, expensive, and introduces latency. By querying external data sources directly where they reside, you can gain immediate insights, validate data quality before ingestion, and reduce the overhead of managing complex ETL infrastructures. This lesson explores how to use T-SQL within Azure Synapse to interface with external data, the underlying architecture required to make these connections, and the best practices for maintaining performance and security.


Not read yet

Understanding the Architecture of External Data Queries

To query external data in Azure Synapse, you aren't just pointing a SQL query at a file. The system requires a set of metadata objects that act as a bridge between the SQL engine and the physical storage. This architecture relies on three primary components:

  1. External Data Source: This object defines the location of your data, such as a specific Azure Data Lake Storage (ADLS) Gen2 container or a specific folder path.
  2. External File Format: This tells the SQL engine how to interpret the data. It specifies whether the file is CSV, Parquet, JSON, or another format, and includes settings for row terminators, field delimiters, and compression types.
  3. External Table: This is the virtual representation of the data. Once defined, you can query an external table using standard SELECT statements, and the engine will handle the file access, schema mapping, and data retrieval in the background.

By decoupling the data location from the table definition, you gain flexibility. If the underlying data files change or move to a different folder within the same container, you only need to update the definition of the data source or the table, rather than rewriting your core analytics queries.


Not read yet

Step-by-Step: Setting Up External Data Access

Before you can run a query, you must establish the necessary permissions and metadata objects. This process follows a logical flow from security configuration to table definition.

Step 1: Configure Security and Permissions

Azure Synapse uses Managed Identities or Shared Access Signatures (SAS) to authenticate with external storage. The most secure approach is using the Synapse Workspace Managed Identity. You must grant this identity the "Storage Blob Data Contributor" role on the specific storage account containing your data. Without this, the SQL engine will return an access denied error, regardless of how well-written your query is.

Step 2: Create the Master Key and Database Scoped Credential

Even if you use a Managed Identity, creating a credential object is often necessary if you are using specific authentication tokens or need to manage access at a granular level.

-- Create a Master Key to secure credentials
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'YourStrongPassword123!';

-- Create a credential if using SAS tokens (optional but common)
CREATE DATABASE SCOPED CREDENTIAL [MyStorageCredential]
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = 'sv=2020-08-04&ss=b&srt=sco&sp=rl&se=2023-12-31T00:00:00Z&sig=...';

Step 3: Define the Data Source and File Format

Next, you define where the files are and how they are structured.

-- Define the location of the data
CREATE EXTERNAL DATA SOURCE [MyDataLakeSource]
WITH (
    LOCATION = 'https://mystorageaccount.dfs.core.windows.net/mycontainer',
    CREDENTIAL = [MyStorageCredential] -- Use this if not using Managed Identity
);

-- Define the file format (Parquet is recommended for performance)
CREATE EXTERNAL FILE FORMAT [ParquetFileFormat]
WITH (
    FORMAT_TYPE = PARQUET,
    DATA_COMPRESSION = 'org.apache.hadoop.io.compress.SnappyCodec'
);

Step 4: Create the External Table

Finally, you define the schema. This maps the columns in your files to SQL data types.

CREATE EXTERNAL TABLE [dbo].[CustomerData] (
    [CustomerID] INT,
    [FirstName] VARCHAR(100),
    [LastName] VARCHAR(100),
    [Email] VARCHAR(255)
)
WITH (
    LOCATION = 'customers/*.parquet',
    DATA_SOURCE = [MyDataLakeSource],
    FILE_FORMAT = [ParquetFileFormat]
);

Callout: External Tables vs. OPENROWSET While External Tables provide a permanent, reusable schema, the OPENROWSET function allows for ad-hoc queries without creating metadata objects. Use External Tables when you need to query the same data repeatedly or expose it to reporting tools like Power BI. Use OPENROWSET for one-off data exploration or quick validation of incoming files.


Not read yet

Querying Data with OPENROWSET

Sometimes, you don't want to define a formal table. Perhaps you have a new file landing in a landing zone, and you need to perform a quick "sanity check" to see if the schema is correct. This is where OPENROWSET shines. It allows you to query files directly using SQL syntax.

Basic Syntax for Ad-hoc Queries

SELECT TOP 10 *
FROM OPENROWSET(
    BULK 'https://mystorageaccount.dfs.core.windows.net/mycontainer/sales_data.csv',
    FORMAT = 'CSV',
    PARSER_VERSION = '2.0',
    HEADER_ROW = TRUE
) AS [result];

The PARSER_VERSION = '2.0' is critical here, as it enables the improved CSV parser which handles complex delimiters and quoted strings much more effectively than the legacy version. Always specify the HEADER_ROW = TRUE option if your CSV files contain headers, otherwise, the first row of data will be incorrectly interpreted as column names.

Inferring Schema

One of the most powerful features of OPENROWSET is schema inference. By omitting the column definitions, you can let Synapse guess the data types:

SELECT *
FROM OPENROWSET(
    BULK 'https://mystorageaccount.dfs.core.windows.net/mycontainer/data.parquet',
    FORMAT = 'PARQUET'
) AS [data];

While convenient, schema inference can be risky in production environments. If a file contains a column with inconsistent data types (e.g., a "ZipCode" column that is mostly numeric but contains a stray alphanumeric entry), the inference engine might choose a data type that causes later failures. For production pipelines, always explicitly define your schema using the WITH clause.


Not read yet

Performance Best Practices

Querying external data is inherently slower than querying internal tables because of the network latency associated with reading from storage and the overhead of interpreting files on the fly. To optimize performance, follow these industry-standard practices.

1. Use Parquet Format

Parquet is a columnar storage format that is highly optimized for analytical queries. Unlike CSV, which requires the engine to read the entire file to find specific columns, Parquet allows the engine to perform "column projection." This means if your query only selects three columns, the engine only reads those specific columns from the file, significantly reducing I/O.

2. Implement Partitioning

If you have data stored in a folder structure like /year=2023/month=10/, you can leverage partition pruning. When you query the data, include the partition columns in your WHERE clause. The engine will intelligently skip folders that don't match your criteria, saving massive amounts of time and compute resources.

3. Use Statistics

The SQL engine uses statistics to determine the most efficient way to join tables and filter data. By default, Synapse does not automatically create statistics on external tables. You should manually create them:

CREATE STATISTICS [Stats_CustomerID] ON [dbo].[CustomerData] ([CustomerID]);

4. Minimize Data Transfer

Always filter data as early as possible. Use WHERE clauses to restrict the rows and SELECT to restrict the columns. Avoid SELECT * in production code. The more data you pull across the network, the slower your query will be.


Not read yet

Comparison Table: External Tables vs. OPENROWSET

Feature External Tables OPENROWSET
Persistence Permanent metadata object Ad-hoc (transient)
Ease of Use High (once configured) High (quick start)
Performance Optimized (can use statistics) Moderate
Best For Reporting, production pipelines Exploration, data validation
Schema Management Explicit/Rigid Flexible/Inferred

Common Pitfalls and How to Avoid Them

Pitfall 1: File Encoding Issues

CSV files often come with different encodings (UTF-8, UTF-16, etc.). If your query returns garbled text or fails to parse, check the file encoding. The OPENROWSET function supports various CODEPAGE settings, but standardizing your incoming files to UTF-8 is the most effective long-term solution.

Pitfall 2: Over-reliance on Schema Inference

As mentioned, relying on the system to guess data types leads to fragile pipelines. If a downstream process expects an INT but the inference engine interprets a column as VARCHAR because of a leading zero, your downstream calculations will fail. Always use an explicit schema definition for any table that feeds a dashboard or a critical report.

Pitfall 3: Security Misconfigurations

Granting broad access to the entire storage account is a common mistake. Use the principle of least privilege. Create specific folders for specific roles or applications and grant the Managed Identity access only to the necessary container or folder path.

Pitfall 4: Ignoring File Sizing

Querying thousands of tiny files is significantly slower than querying a few larger files. This is due to the overhead of opening and closing connections for each file. If your data ingestion process creates many small files, implement a "compaction" process that periodically merges these small files into larger, optimized Parquet files.

Warning: Schema Drift If the source system adds a new column to the data files, your External Table definition will not automatically update. Your queries will continue to work, but the new column will be ignored. If you need to include new data, you must run an ALTER EXTERNAL TABLE statement or recreate the table. Monitor your source systems to ensure your metadata stays in sync.


Not read yet

Advanced Querying: Handling Complex Data Types

Modern data often includes nested structures, such as JSON objects within Parquet files. Synapse allows you to query these structures using path-based syntax. If you have a column named User that contains an object with a Name field, you can access it like this:

SELECT [User].Name
FROM [dbo].[JsonData]

This capability makes Synapse an excellent tool for semi-structured data analysis. You don't need to "flatten" your data before loading it into your environment. You can query the hierarchy directly, which is particularly useful for logs, telemetry data, or API responses.

Working with Multiple Files

You can use wildcards in your LOCATION definition to capture multiple files at once. For example, location = 'sales/*.parquet' will include every file within the sales folder. This is powerful for time-series data where new files are added daily.


Troubleshooting Connectivity

When a query fails, the error message is your primary source of truth. Most errors fall into three categories:

  1. Authentication Errors: These usually involve the Managed Identity lacking the "Storage Blob Data Contributor" role. Verify this in the Azure Portal under the Access Control (IAM) tab of the storage account.
  2. Parsing Errors: These occur when the file structure doesn't match the EXTERNAL FILE FORMAT definition (e.g., a tab-delimited file being read as a comma-delimited file).
  3. Path Errors: These occur when the LOCATION string is incorrect. Remember that the DATA_SOURCE location and the EXTERNAL TABLE location are concatenated. If your data source points to the root container, your table location should be the relative path.

If you are unsure why a query is failing, try running a simple SELECT TOP 1 * using OPENROWSET on the specific file path. This isolates the file access from the table metadata and helps you determine if the issue is with the file itself or your table configuration.


Not read yet

Industry Best Practices for Data Governance

Managing external data requires a disciplined approach to governance. As your environment grows, you will inevitably end up with "data swamps"—collections of unmanaged, undocumented files.

  • Implement a Naming Convention: Use a consistent naming convention for your external tables (e.g., ext_source_table). This makes it easy to distinguish them from internal tables.
  • Documentation as Code: Store your table creation scripts in source control (like GitHub or Azure DevOps). This ensures that if you need to recreate your environment, you have a repeatable process.
  • Regular Audits: Periodically review the external data sources to ensure they are still being used. Remove unused credentials and external tables to reduce the security surface area.
  • Data Quality Checks: Since you do not control the source files, implement automated checks. Use a separate process to validate the schema and data quality of files before they are exposed to end-users through external tables.

Not read yet

Key Takeaways

  1. Direct Querying Efficiency: Querying external data allows you to bypass the time-consuming ETL process, providing faster access to data for exploratory analysis and virtualization.
  2. Metadata is Essential: External tables, data sources, and file formats provide the necessary mapping between the SQL engine and your physical storage, ensuring that the engine knows how to interpret the data.
  3. Performance Optimization: Always prefer Parquet over CSV for analytical queries. Use partitioning and statistics to ensure that your queries run efficiently as your data volume grows.
  4. Security First: Use Managed Identities to authenticate with storage accounts. Avoid hardcoding passwords or SAS tokens in your scripts whenever possible.
  5. Schema Consistency: While schema inference is useful for ad-hoc exploration, always define explicit schemas for production-grade tables to avoid failures caused by data drift.
  6. File Management: To maintain high performance, avoid querying thousands of small files. Implement a compaction strategy to merge small files into larger, optimized blocks.
  7. Tooling Selection: Understand the distinction between OPENROWSET for ad-hoc tasks and EXTERNAL TABLE for permanent, reusable reporting layers.

By mastering these concepts, you shift your focus from managing data movement to extracting value from the data itself. You become an enabler for your organization, providing the agility to query and analyze data wherever it resides, while maintaining the rigor and security required for enterprise-grade analytics. Continue to experiment with these features in a development environment, and always prioritize clear, documented code to ensure your data pipelines remain maintainable and scalable.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.