SQL Server CAST() Function Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report In SQL Server, manipulating data is a fundamental aspect of database management. Often, you'll find yourself needing to transform data from one type to another, either for calculations, comparisons, or presentation purposes. This is where the CAST() function comes. In this article, we will learn about the CAST() function in SQL Server, which is used to convert a value from one data type to another. What is the CAST() Function?The SQL server CAST() function allows you to explicitly convert data from one data type to another. Whether you need to change a string to a number, adjust the precision of a decimal, or alter the format of a date, the CAST() function provides the flexibility to manipulate your data to meet specific requirements. Understanding how to use this function effectively can streamline your data management processes and enhance the accuracy of your database queries. The syntax of the CAST() function is as follows: CAST ( expression AS data_type [ ( length ) ] )Here: expression represents the value to be converted.data_type denotes the target data type to which the expression will be converted.length (optional) specifies the length of the target data type, particularly relevant for character data types like VARCHAR. The default value is 30.The CAST() function can convert values of any data type to one of the following data types: bigint, int, smallint, tinyint, bit, decimal, numeric, money, smallmoney, float, real, datetime, smalldatetime, char, varchar, text, nchar, nvarchar, ntext, binary, varbinary, or image. Examples of Using the CAST() FunctionLet's see some examples of how to use the CAST() function in SQL Server. Example 1: Convert a String Value to an IntegerSuppose we have a decimal value '123' and we want to convert it to an integer. We can use the CAST() function as follows: SELECT CAST('123' AS INT) AS IntegerValue;Output: Convert String to Integer using Cast() functionExplaination: In this Example, The provided SQL query uses the CAST function to convert the string '123' to an integer. The result, named IntegerValue, is the integer representation of the given string, which is 123. Example 2: Convert a String Value to a DateSuppose we have a date value 2024-02-08' and we want to convert it to a varchar. We can use the CAST() function as follows: SELECT CAST('2024-02-08' AS DATE) AS ConvertedDate;Output: Convert String to Date using Cast() functionExplaination: In this Example a string representing a date('2024-02-08') is cast to the DATE data type. Example 3: Convert a Integer Value to an Bit ValueSuppose we have a Integer value 1 and we want to convert it to a Bit. We can use the CAST() function as follows: SELECT CONCAT('The bit value is: ', CAST(1 AS bit)) AS BitValue;Output: Convert Integer to Bit using Cast() functionExplaination: In the provided example, we're using the CONCAT() function along with the CAST() function to create a string that includes both text and a converted value. CAST() function convert the integer value 1 to a bit data type ConclusionThe CAST() function in SQL Server is a versatile tool for data transformation tasks. By understanding its usage and syntax, you can seamlessly convert data between different types to suit your specific needs. Its ability to transform data types with precision and control enhances the flexibility and efficiency of database operations. Whether it's converting strings to numbers, adjusting decimal precision, or handling other data type conversions, CAST() empowers SQL developers to tackle diverse data challenges with ease. Comment More infoAdvertise with us C chintantogadiya Follow Improve Article Tags : SQL Server Databases SQL Server Query Similar Reads SQL Server BasicsIntroduction of MS SQL ServerData is a collection of facts and figures and we have humungous data available to the users via the internet and other sources. To manipulate the data, Structured Query Language (SQL) in short has been introduced years ago. There are different versions of SQL available in the market provided by diff2 min readCreate Database in MS SQL ServerDatabases in Microsoft SQL Server are crucial for managing data, categorized into system databases, which are auto-created and user databases, created by users. In this article, We will learn about the basics of system and user databases along with methods for creating and managing them using T-SQL5 min readList All Databases in SQL ServerIn SQL Server, databases are crucial for storing and managing data efficiently. Whether we are managing a large enterprise system or a small application, understanding how to list all the databases on our SQL Server is essential. In this article, we will write SQL queries that help us to retrieve al3 min readSQL Data TypesIn SQL, each column must be assigned a data type that defines the kind of data it can store, such as integers, dates, text, or binary values. Choosing the correct data type is crucial for data integrity, query performance and efficient indexing.Benefits of using the right data type:Memory-efficient3 min readSQL Server Tables & SchemasCREATE TABLE in SQL ServerSQL Server provides a variety of data management tools such as querying, indexing, and transaction processing. It supports multiple programming languages and platforms, making it a versatile RDBMS for various applications. With its robust features and reliability, SQL Server is a popular choice for4 min readSQL Server Table VariableSQL Server Table variable is a local variable that stores data temporarily, similar to the temporary table in SQL Server. Tempdb database is used to store table variables. How to Declare Table Variable in SQL ServerTo declare a table variable in SQL Server, start the DECLARE statement. The name of t2 min readSQL Server DROP TABLEIn SQL Server, the DROP TABLE statement is used to remove or delete permanently from the database. In SQL Server after performing the DROP Operation we cannot revoke the table or database again, because it is an irreversible action. The Drop Operation is different from the DELETE Command, In the DEL3 min readRename Column in SQL ServerSQL Server is a widely used Relational Database Management System (RDBMS) that allows users to create and manage databases effectively. Renaming a column in a database is a common task usually required when users want to change the database schema. In this article, we will explore different methods3 min readSQL Server Rename TableIn SQL Server, renaming tables is a frequent operation that we often require during database maintenance or schema changes. This article ensures your seamless transition through the table-renaming process without compromising data integrity. it provides comprehensive guidance and guarantees protecti3 min readCREATE SCHEMA in SQL ServerA schema is a collection of database objects like tables, triggers, stored procedures, etc. A schema is connected with a user which is known as the schema owner. The database may have one or more schema. To create a schema in SQL Server use the 'CREATE SCHEMA' Statement. SQL CREATE SCHEMACREATE SCHE2 min readSQL Server Queries & OperationsSelect Statement in MS SQL ServerThe SELECT statement in SQL Server is a foundational SQL command used for querying and retrieving data from one or more tables within a database. This command allows users to specify which columns and rows to retrieve and apply filters to focus on specific data and perform various operations to mani4 min readInsert Statement in MS SQL ServerThe SQL Server INSERT statement is a fundamental command used to add new rows of data to a table. Whether we are inserting specific values, utilizing default values or copying data from another table.In this guide, weâll explore various ways to use the Insert statement in MS SQL Server with the help4 min readSQL Server UPDATESQL Server is a database engine. It works on the relational database management system (RDBMS) that allow programmer to create, manage, and manipulate data present on the relational database through their commands which is easy to learn and implement. UPDATE CommandThe UPDATE operation is a part of3 min readDELETE Statement in MS SQL ServerThe DELETE statement in MS SQL Server deletes specified records from the table. SyntaxMS SQL Server DELETE statement syntax is: DELETE FROM table_name WHERE condition; Note: Always use the DELETE statement with WHERE clause. The WHERE clause specifies which record(s) need to be deleted. If you exclu1 min readSQL Server SubqueryIn SQL Server, Subqueries are a powerful feature used to perform complex queries and combine data from multiple tables or multiple data sets. Subqueries can be used in different business cases and in different scenarios to join data from an inner query with an outer query. In this article let us see5 min readJoins in MS SQL ServerA database comprises tables and each table in case of RDBMS is called a relation. Let us consider a sample database named University and it has two tables named Student and Marks. If a user wants to transfer a certain set of rows, insert into select statement is used along with the query. But if a u2 min readRollup in SQL ServerThe ROLLUP operator enhances the capabilities of the GROUP BY clause by enabling the computation of subtotals and grand totals for a set of columns. It produces a result set that incorporates rows at various levels of aggregation. ROLLUP streamlines the aggregation process by eliminating the need fo4 min readSQL Server PIVOTSQL Server relational database management system. It has core functions that create, manipulate, and store data very efficiently. SQL Server contains all these characteristics and it has an extremely user-friendly installation interface, unlike other database servers that require extensive command-l7 min readSQL Server Constraints & KeysSQL PRIMARY KEY ConstraintThe PRIMARY KEY constraint in SQL is one of the most important constraints used to ensure data integrity in a database table. A primary key uniquely identifies each record in a table, preventing duplicate or NULL values in the specified column(s). Understanding how to properly implement and use the5 min readForeign key in MS SQL ServerA foreign key in SQL Server plays a crucial role in establishing and enforcing relationships between tables. It is a column or a set of columns in a table that references the primary key or a unique key in another table. By using foreign key constraints the SQL Server keeps data consistent between r6 min readCascading Referential Integrity Constraints in SQL Server Management StudioIn the Microsoft SQL server if we want to delete any record or column from one table but that record or column is a foreign key for another table then we will get the error to solve this problem we use Cascading referential integrity constraint. It allows the actions that SQL Server should take when4 min readHow to Turn IDENTITY_INSERT On and Off Using SQL Server?IDENTITY_INSERT in SQL Server is a valuable tool in SQL Server 2008, allowing us to control how identity values are assigned when inserting new records into a table. IDENTITY_INSERT ON is a Transact-SQL statement that allows us to explicitly specify the value we want to insert into the identity colu6 min readCan a Foreign Key be NUll in SQL Server?In SQL Server, foreign keys are essential to maintaining relationships between tables and enforcing referential integrity. A foreign key is a column (or set of columns) in a child table that references a primary key in a parent table and ensures that the data in both tables remains consistent. Howev4 min readSQL Server Indexes & PerformanceSQL IndexesAn index in SQL is a schema object that improves the speed of data retrieval operations on a table. Imagine them like an index in a book instead of flipping through every page (row), the database can jump right to the data it requires.Works by creating a separate data structure that provides pointer6 min readSQL Server CHARINDEX() functionCHARINDEX() function in SQL Server returns the position of a substring within a given string. The search performed in this function is case-insensitive. SyntaxCHARINDEX function syntax is: CHARINDEX(substring, string, [starting_position] ParametersCHARINDEX function accepts 3 parameters: substring:2 min readSQL Server SUBSTRING() FunctionThe SQL Server SUBSTRING function extracts a substring from a string, starting at a specified position and with an optional length. The SUBSTRING function also works in Azure SQL Database, Azure SQL Data Warehouse, and Parallel Data Warehouse. SyntaxThe SQL SUBSTRING function syntax is: SUBSTRING(in3 min readSQL Query OptimizationsPoorly written SQL queries can result in slow performance, high resource costs, locking and blocking issues, and unhappy users. The following are common practices that can be used to write efficient queries.1. Use Indexes WiselyIndexes let the database quickly look up rows instead of scanning the en6 min readHigh Availability (HA) in SQL ServerIt is the solution or process or technology to make the service or application or database availability 24x7 and 100% through needless and fault-tolerant components at the same location under either planned or unplanned outages. There are mainly five options in MS SQL Server to setup high availabili5 min readSQL Server Advanced TopicsDateTime2 vs DateTime in SQL ServerIn SQL Server, managing date and time values for various applications ranging from transaction processing to reporting. SQL Server offers two main data types for handling date and time:DateTimeDateTime2While both serve similar purposes, they differ significantly in terms of precision, storage requir3 min readDifference Between DateTime and SmallDateTime in SQL ServerSQL Server datatypes are used to store date and date and time values in the database, there are various types of date data types available in the SQL. Whenever we manage data in the SQL server database, itâs often very important to choose the right to store the date and time. The following two data3 min readFind Referencing Entities in SQL ServerUnderstanding the relationship between different object entities is very crucial in complex databases because changes in any object can affect the overall database. The SQL Server provides a very effective dynamic management function known as sys.dm_sql_referencing_entities which helps the user to t9 min readExport SQL Server Data From Table to CSV FileSQL Server is a very popular relational database because of its versatility in exporting data in Excel, CSV, and JSON formats. This feature helps with the portability of data across multiple databases. Here, we will learn how to export SQL Server Data from a table to a CSV file. Tools like Azure Dat3 min readHow to Setup Compatibility in Microsoft SQL Server?In SQL Server, managing the compatibility level of a database is crucial for ensuring that your database operates with the appropriate features and behaviors for your application. Compatibility levels allow us to use features and syntax from specific versions of SQL Server while running your databas4 min read Like