In a previous article, we discussed what Machine Learning is and explored some of its practical applications.
Today, we continue our series of articles dedicated to Data Science, Machine Learning, and Artificial Intelligence (AI) by discussing an interesting capability of the Microsoft SQL Server Data Platform: SQL Server Machine Learning Services.
More specifically, we will explain what SQL Server Machine Learning Services are, how they work, which programming languages they support, and how you can use them to implement Data Science and Machine Learning solutions using SQL Server.
We will also examine a simple example of executing Python code through T-SQL and discuss some important architectural considerations.
Let’s get started!
What Are SQL Server Machine Learning Services?
SQL Server Machine Learning Services is a feature of Microsoft SQL Server that enables you to execute Python and R scripts using data stored in SQL Server databases.
Instead of exporting your data to a separate application or analytics environment, you can execute supported Python and R scripts through SQL Server’s extensibility framework.
This means that you can perform operations such as data preparation, statistical analysis, feature engineering, model training, and prediction generation close to where your data is stored.
For example, imagine that you have a SQL Server database containing historical sales information.
You could use Machine Learning Services to retrieve the relevant data, process it using Python, train a prediction model, and generate predictions that can be consumed by your applications or reporting solutions.
The main advantage is that you can integrate Data Science and Machine Learning operations with your existing SQL Server data platform.
However, there is one important clarification: Python and R scripts are executed in external runtime processes managed through SQL Server’s extensibility framework, not directly inside the Database Engine process.
This architecture allows SQL Server to coordinate execution and exchange data with the supported language runtimes.
For more information, you can review the official Microsoft documentation for SQL Server Machine Learning Services.
A Brief History of SQL Server Machine Learning Services
SQL Server’s Machine Learning capabilities have evolved significantly since their initial introduction.
SQL Server 2016: R Services
Microsoft introduced in-database Machine Learning capabilities with SQL Server 2016 under the name SQL Server R Services.
As the name suggests, this feature initially supported the R programming language.
R is widely used for statistical analysis, data visualization, and Machine Learning.
With R Services, developers and Data Scientists could execute R scripts using data stored in SQL Server databases.
SQL Server 2017: Python Support
With SQL Server 2017, Microsoft expanded these capabilities by introducing support for the Python programming language.
As a result, the feature was renamed from R Services to Machine Learning Services.
Python brought access to a rich ecosystem of Data Science and Machine Learning libraries, making SQL Server more attractive for developers who preferred Python over R.
SQL Server 2019: Language Extensions and High Availability
SQL Server 2019 introduced additional extensibility capabilities, including support for executing Java code through SQL Server Language Extensions.
It is important to clarify that Java support belongs to the Language Extensions feature. It is not the same thing as the R and Python support provided by Machine Learning Services.
Both capabilities use SQL Server’s extensibility framework, but they serve somewhat different purposes.
SQL Server 2019 also introduced support for Machine Learning Services on SQL Server Always On Failover Cluster Instances (FCIs).
Previously, this configuration was not supported in SQL Server 2017.
For clustered environments, the necessary Machine Learning Services components and packages must be configured according to the supported deployment requirements.
SQL Server 2022 and Later: Changes to Runtime Installation
An important change was introduced with SQL Server 2022.
Beginning with SQL Server 2022, R, Python, and Java runtimes are no longer installed automatically through SQL Server Setup.
Instead, administrators must install and configure the required supported runtimes and packages separately.
This gives administrators more control over the language runtime environment, but it also makes proper installation and configuration particularly important.
Also, some Microsoft Machine Learning packages available in earlier versions are no longer included with SQL Server 2022.
Therefore, before implementing a new solution, always verify the compatibility of your SQL Server version, language runtime, and required packages.
For detailed installation guidance, refer to Microsoft’s SQL Server 2022 Machine Learning Services installation documentation.
What Can You Do with SQL Server Machine Learning Services?
SQL Server Machine Learning Services can be used for several types of Data Science and analytical workloads.
Let’s examine some of the most common scenarios.
1. Data Preparation and Transformation
Before training a Machine Learning model, you usually need to prepare the data.
This might involve handling missing values, removing duplicate records, transforming columns, encoding categorical information, or creating new features.
With Machine Learning Services, you can combine T-SQL data retrieval and transformation with supported Python or R processing.
For example, you could retrieve customer transaction data from SQL Server and use Python to prepare the information for a prediction model.
2. Train Machine Learning Models
Machine Learning Services can also support model training.
Depending on the libraries you install and the requirements of your solution, you can implement different Machine Learning algorithms.
These might include:
- Regression: Predicting numerical values, such as future sales or product demand.
- Classification: Predicting categories, such as whether a transaction belongs to a particular risk category.
- Clustering: Grouping records according to similarities in their characteristics.
- Other analytical methods: Applying statistical and Machine Learning techniques appropriate to the available data and business problem.
The actual capabilities depend on the installed runtime, available libraries, and the resources allocated to the workload.
3. Generate Predictions
After training and evaluating a Machine Learning model, you can use it to generate predictions for new data.
For example, imagine that you have trained a model to estimate future sales based on historical information.
You could execute the relevant prediction logic through a stored procedure and return the generated results to another application.
Depending on the implementation, the trained model can be persisted and loaded for future predictions.
It is important to remember that model persistence and deployment must be designed explicitly. SQL Server does not automatically save and deploy every model created by an external script.
4. Integrate Machine Learning with Existing Applications
Another useful capability is the integration of Machine Learning operations with existing database applications.
For example, an application could call a SQL Server stored procedure that executes Python code and returns prediction results.
This approach can be useful when you already have applications that communicate with SQL Server through standard database connectivity mechanisms.
However, whether model execution should occur within the database environment or in a separate service depends on your solution’s architecture and requirements.
How Do SQL Server Machine Learning Services Work?
At a high level, SQL Server Machine Learning Services uses an extensibility architecture that connects the Database Engine with external language runtimes.
The execution process can be summarized as follows:
- An application or administrator executes a T-SQL statement or stored procedure that requests Python or R execution.
- SQL Server coordinates the request through its external script execution infrastructure.
- The SQL Server Launchpad service participates in starting and managing the external execution environment.
- The external Python or R runtime processes the supplied data using the script and available libraries.
- The results are transferred back to SQL Server and made available to the calling application or query.
The main system stored procedure used for executing Python and R code is:
sp_execute_external_script
This stored procedure allows you to specify the programming language, the script to execute, and the input data to provide.
Let’s see how this works with a simple example.
Example: Execute a Python Script Using T-SQL
Let’s assume that you have already installed and configured SQL Server Machine Learning Services with a compatible Python runtime.
Before executing Python or R scripts, external script execution must be enabled on the SQL Server instance.
An administrator with the required permissions can configure this setting using the following T-SQL commands:
EXEC sp_configure
'external scripts enabled', 1;
GO
RECONFIGURE;
GO
Depending on the SQL Server version and configuration, enabling external script execution requires restarting the SQL Server service for the change to take effect.
You must also ensure that the SQL Server Launchpad service and the relevant language runtime are correctly configured.
Security note: Enable external script execution only when required and grant execution permissions to trusted users according to your organization’s security policies.
A Simple Python Example
Now, let’s execute a Python script that performs a simple calculation using data supplied by a T-SQL query.
EXEC sp_execute_external_script
@language = N'Python',
@script = N'
OutputDataSet = InputDataSet.copy()
OutputDataSet["SquaredValue"] = (
OutputDataSet["Value"] ** 2
)
',
@input_data_1 = N'
SELECT CAST(2 AS int) AS Value
UNION ALL
SELECT CAST(3 AS int) AS Value
'
WITH RESULT SETS
(
(
[Value] int,
[SquaredValue] int
)
);
In this example, the T-SQL query provides two numerical values to the Python runtime.
The Python script creates a copy of the input dataset and calculates the square of each value.
The expected result contains the following values, although their display order is not guaranteed without an explicit ordering operation:
Value SquaredValue
----- ------------
2 4
3 9
Let’s break down the example:
@languagespecifies the external programming language to execute.@scriptcontains the Python code.@input_data_1specifies the T-SQL query that provides the input data.InputDataSetis the default variable used to receive the input dataset in Python.OutputDataSetis the default variable used to return the output dataset.WITH RESULT SETSdefines the columns and data types returned to SQL Server.
This is a deliberately simple example that demonstrates the integration between T-SQL and Python.
It does not train a Machine Learning model. Instead, it shows the basic mechanism that can also be used for more advanced analytical operations.
For a complete reference, see Microsoft’s sp_execute_external_script documentation.
Using Python and R Packages
One of the main advantages of using Python and R for Data Science is their extensive ecosystem of open-source libraries.
For example, Python libraries commonly used in Data Science include:
- pandas: Data manipulation and analysis.
- NumPy: Numerical calculations and array processing.
- scikit-learn: Machine Learning algorithms and model evaluation tools.
- Matplotlib: Data visualization.
Similarly, R offers libraries for statistical analysis, data processing, and Machine Learning.
SQL Server Machine Learning Services can also work with supported Microsoft packages, such as RevoScaleR and revoscalepy, depending on the installed SQL Server version and runtime configuration.
However, not every Python or R package is installed automatically, and not every package is compatible with every SQL Server deployment.
Furthermore, packages such as microsoftml and MicrosoftML, which were available in earlier SQL Server releases, are not included with SQL Server 2022.
This is why package compatibility and version management are important.
Installing Additional Packages
SQL Server provides different supported mechanisms for installing additional R and Python packages, depending on the version and environment.
One useful utility is sqlmlutils, an open-source project maintained on GitHub.
This utility provides capabilities for managing supported R and Python packages in SQL Server Machine Learning Services environments.
However, package installation methods differ between SQL Server versions, particularly with the runtime installation changes introduced in SQL Server 2022.
Therefore, always follow the Microsoft documentation applicable to your particular SQL Server version.
In production environments, it is also recommended to review package dependencies, licensing, security vulnerabilities, and runtime compatibility before installing additional libraries.
How Can You Implement a Data Science Project?
Now that we have discussed the capabilities of SQL Server Machine Learning Services, let’s examine the main steps involved in implementing a Data Science project.
Although every project is different, a typical Machine Learning workflow includes the following stages.
- Define the business problem: Identify what you want to achieve and how the results will be evaluated.
- Collect the required data: Identify and retrieve the relevant data from SQL Server or other authorized sources.
- Explore and prepare the data: Understand its characteristics, identify quality problems, and perform the necessary transformations.
- Perform feature engineering: Select or create relevant input features for the model.
- Split the data appropriately: Establish training, validation, and test datasets, avoiding information leakage between them.
- Select and train a model: Choose a suitable Machine Learning algorithm and train it using the training data.
- Evaluate the model: Use appropriate metrics and previously unseen test data to assess its performance.
- Deploy the model: Make the trained model available for predictions using a suitable deployment mechanism.
- Monitor and maintain the solution: Monitor model performance, data quality, and changes in the underlying data over time.
These steps form a simplified view of the Machine Learning lifecycle.
In practice, Data Science projects are usually iterative. You might need to repeat data preparation, feature engineering, or model training several times before achieving acceptable results.
Also, the evaluation of a model depends on the type of problem you are solving.
For example, classification problems might use metrics such as precision, recall, or F1-score, while regression problems might use metrics such as mean absolute error or root mean squared error.
The important thing is to evaluate your model against clearly defined business and technical requirements rather than relying only on a single accuracy metric.
Important Architectural Considerations
SQL Server Machine Learning Services offers useful capabilities, but it is not necessarily the best choice for every Machine Learning workload.
Before implementing a solution, consider the following architectural factors.
1. Resource Utilization
Machine Learning workloads can be computationally intensive.
For example, model training might consume significant CPU and memory resources.
If the same SQL Server environment is also responsible for critical transactional workloads, poorly planned analytical processing could affect application performance.
Therefore, evaluate resource usage, workload isolation, concurrency, and capacity requirements before running resource-intensive Machine Learning operations.
2. Security and Access Control
Executing external scripts introduces additional security considerations.
These include controlling who can execute scripts, which data they can access, and which packages and dependencies are installed.
Follow the principle of least privilege and use the applicable SQL Server security mechanisms to restrict external script execution.
Also, remember that processing data close to SQL Server does not automatically guarantee compliance with data protection requirements.
Data access, logging, execution isolation, and regulatory obligations must still be considered.
3. High Availability
For environments using Always On Availability Groups or Failover Cluster Instances, Machine Learning Services requires additional planning.
For example, in an Availability Groups deployment, the necessary runtime components and packages should be configured on the participating replicas where the workloads might execute.
Similarly, Failover Cluster Instance deployments must follow the supported installation and configuration procedures.
The database failover mechanism alone does not guarantee that all external runtime dependencies will be available after failover.
4. In-Database vs. External Machine Learning
One important architectural decision is whether to execute Machine Learning workloads close to the SQL Server data or in a dedicated Machine Learning environment.
In-database execution can be useful when:
- The required data is already stored in SQL Server.
- You want to reduce unnecessary data movement.
- Your workloads can operate within the available infrastructure resources.
- You want to integrate prediction logic with existing SQL Server applications and stored procedures.
On the other hand, external Machine Learning services might be more appropriate when:
- You need specialized computing resources, such as GPUs.
- You want to scale model training and inference independently from the database.
- Your solution requires dedicated model deployment, monitoring, and lifecycle management.
- You want to isolate intensive Machine Learning operations from production database workloads.
Modern platforms also support architectures where SQL Server remains the system of record while dedicated services handle model training and predictions.
For SQL Server 2025, Microsoft has also introduced additional AI-related database capabilities, including vector data support and vector functions. These capabilities serve different purposes and should not be confused with the execution of Python and R scripts through Machine Learning Services.
The main recommendation is to choose the architecture based on your business and technical requirements, rather than assuming that all Machine Learning workloads should run inside the database environment.
What About Azure SQL Managed Instance?
An important distinction should also be made between SQL Server and Azure SQL Managed Instance.
Machine Learning Services has been available in Azure SQL Managed Instance, but its availability depends on the instance’s SQL Server update policy.
According to Microsoft’s current documentation, Machine Learning Services is available on Azure SQL Managed Instances configured with the SQL Server 2022 update policy.
It is not available with the SQL Server 2025 or Always-up-to-date update policies.
Therefore, if you are designing a new Azure SQL Managed Instance solution, verify the supported features and update-policy requirements before deciding to use in-database Python or R execution.
For additional information, see Microsoft’s Machine Learning Services differences for Azure SQL Managed Instance.
Watch a Free Lesson: What Is Data Science?
If you are new to Data Science and Machine Learning, you can also watch the following introductory video lecture.
The lesson discusses Data Science fundamentals and provides useful background before getting started with SQL Server Machine Learning Services.
Watch the original video lecture on YouTube.
Concluding Remarks
SQL Server Machine Learning Services provides an interesting way to combine relational database technologies with Data Science and Machine Learning.
By supporting Python and R execution through SQL Server’s extensibility framework, it allows developers and Data Scientists to perform analytical operations using data stored in SQL Server databases.
As we discussed, these capabilities can be useful for data preparation, statistical analysis, model training, prediction generation, and integration with existing applications.
However, it is important to understand that Machine Learning Services requires proper installation, configuration, security, and resource management.
Furthermore, the available runtimes, packages, and deployment options depend on your SQL Server version and target platform.
Finally, remember that Machine Learning Services is one possible approach to implementing Machine Learning solutions, not the only one.
The most important thing is to select the technology and architecture that best support the requirements of your Data Science project.
Hope this helps!
References
- Microsoft Learn – What Are SQL Server Machine Learning Services?
- Microsoft Learn – What’s New in SQL Server Machine Learning Services?
- Microsoft Learn – sp_execute_external_script (Transact-SQL)
- Microsoft Learn – Java Language Extension in SQL Server
- Microsoft Learn – SQL Server Extensibility Architecture
Continue learning
If you want a structured next step in artificial intelligence fundamentals, explore my AI Essentials: A Beginner’s Guide to Artificial Intelligence course on Udemy. Review the curriculum and available preview lessons to see whether it matches your level and learning goal.
View the course and current offer. Pricing and coupon availability are determined on Udemy.
Read Also
- What Is Machine Learning?
- What Is Data Science?
- Introduction to SQL Server Machine Learning Services (Course Preview)
- What Is Data Management and Why Is It Important?
- AI Essentials: A Beginner’s Guide to Artificial Intelligence
Stay Connected
Subscribe to the GnoelixiAI Hub Newsletter on LinkedIn for practical insights on AI, data, and technology.
Watch more on YouTube: SQLNetHub TV and my personal channel.
Originally published on SQLNetHub.
© SQLNetHub
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.