Tag Archives: DBA

Articles for the DBA – accidental or otherwise

CAST v/s CONVERT – Is there a difference as far as SQL Server is concerned? Which is better?


Data type conversion has been one of the most used features of any programming language. Microsoft SQL Server users are familiar with the two functions: CAST() and CONVERT() and use them regularly, and more specifically, interchangeably. A few months ago, I had written a post comparing the performance of CAST v/s CONVERT, and was able to prove that there is no difference in performance of the two functions.You can read that post here: https://nakulvachhrajani.com/2011/01/03/cast-vs-convert/.

Recently, a colleague and I were discussing a particular design element and found that a data type casting was required. During this discussion, the following questions almost simultaneously came to our minds –

  • If the performance and end results are the same, what is the difference between CAST & CONVERT aside from the fact that they have different syntax elements?
  • Do we really need 2 data conversion functions?
Parameter CAST CONVERT
ANSI standard Yes No
Data-type coverage Limited Full (Date & Date Time values supported)
Performance No difference No difference
Microsoft SQL Server implementation ?? ??
Books On Line Page http://msdn.microsoft.com/en-us/library/ms187928.aspx http://msdn.microsoft.com/en-us/library/ms187928.aspx

So, I ran a little test, and today, I will share with you my findings.

The CAST v/s CONVERT Test

The test is quite simple – we have two identical T-SQL statements, one using CAST, the other using CONVERT. We will use the Properties window of SSMS to analyze the execution plan and try to see what can be found about the underlying implementation.

Let’s take a look at our test statements:

/***********************************************************
Press Ctrl+M (or go to Query->Include Actual Execution Plan)
************************************************************/
USE AdventureWorks2008R2
GO
--Use CONVERT
select CONVERT(VARCHAR(10),BusinessEntityID) FROM HumanResources.Employee

--Use CAST
select CAST(BusinessEntityID AS VARCHAR(10)) FROM HumanResources.Employee
  1. Connect to your SQL Server instance using SQL Server Management Studio (SSMS)
  2. Copy the T-SQL code above into SSMS Query editor window
  3. Run the above T-SQL statements against your SQL Server instance
  4. Change over to the Execution Plan tab in the Results pane
  5. In the results pane, notice that both CAST & CONVERT have been implemented as “Compute Scalar” operators
  6. image
  7. Press the F4 key or go to View –> Properties to launch the properties window
  8. Expand the “Defined Values” node

CONVERT implementation

CONVERT does not come up with any surprises, and has a straightforward internal implementation as demonstrated in the Properties window.

image

CAST implementation

When we move to the properties for the query using the CAST operation, we see that under the hood, SQL Server does take us for a ride. Internally, CAST is implemented as a CONVERT call. There is no difference between CAST & CONVERT besides the fact that CAST is an ANSI standard, while CONVERT is not. No wonder both CAST & CONVERT demonstrate the same performance.

image

Surprised? Try it for yourself – I was not prepared to see what I saw when I first ran through the test. I restarted the entire server and got a cup of coffee to make sure I was not dreaming!

Conclusion

I guess all I need to do now is to complete the little grid I had above:

Parameter CAST CONVERT
ANSI standard Yes No
Data-type coverage Limited Full (Date & Date Time values supported)
Performance No difference No difference
Microsoft SQL Server implementation CONVERT CONVERT
Books On Line Page http://msdn.microsoft.com/en-us/library/ms187928.aspx http://msdn.microsoft.com/en-us/library/ms187928.aspx

What would I recommend?

Although we now know that to Microsoft SQL Server, data type conversion only happens via CONVERT, I would still prefer to go with CAST unless I am converting dates or date-time values. The reason being CAST is an ANSI standard, CONVERT is not. CONVERT is implementation specific, and therefore may change in terms of the number of parameters or underlying processes. To the calling T-SQL statement, it is safe to assume that CAST would remain unchanged (unless the standard changes) and therefore, it would be the responsibility of Microsoft SQL Server to translate the CAST to a CONVERT implementation.

Do share your thoughts on the whole CAST v/s CONVERT myths and controversies floating around in the SQL Server world. I will be more than happy to research more and share my findings with you.

Until we meet next time,

Be courteous. Drive responsibility.

Getting started with Contained Databases in SQL 11 (“Denali”) – Part 01 – An Introduction


