31.8.10

Update table based on the other column

I got a new scenario in one of the popular forum. "Update the table based on the other column"
Let's move the exact scenario, there's a table with the below data
--------------------------------
ID Name GroupID GroupName
--------------------------------
1 A 2 ?
2 B 3 ?
3 C 3 ?
4 D 3 ?
--------------------------------
I need to update the groupname based on the group ID column?

The output should be,
--------------------------------
ID Name GroupID GroupName
--------------------------------
1 A 2 B
2 B 3 C
3 C 3 C
4 D 3 C
--------------------------------
Here we need to use,
1. Self join option - Joining the table with it's own
2. Update statement with inner join
Below is the query to achieve it,

--- Am creating the table
DROP TABLE VENKAT_TABLE
CREATE TABLE VENKAT_TABLE (ID INT, NAME VARCHAR(100),GROUPID INT, GROUPNAME VARCHAR(100))


-- Inserting needy data
INSERT INTO VENKAT_TABLE(ID,NAME,GROUPID) SELECT 1,'A',2
UNION ALL SELECT 2,'B',2
UNION ALL SELECT 3,'C',3
UNION ALL SELECT 4,'D',3
UNION ALL SELECT 5,'E',4


Self joining the table:

SELECT A.NAME,* FROM VENKAT_TABLE A INNER JOIN VENKAT_TABLE B
ON A.ID = B.GROUPID


update query with Innerjoin / self join:

UPDATE B
SET GROUPNAME = A.NAME
FROM VENKAT_TABLE A INNER JOIN VENKAT_TABLE B ON A.ID = B.GROUPID


SELECT * FROM VENKAT_TABLE

Cheers,
Venkatesan Prabu .J

http://venkattechnicalblog.blogspot.com/

23.8.10

Round function in SQL Server

I happened to work in the round function. I found some interesting / peculiar nature of round fucntion. Hope you will enjoy this article. Can you believe you can use round function to validate the input values???????Are you ready for the excitement??


The syntax for the round function is
round(value, length)
length indicates the rounding at the precion level (If positive)...Or else it will round the actual value (If the value is negative)


You will understand it from the below sample queries.
Now, I am trying to round the below value. Let's see how it goes....

SELECT ROUND(19.46,0 ) as total
-- In above query, am informing sql to round the value with no precisions.


SELECT ROUND(19.46123,1 ) as total
-- In above query, am informing sql to round the value with 1 precisions. (.46) value is round off to (.5).
--if the value is (.44) it will rounded off to (.40). Since its (.46) which is greater than (.45) the value is (.50)

SELECT ROUND(19.46123,2 ) as total
-- In above query, am informing sql to round the value with 2 precisions.


SELECT ROUND(19.46123,-1 ) as total
---- In above query, am informing sql to round the value not the precisions.
--If the value is negative, the rounding operation will start from the left side. Here, it's trying the value 19 and not
--checking the precisions (.46123)


SELECT ROUND(19.46123,-2 ) as total
-- In above query, am informing sql to round the value. If the length is equal or more than the value. Then round function will make the value as 0.


Interesting right!!!!

So, If two digit value is mandatory and if the user is trying to give 1 digit. The above query will help us to evaluate the inputs.


Good one right!!!!!



Cheers,

Venkatesan Prabu .J

Date datatype in SQL Server 2008

DATE DATA-TYPE:

Date datatype is one of the new data type introduced in SQL Server 2008. It provided you the date.

Reason for this data type:

There are lot of scenarios where, we need to get only date. In our legacy system, we dont have an option to get only date. We need to do some logic on the datetime column to get the time.

Let's play around this Date datatype in our SSMS :-)
-------------------------------------------------------------------------------------

DECLARE @VAL DATE
SELECT @VAL = GETDATE()
PRINT @VAL


The output is

2010-08-23 ( The format is Year:Month)
-------------------------------------------------------------------------------------

Memory space taken:
This datatype will take 3 bytes of memory.

Implicit conversion from datetime datatype:

From Datetime to Date , implicit conversion will happen. No need to explicitly convert the datatypes. Below is an example for the same.

-------------------------------------------------------------------------------------

