30.8.08

Count data value in a group from result set

Count data value in a group from result set:
I have come up with a new scenario like, I need to add the data value in the result set.
Using the below technique, we can achieve the same.
create table venkattab (Number int,name1 varchar(10))
insert into venkattab values(1,'Venkat')
insert into venkattab values(2,'Venkat2')
Declare @SQLvar int
SET @SQLvar = 0
Select @SQLvar = @SQLvar + TempValue FROM
(Select Number as TempValue from venkattab where name1='Venkat'
Union All Select Number as TempValue from venkattab where name1='Venkat2')
AS A
Select @SQLvar -- Output is 3
Another Example,
Declare @SQLvar int
SET @SQLvar = 0
Select @SQLvar = @SQLvar + TempValue FROM ( Select 2 TempValue Union All Select 3 Union All Select 4) AS A
Select @SQLvar -- Output is 9
The query,
Select 2 TempValue Union All Select 3 Union All Select 4
will yield a result set 2,3,4 and the variable will fetch the summation of these values.
Happy Learning!!!
Regards,
Venkatesan Prabu . J

XML data type in SQL Server 2005- Part I

XML Data type in SQL Server 2005:
XML is the new data type introduced in SQL Server 2005. XML stands for Extended Markup langugage. A world wide accepted standard to pass the data through network. I can remember my experience on using XML data in legacy systems of SQL server, we used to store those data in the form of varchar data types. But, with the introduction of sql server 2005 XML data type, we can store the data in the form of XMLs.
Let create a table Venkattable,
create table Venkattable(id int, Name varchar(10),age int)
Am inserting some data into this table,
insert into Venkattable values(1,'Venkat',16)
insert into Venkattable values(2,'Arun',16)
insert into Venkattable values(3,'Suba',16)
insert into Venkattable values(4,'Karthi',16)
insert into Venkattable(id,age) values(4,16)
select * from Venkattable

XML Raw:
XML raw statement is used to display your result set in the form of XML but the format of display is quite intersting.It will show up the row by row data with a tag "Row"
Let see a sample for the XML RAW, am trying to display the result set in XML RAW mode.

SELECT * FROM Venkattable FOR XML RAW
The output resembles,

In the above XML Raw method, we wont get a proper segregation of datas like, id in seperate tag, name in seperate and age in seperate tag. To achieve the same, we can go for specifying an additional tag named Elements.
Below is the syntax to acheieve the same.
SELECT * FROM Venkattable FOR XML RAW, ELEMENTS
The output resembles as below,
In the XML RAW method, we lose the identity about the table VenkatTable. Suppose, we need to fetch the table identity in our XML output. We can use XML AUTO method.
The syntax for XML Auto is,
SELECT * FROM Venkattable FOR XML AUTO
The output resembles as below,

Happy Learning!!!
Regards,
Venkatesan Prabu .J

23.8.08

charindex in sql server

charindex in sql server:
Charindex method is used to identify a particular character position in the string.
Thh syntax is Charindex(character or string to find , parent string).
This function will return an integer value.
Create Table #VenkatTable (fname varchar(50))
Insert into #VenkatTable values('1.doc')
Insert into #VenkatTable values('2.doc')
select charindex('.',fname) from #VenkatTable
Output is 2
Happy Learning!!!
Regards,
Venkatesan Prabu .J

Distinct filename or distinct items in SQL Server

Distinct filename or distinct items in SQL Server
Let see some interesting facts like identifying the unique file types available in the database.
Considering, I have stored lot of file types in my database and I need to find, what are the filetypes available
in my database.
---Created a sample table
Create Table VenkatTable (fname varchar(50))
Insert into VenkatTable values('1.doc')
Insert into VenkatTable values('2.doc')
Insert into VenkatTable values('3.doc')
Insert into VenkatTable values('1.xls')
Insert into VenkatTable values('2.xls')
Insert into VenkatTable values('3.xls')
Insert into VenkatTable values('4.xls')
Method 1:
Select Count(*) as [Count],right(fname,3) as FileType from VenkatTable
group by right(fname,3) Order by [Count] desc