As you know, I had visited Tech-Ed 2011 (India) last month. The last day of Tech-Ed was a special day for DBAs because we had a dedicated DBA track – and to add to it, we had a power packed hands-on lab from Jacob Sebastian and break-out sessions from Pinal Dave, Vinod Kumar, Prem Mehra and Balmukund Lakhani. You can read all about Tech-Ed Day 03 at my post here.

For this week, I will be sharing with you the content of the hands-on lab on “Contained Databases in SQL 11 (“Denali”)” from Tech Ed. The hands-on lab was conducted by Jacob Sebastian.

Database containment – the current situation

What does a typical day in the life of the DBA (especially in a development shop) consist of? Let me list a few of these activities down:

  1. Create new databases
  2. Setup database options
  3. Create Logins on the SQL Server and assign permissions to various objects
  4. Move databases across SQL Servers
  5. Repeat the same steps on demand

SQL Server is huge, and there are a variety of objects and tasks to be done within the server. Unfortunately, these objects and tasks are spread all over the entire product, which leads to the following disadvantages:

Database Deployment

This is the most feared situation – it is the time when an application is moved from one instance to another. When this movement happens, some part of the application’s data (eg. the logins and agent job information) is left behind.

The DBA must then painstakingly recreate and map each login to required database users on the new instance. Maintenance and other SQL Agent jobs also need to be recreated on the new instance. Depending upon the number of such operations to be carried out, this process is time-consuming and error-prone.

Application Development

Application development has to currently keep into consideration the finer points of the final deployment/production environment. Database and server configuration and deployment scenarios are no longer isolated. It is quite possible that some of the dependencies and conditions that application developers assumed to be available may not be true (eg. the availability of the “sa” login, permissions to create new logins on the server, or “xp_cmdshell” being enabled).

Another major influencer in application development is the collation of the database. Since this is initially determined by the server collation, developers need to constantly ensure that the collation is exactly as required by the application.

Such situations take the focus away from application development and instead divert it to application deployment, which should not be the case.

Application Administration

Because logins and agent jobs are spread across the instance and the database, administration is a virtual nightmare. In high-security enterprise class installations, the need to administer a single database typically requires that the user be granted permissions to the entire instance – thus providing access to many other databases to which the user has no relation with.

Contained Databases – The solution

There exists a distinct boundary between the multiple areas of any application:

  1. Application boundary – the boundary between the application code and functionality and the server instance
  2. Application Model – inside the application boundary, this is where applications are developed and managed
  3. Management Model – outside of the application boundary, this is where instance-level management happens

Here is how you may classify some of the objects into Application model & Management model:

Application Model Management Model
System tables like sys.tables Instance level system tables like sys.endpoints
Database users and passwords Database server logins
Database server login and database user mapping
User tables in the current database
(i.e. referenced by a 2-part name)
User tables in another database
(i.e. referenced by a 3-part name)

Once these boundaries are defined, and the objects completely contained within these boundaries, they will become independent of the objects on the other side of the boundary.

A “Contained Database” paradigm ensures:

  1. Simplified database movement
  2. Application development environment independent of the deployment environment considerations
  3. More granular, yet powerful administrative groups possible

SQL 11 (“Denali”) and Contained Databases

As of SQL 11 (“Denali”) CTP 01, SQL Server supports the concept of “Contained databases”. Here’s how you can define contained database:

“A contained database has no external dependencies on server-based settings or metadata to define the database. Users defined in a contained database do not have a dependency on logins created on the server, and therefore contain all information necessary to authenticate a user within the database.”

By default, this feature is turned OFF, meaning everything is just as it was before, i.e. “uncontained”.

Tomorrow, we will soon see how to turn Contained Database support ON, and also create a new contained database, after which we will see how to migrate a contained database across severs, and finally, how to convert your non-contained database to a contained one.

You can understand more about Contained Databases at: http://msdn.microsoft.com/en-us/library/ff929071(SQL.110).aspx

Until tomorrow,

Be courteous. Drive responsibly.

CAST v/s CONVERT


Data type conversion has been one of the most used features of any programming language. Microsoft SQL Server users are familiar with the two functions: CAST() and CONVERT() and use them regularly, and more specifically, interchangeably.