DECLARE @VAL DATETIME
DECLARE @VAL1 DATE
SELECT @VAL = GETDATE()
SELECT @VAL1 = @VAL
PRINT @VAL
PRINT @VAL1


The Output is,

Aug 23 2010 7:01PM
2010-08-23

-------------------------------------------------------------------------------------

Cheers,
Venkatesan Prabu .J

Time datatype in SQL Server 2008

TIME DATA-TYPE:

Time data type is one of the new data type introduced in SQL Server 2008. It provided you the time with the accuracy of 100 nanoseconds.

Reason for this data type:

There are lot of scenarios where, we need to get only time. In our legacy system, we dont have an option to get only time. We need to do some logic on the datetime column to get the time.

Let's play around this Time datatype in our SSMS :-)
-------------------------------------------------------------------------------------
DECLARE @VAL TIME
SELECT @VAL = GETDATE()
PRINT @VAL

The output is
18:45:29.0230000 ( The format is hour:Minute:Second:Nanoseconds upto 7 precision)
-------------------------------------------------------------------------------------

Memory space taken:
This datatype will take 3 to 5 bytes memory.

Let's see another example,
-------------------------------------------------------------------------------------

DECLARE @VAL TIME(0) -- This will take 3 bytes to store. Because it doesn't have nanoseconds to store
DECLARE @VAL1 TIME(7) -- -- This will take 5 bytes to store. Because, it holds nanoseconds
SELECT @VAL = GETDATE()
SELECT @VAL1= GETDATE()
PRINT @VAL
PRINT @VAL1


The output is,
18:48:43 -- 3 bytes to store only hour:minute:seconds
18:48:42.5530000 -- 5 bytes to store

-------------------------------------------------------------------------------------

Implicit conversion from datetime datatype:

From Datetime to time, implicit conversion will happen. No need to explicitly convert the datatypes. Below is an example for the same.

-------------------------------------------------------------------------------------
DECLARE @VAL DATETIME
DECLARE @VAL1 TIME(7)
SELECT @VAL = GETDATE()
SELECT @VAL1 = @VAL
PRINT @VAL
PRINT @VAL1


The Output is,

Aug 23 2010 6:51PM
18:51:40.3500000

-------------------------------------------------------------------------------------

Cheers,
Venkatesan Prabu .J

Running vs Configured Values in SQL Server 2008

Have you noticed an option Running vs. Configured Values. What's this?

1. Configured values - Modified value and it's effectively only if you click OK button (Some options may be after server restart)
2. Running values - Current values stored or current property of the server.


Cheers,
Venkatesan Prabu .J

Index Creation Memory option in SQL Server 2008

This option will control the maximum amount of memory to be allocated for the index creation. It's a defined size allocated for the index creation.

Scenario 1 : If the server memory is available and if the index needs more memory space. In that case, SQL Server will try to use the available server memory.

Scenario 2 : If the server memory is not available and if the index needs more memory space. In that case, SQL Server will try to use the existing allocated index space.

Right click on the server ->Properties -> Memory. You will get this option.


By default, the value is 0
Coniguring this setting through query,
--------------------------------------------------------------------------------
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'index create memory', 4096 -- Am setting the value as 4096KB
GO
RECONFIGURE;
GO
--------------------------------------------------------------------------------
Cheers,
Venkatesan Prabu .J

22.8.10

Function related to exceptions in sql server

I happened to read an article on SQL Server exception. I found some of the useful functions which will be very useful to find the exception details like,

1. ERROR_NUMBER() - This function will provide your the exact error number.
2. ERROR_MESSAGE() - This function will provide the error message thrown
3. ERROR_LINE() - This function will provide you the exact line number where error occurs.
4. ERROR_PROCEDURE() - This function will provide your the procedure where error occurs.

BEGIN TRY BEGIN TRAN
DECLARE @dividebyzero INT
SET @dividebyzero = 100
SET @dividebyzero = @dividebyzero/0
COMMIT
END
TRY
BEGIN CATCH
PRINT ERROR_NUMBER()
PRINT ERROR_MESSAGE()
PRINT ERROR_LINE()
PRINT ERROR_PROCEDURE()
ROLLBack
END CATCH