Here am trying to use "right" method to fetch the file types availabel in my db. But, this method will fail
if the length of the file extension is more than or less than 3. In that case, we can prefer the second method.
If we are pretty much sure that the extension is of length 3. Method 2:
select
distinct substring (fname, charindex('.',fname)+1,len(fname)) as filetype,
count(*) as count from VenkatTable
group by substring (fname, charindex('.',fname)+1,len(fname))
Its a very generic method to identify all filetypes available in our db.
Happy Learning!!!
Regards,
Venkatesan Prabu .J

20.8.08

SQL Teaser - Between Operator in SQL Server

Let see some interesting facts of SQL Server's between operator:

create table VenkatTable(id int identity(1,1) primary key clustered, MyColumn int)
insert VenkatTable(MyColumn) select 1
union all select 2
union all select 3
union all select 4
union all select 5
union all select 6
union all select 7
union all select 8

--Statement 1
select count(*) from VenkatTable where MyColumn between 3 and 5

Ouput is 3

--Statement 2
select count(*) from VenkatTable where MyColumn between 5 and 3

Ouput is 0
The reason behind the different output is,
Generally, Between indicates the data between the left value and right value. But it's not the case in SQL Server.
This compiler will check for the syntax and
1. It will check the left value should be less than the right value.
2. If its the case, it will return "True" else it will return "False"
3. If the result is true then it will fetch the actual data from the database.
4. If the result is false then it wont fetch any data and give the data as null.

Happy Learning!!!
Regards,
Venkatesan Prabu .J

16.8.08

Compatibility Levels in SQL Server

Compatiblity Level is a nice feature in sql server. It's used to enable your SQL Server in different version. Below is the query used to check the compatibility level of your current database.
EXEC SP_DBCMPTLEVEL 'master'

On executing the above statement you will get the outpu,
The current compatibility level is 90.

90 indicates that, its SQL Server 2005 database.

EXEC SP_DBCMPTLEVEL 'master',80
The above statement is used to enable your database to work as a SQL Server 2000 database.
We can achieve the same using inbuilt dialog box option in SSMS.
right click database ->Properties ->Options->Compatibility Level
Providing You should be a sysadmin role or the database owner to achieve this task.
Happy Learning!!!
Regards,
Venkatesan Prabu .J

Null value handling in Count function

Let's see some interesting facts of NULL value in SQL Server.Am trying to Insert some Null values in my table and check the count of the records available in my table.

Code Snippet
DECLARE @t table(
id int identity(1,1), value varchar(50))
INSERT INTO @t values(NULL)
INSERT INTO @t values(NULL)
INSERT INTO @t values(NULL)
INSERT INTO @t values('1')
INSERT INTO @t values('2')
INSERT INTO @t values('3')
SELECT count(id), count(value) FROM @t

with out executing the code, Can you tell me the output?

OOps, Its 6,3.... How? Its because, SQL Server will discard the null values and considered only the valid values for count function.

Happy Learning!!!

Regards,

Venkatesan Prabu .J

15.8.08

String Pattern matching in SQL Server

Lets see some interesting facts in SQL Server. Today we will see pattern matching concept in SQL Server.
I have tried to create a table name VenkatTable and inserted some rows into it,



Code Snippet
create table VenkatTable( Col1 varchar(5) )
insert into VenkatTable values('_Sas')
insert into VenkatTable values('Sas_')
insert into VenkatTable values('S_us')
insert into VenkatTable values('Sas')
insert into VenkatTable values('Sa_s')
Now I need to fetch the data as per the below condition,



Real Query
select * from VenkatTable where Col1 Like '%Sa_%'


Without executing the above code. Can you tell the number of rows retrieved by the above query?


In the above query, a small trick is embedded, SQL Server wont check for the string having "Sa_"
Because, the character "_" is nothing but a single character matching.
The above query will fetch all the strings matching the word Sa, starting with 0 or any number of characters
and should have 1 character after Sa and its followed by 0 or any number of characters.

Happy Learning!!!

Regards,

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