However, using CAST() and CONVERT() interchangeably is one of the most capital mistakes that a developer can make. Madhivanan, a SQL Server blogger on BeyondRelational.com (http://beyondrelational.com/blogs/madhivanan/default.aspx) does a very good job at highlighting the differences between CAST() and CONVERT() in his blog post here.

To summarize, the differences that he highlights are:

  1. CAST is an ANSI standard, while CONVERT is specific to Microsoft SQL Server
  2. CAST cannot be used for formatting purposes (i.e. used to type cast something to a character string), whereas CONVERT can do so, especially for datetime and money datatypes
  3. CAST cannot convert a string to a DATETIME value of a required format (i.e. formatting as mm/dd/yyyy or dd/mm/yyyy as required etc), while the CONVERT can

Finally, he warns us to use a properly calculated size value when using the CAST and CONVERT functions to convert integer values to character data types.

All very great points, and very, very useful. Thank-you, Madhivanan for the wonderful research and enlightenment.

A Question

We can draw a general conclusion that for computation purposes, CAST should be used and for formatting of values for display on a UI or a report, CONVERT should be used. However, the interesting question is one which came up when I was following the discussion on the blog the other day –

Tuesday, July 27, 2010 10:38 AM by cute_boboi

For data extraction purpose, with 1M+ records, which method is faster/recommended ? CAST or CONVERT from:
(i) Date to varchar
(ii) Int to varchar

Today, I try to answer that question.

The Demonstration

Preparing the Environment

Let’s start by creating a table, and filling it up with some test data (Running against the AdventureWorks2008 database gives you about 356409 rows in the table):

-- Step 01. Create a test table
CREATE TABLE CASTCONVERTTest (Id INT,
                              CrDate DATETIME)

-- Step 02. Generate Test Data
INSERT INTO CASTCONVERTTest
SELECT sso1.Id, sso1.crdate
FROM sys.sysobjects sso1
CROSS JOIN sys.sysobjects sso2

Now, let’s begin by pressing Ctrl+M when in the SQL Server Management Studio or go to Query->Include Actual Execution Plan to enable showing the Actual Execution Plan.

Conversion of INT to VARCHAR

In order to see the performance of using CAST and CONVERT on INT to VARCHAR conversion, we will use the following script. At each stage, we will be using DBCC freeproccache to remove all elements from the plan cache.

/***********************************************************
Press Ctrl+M (or go to Query->Include Actual Execution Plan)
************************************************************/
-- Step 03. Test conversion of INT to VARCHAR
-- A. Remove all elements from the plan cache
DBCC freeproccache
GO

-- B. Check the performance of CAST
SELECT CAST(Id AS VARCHAR(11))
FROM CASTCONVERTTest
GO

-- C. Remove all elements from the plan cache
DBCC freeproccache
GO

-- D. Check the performance of CONVERT
SELECT CONVERT(VARCHAR(11),Id)
FROM CASTCONVERTTest
GO

Let’s look at the Actual Execution Plan used by SQL Server. As you can see, we get a 50-50 split, which means that both CAST and CONVERT perform equally well for the INT to VARCHAR conversion.

image

Conversion of DATETIME to VARCHAR

In order to see the performance of using CAST and CONVERT on DATETIME to VARCHAR conversion, we will use the following script. At each stage, we will be using DBCC freeproccache to remove all elements from the plan cache.

-- Step 04. Test conversion of DATETIME to VARCHAR
-- A. Remove all elements from the plan cache
DBCC freeproccache
GO

-- B. Check the performance of CAST
SELECT CAST(CrDate AS VARCHAR(25))
FROM CASTCONVERTTest
GO

-- C. Remove all elements from the plan cache
DBCC freeproccache
GO

-- D. Check the performance of CONVERT
SELECT CONVERT(VARCHAR(25),CrDate,106)
FROM CASTCONVERTTest
GO

Let’s look at the Actual Execution Plan used by SQL Server. As you can see, again we get a 50-50 split, which means that both CAST and CONVERT perform equally well for the DATETIME to VARCHAR conversion.

image

The Cleanup

Finally, as always, let’s cleanup the environment.

-- Step 05. Cleanup!
DROP TABLE CASTCONVERTTest

In Conclusion

In conclusion, we can safely conclude that both CAST and CONVERT perform equally well for the following conversions:

  1. INT to VARCHAR
  2. DATETIME to VARCHAR

I hope the above is a satisfactory reply to the question we started with.

Powered with the research conducted by Madhivanan and with the afore described performance test, the choice is now up to the reader. Do share your practices with CAST & CONVERT on this blog. Also, do mention the reasons why you practice a particular rule of thumb, if possible.

Be courteous. Drive responsibly.