Cheers,
Venkatesan Prabu .J

Swap values in a column

I got a query from one of the blog reader. How to swap the values in a column?
There is a column "availability" in a table and it's have 2 values "Yes" or "No".

The user have wrongly entered the values. Instead of yes they have inserted No and similary for No, they have entered Yes. How to rectify this problem?

Here is the solution to solve this problem

DROP TABLE VENKAT
CREATE TABLE VENKAT(ID INT, NAME VARCHAR(100))
INSERT INTO VENKAT VALUES(1,'VENKAT1')
INSERT INTO VENKAT VALUES(2,'VENKAT2')
INSERT INTO VENKAT VALUES(3,'VENKAT1')
INSERT INTO VENKAT VALUES(4,'VENKAT2')
SELECT * FROM VENKAT
BEGIN TRANSACTION
UPDATE VENKAT SET NAME='VENKAT12' WHERE NAME='VENKAT2'
UPDATE VENKAT SET NAME='VENKAT2' WHERE NAME='VENKAT1'
UPDATE VENKAT SET NAME='VENKAT1' WHERE NAME='VENKAT12'
COMMIT
SELECT * FROM VENKAT









Cheers,
Venkatesan Prabu .J
http://venkattechnicalblog.blogspot.com/

21.8.10

Profile issue with Outlook

I happened to configure my exchange server and gmail in my Outlook 2007.

Initially, I tried to configure my exchange server. I had some problem in connecting my server. After that, I have configured my gmail. Yahooo.... am able to access my gmails. But while opening my Outlook am getting errors about the exchange server. I thought of removing the same from my outlook.

Went to Options and tried deleting the exchange server under mail section. I couldn't succeed.

I got the below error,

"You cannot delete this Outlook data file. Configuration information in the file is being copied to your new default data file. You can delete the file after this information is copied."

I moved to data tab and tried to remove the data file. Am getting the below error,

"This data file is associated with a mail account. To remove it use the 'E-Mail' tab.

How can I solve this??????

Here is the simple approach,

1. Once you configured your email. A profile will be created for you.
2. Got control panel -> Mail -> You will get Email accounts/Data files/Profiles. Click the third button and remove your current profile. Create a new profile and add your Gmail account. Yes, now are ready to go -> Am able to check my gmails...

Cheers,
Venkatesan Prabu .J

15.8.10

Not In Vs Not exists clause in SQL Server - Part 1

NOT IN Operator and NOT EXISTS Operator will work or produce similar results. But, the operational flow in getting the results will differ a lot.


Not In operator will check for a particular value in the subquery list. Subquery will provide a list of values and our main query will check for the non availability of specific column values in the subquery list. It will use nested loops to fetch the data. We will see in details while analysing the execution plans.



SELECT NAME FROM VENKAT WHERE ID NOT IN (SELECT ID FROM VENKAT_SECOND_TABLE)


Not Exists operator will do a similar kind of operation but the matching is done with correlated join and it will utilise the index to fetch the records. So performance wise, this will give you an apt solution.


SELECT NAME FROM VENKAT V1 WHERE NOT EXISTS (SELECT ID FROM VENKAT_SECOND_TABLE V2 WHERE V2.ID=V1.ID)

Your code snippet,


DROP TABLE VENKAT
GO
CREATE TABLE VENKAT(ID INT, NAME VARCHAR(100))
INSERT INTO VENKAT VALUES(1,'VENKAT1')
INSERT INTO VENKAT VALUES(2,'VENKAT2')
INSERT INTO VENKAT VALUES(3,'VENKAT3')



GO
DROP TABLE VENKAT_SECOND_TABLE
GO
CREATE TABLE VENKAT_SECOND_TABLE(ID INT, NAME VARCHAR(100))
INSERT INTO VENKAT_SECOND_TABLE VALUES(1,'VENKAT1')
INSERT INTO VENKAT_SECOND_TABLE VALUES(2,'VENKAT2')
INSERT INTO VENKAT_SECOND_TABLE VALUES(4,'VENKAT4')
GO




SELECT NAME FROM VENKAT WHERE ID NOT IN (SELECT ID FROM VENKAT_SECOND_TABLE)
GO



SELECT NAME FROM VENKAT V1 WHERE NOT EXISTS (SELECT ID FROM VENKAT_SECOND_TABLE V2 WHERE V2.ID=V1.ID)


Both above statements were providing a similar kind of results. Let's see the execution plan for both,







From the execution plan, we can easily identify the performance comparison these two operators. Hope, you will be using not exists operator in your future queries:-)

Cheers,
Venkatesan Prabu .J

13.8.10

Single quotes inside the string

Storing character or string is possible in the database. For storing the value we will put the string inside the single quotes and we will insert it. For instance,

INSERT INTO VENKAT_TABLE VALUES(1,'VENKAT')

Now, I want to insert a data like Venkat's instead of venkat. Let's see the query now,

INSERT INTO VENKAT_TABLE SELECT 1,'MEN'S'

Am getting the error,

Msg 105, Level 15, State 1, Line 3
Unclosed quotation mark after the character string '



In this case, we need to use two single quotes to insert one single quote between the characters in a string.


DROP TABLE VENKAT_TABLE
CREATE TABLE VENKAT_TABLE(ID INT, NAME VARCHAR(100))
INSERT INTO VENKAT_TABLE SELECT 1,'MEN''S'
SELECT * FROM VENKAT_TABLE




Cheers,
Venkatesan Prabu .J

10.8.10

My SQL Server session in Chennai - One of the fabulous event

Writing in my blog after a very long time. Last month, I got a very nice opportunity to share my knowledge on SQL Server 2008 - Manageability features to chennai SQL experts.



It was a unforgottable experience and I enjoyed the whole day with my fellow MVP's. I came to know about me.


As usual am late:

My session is in the afternoon and am bit late for the session. I missed Pinal's morning session on spatial indexing. Anyway, I have attended his final session.

This program is well organised and the entire credit goes to the organisers Sugesh, Vidya sagar, Madhivanan and Deepak. No words to express my joyfullness in meeting all the technology experts at the same time in Chennai.


My Laptop problem:


Unfortunately, my laptop is not connecting to the Projector. We tried our level best but nothing works for me. Moved all my presentation materials to vidya sagar's laptop. Unfortunately, VS2010 demo is not working in his laptop. Atlast, I moved my presentation materials to Deepak's laptop. Thank god, It's working fine. Everyone is too friendly, but I couldn't come out from my tension. Had little bit of food and started my session.


My session:

Am bit tensed and faced a problem with SQL Server authentication. Deepak and vidya sagar understood my situation and helped me at the initial stage. Now, I am relaxed a little bit.


Below are the topics covered in my session,
1. Activity Monitor
2. Policy Based Management
3. Resource Governor
4. SQL Server Audit

I have provided the Sample scenario, Details and Sample demo for each topics.


My snap with other technology experts Vidya sagar, Madhu K.Nair, Mathivanan, Pinal Dave, Deepak and myself (To know more about these people, you can just google their names)



I got a friendly gift/honor from SQL Server Chennai User group (Gift from vidya sagar). All attendees have got a black colour T-shirt with CSSUG embossed on it. In addition to this, speakers should select 2 active attendees and those two will be rewarded with SQL Server related books. Speakers will put their autograph and presented the books to the active participants.

Special note on Pinal Dave:

OOPS, Pinal is an extra ordinary person. I can remember he speaks atleast 30 minutes continuously on seeing me. He had the capability to talk on any topics for atleast 1 hour :-) (Just kidding). Too realistic, too jovial, too friendly and finally a very strong SQL Server expert. Proud to tell you all that, I am a big fan of Pinal Dave.


Anyway, Thanks to CSSUG organisers for providing me a very nice opportunity to share my knowledge and to meet everyone.

Cheers,
Venkatesan Prabu .J

My T-SQL Gallery @code.msdn.microsoft


Created my own T-SQL Gallery in Microsoft site. Do visit the same and share your feedback,

http://code.msdn.microsoft.com/VenkatSQLSample/Thread/List.aspx

Thanks and Regards,
Venkatesan Prabu .J

SQL Server Interview questions - Part 1

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

What is SQL whats its uses and its component ?
The Structured Query Language (SQL) is foundation for all relational database systems. Most of the large-scale databases use the SQL to define all user and administrator interactions. It enable us to retrieve the data from based on our exact requirement. We will be given a flexibility to store the data in our own format.


The DML component of SQL comprises four basic statements:
* SELECT to get rows from tables
* UPDATE to update the rows of tables
* DELETE to remove rows from tables
* INSERT to add new rows to tables


What is DTS in SQL Server ?
Data Transformation Services is used to transfer the data from one source to our required destination. Considering am having some data in sql server and I need to transfer the data to Excel destination. Its highly possible with dialogue based tool called Data Transformation services. More customization can be achieved using SSIS. A specialized tool used to do such migration works.


What is the difference between SQL and Pl/Sql ?

Straight forward. SQL is a single statement to finish up our work.Considering, I need some data from a particular table. “Select * from table” will fetch the necessary information. Where as I need to do some row by row processing. In that case, we need to go for Procedural Logic / SQL.

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

Difference between primary key and Unique key?
Both constraints will share a common property called uniqueness. The data in the column should be unique. The basic difference is,
· Primary key won’t allow null value. Whereas, unique key will accept null value but only one null value.
· On creating primary key, it will automatically format the data inturn creates clustered index on the table. Whereas, this characteristics is not associated with unique key.
· Only one primary key can be created for the table. Any number of Unique key can be created for the table.

Select Statement in SQL Server

Select Statement in SQL Server

String Functions in sql server

String Functions in sql server
Substring/Len/replace/Ltrim/Rtrim

SQL Server Interview Question - Part 2

What is normalization?

Normalization is the basic concept used in designing a database. Its nothing but, an advise given to the database to have minimal repetition of data, highly structured, highly secured, easy to retrieve. In high level definition, the Process of organizing data into tables is referred to as normalization.


What is a stored procedure:
Stored procedures are precompiled T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. As, its precompiled statement, execution of Stored procedure is compatatively high when compared to an ordinary T-SQL statement.


What is the difference between UNION ALL Statement and UNION ?
The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION,the reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

Example for Stored Procedure?
They are three kinds of stored procedures,1.System stored procedure – Start with sp_2. User defined stored procedure – SP created by the user.3. Extended stored procedure – SP used to invoke a process in the external systems.Example for system stored proceduresp_helpdb - Database and its propertiessp_who2 – Gives details about the current user connected to your system. sp_renamedb – Enable you to rename your database


What is a trigger?

Triggers are precompiled statements similar to Stored Procedure. It will automatically invoke for a particular operation. Triggers are basically used to implement business rules.


What is a view?
If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.


What is an Index?
When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.


What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL ServerClustered -

1. It will format the entire table, inturn physically sort the table.

2. Only one clustered index can be created for a table.

3. Data will be located in the leaf level.

4. By default, primary key will create clustered index on the table.

Non-Clustered Index

1. It wont touch the structure of the table.

2. It forms an index table as reference to the exact data.

3. A reference to the data will be located in the leaf level.

4. For a table, we can create 249 non clustered index.

Happy Learning!!!
Regards,
Venkatesan Prabu .J

SQL Interview question

Extent Vs Page?

Pages are low level unit to store the exact data in sql server. Basically, the data will be stored in the mdf, ldf, ndf files. Inturn, pages are logical units available in sql server.The size of the page is 8KB.

Eight consecutive pages will form an extent 8 * 8KB = 64KB.

Thus I/O level operation will be happening at pages level.The pages will hold a template information at the start of each page (header of the page).

They are,

1. page number,

2. page type,

3. the amount of free space on the page,

4. the allocation unit ID of the object that owns the page.

Extents will be classifed into two types,

1. Uniform extents

2. Mixed extents

Uniform Extents:It occupied or used by a single object. Inturn, a single object will hold the entire 8 pages.Mixed

Extents:Mulitple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

Property of SQL Server :Initally if an object is created, sql server will allocate the object to the mixed extent and once if the size reaches 8 pages and more... immediately, a new uniform extent will be provided for that particular object.

Herecomes, our fragmentation and reindexing concepts.



Best Joke - Enjoy it

Best Joke - Enjoy it