Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Thursday, November 6, 2008

What is SQL Server Index?

  

SQL Server Indexes are the objects used to optimize the performance of queries. It makes SQL queries select, update or delete run faster. The whole purpose of indexes is to make finding data rows in a table easier.

 

If a table is created with no indexes, then the data rows are not stored in any particular order. This structure is called a heap.

If a clustered index is created in a table, then data rows are stored in sorted order on the clustered index key making easier to find rows.

But a nonclustered index is rather complex. The data rows are not stored in order based on the noclustered key rather each nonclustered key value entry has pointers to the data rows containing the key value.

 

Here, I want to elaborate mainly the difference between using an index and not using it.

For that I first, created two tables one without index and other with index. Then, I inserted some sample data in both of them.

The SQL query used is shown below.

 

create table tbl_test_index ( pid int, cname varchar(50))

insert into tbl_test_index values (1, 'Nepal')

insert into tbl_test_index values (2, 'India')

 

create table tbl_test_index2 ( pid int , cname varchar(50))

create index test_index2 on tbl_test_index2(pid)

insert into tbl_test_index2 values (1, 'Nepal')

insert into tbl_test_index2 values (2, 'India')

 

Then, I tried to find out the cost of running a select query with order by clause.

For that I highlighted the following query and clicked "Display Estimated Execution Plan (Ctrl + L)" button on tool bar of SQL Query Analyzer to display execution plan.

 

select    *

from     tbl_test_index

order by 1

 

The output is shown below.

 

Fig: SQL Execution Plan 1

 

Then, I highlighted following query in query analyzer and viewed execution plan.

select    *

from     tbl_test_index2

order by 1

 

 

Fig: SQL Execution Plan2

 

From the first figure for case without index, following things can be obtained.

Total CPU cost = 0.0009

Total I/O cost = 0.0487

From the second figure for case with index, following things can be obtained.

Total CPU cost = 0.000812

Total I/O cost = 0.04375

Also, the estimated cost is lower in second case.

From these results, it can be concluded the use of indexes optimizes the performance of SQL Queries or makes queries faster.

However, the choice of column as key should be made carefully depending upon maximum use of the column.

 

Read more...

Saturday, November 1, 2008

Paging in Web Applications (SQL Trick)

Web Applications here means the applications that are used through browsers. Web applications are tougher to develop and use as compared to windows applications. In this topic, I want to put focus on paging techniques for web applications.

If you are a web programmer, you may be having problem to display a large report or data in a data grid with paging. Paging is required as it might not be practical to display large no. of rows in a single grid. User will have to keep scrolling down and up. Also, a large memory will be constantly consumed. There are no. of ways to use paging in data grids. Here, I would like to focus on data grid displayed by pulling data from RDBMS database like SQL Server.

Suppose you are running a stored procedure (say sp_report1) to pull data from SQL Server database and it returns all data (say 5000 rows) at one time. A simple way would be to pass two input variables like @from_row_no and @to_row_no to the procedure and modify it to return rows of data from @from_row_no to @to_row_no.

This also can be done two ways. In first way, you put all output data in a temporary table which also contain an identity column. Then, while running final select statement from that final output table, use conditions to display from @from_row_no to @to_row_no.

Here is an example.

Create proc sp_Report1

( @from_row_no int, @to_row_no int)

as

begin

create table #tbl_final_display

(

id  int identity(1,1),

col1 varchar(30),

col2 varchar(30)

)

/* now insert data into #tbl_final_display as per your requirement */

-- for final select

select *

from #tbl_final_display

where id >= @from_row_no

and id <= @to_row_no

end

If you have to display results in order then you will have to pass ordering column name also to stored procedure. If the data in #tbl_final_display is going in single statement you can use order by clause in that statement with passed input variable. If not, you will have to create two temporary tables. First one to just hold the data and second one to copy data from first one by using order by clause. The second table will obviously have one more column than first one for id field. This process becomes tedious when there are many sortable columns as many if else conditions are required.

Here "id int identity(1,1)" means that id column of the table will have datatype int and the values will be automatically inserted while inserting rows in that column. The values will start from 1 and will keep on increasing by 1 for each new row.

In Second Method, you need to use the permanent table in which data are kept temporary. The stored procedure will just populate the table. Final select from table is run from front end like this.

For example to retrieve data from table tbl_final_display from row 9 to row 14 order by first field, you can use this query.

select    *
from    (
    select    top 6 *
    from    (
        select    top 14 *
        from    tbl_final_display
        order by 1
    ) tmp
    order by 1 desc
    ) tmp
order by 1

It uses multiple sub-queries and multiple select. First it selects 14 rows (@to_row_no) and then selects last 6 rows from that select. This has to be done from front end as while using "top 6 " we cannot pass variable instead of 6. It may be tedious for programmers to handle from front-end as much additional care must be taken. Such as provide fields to distinguish multiple users to eradicate the chances of wrong output when same report is used by multiple users.

Read more...

Tuesday, October 28, 2008

Temporary Tables in SQL Server

Temporary tables are tables used to hold data for temporary purpose. There are two types of temporary tables.

1. Local Temporary table

2. Global Temporary table

Local Temporary table is a table created with "#" preceding the name of table. It exists till the connection to database, which has created it, lasts. The table is accessible by that connection only. The table is created in temporary database i.e. tempdb. The name of database.tablename should not be more than 116 characters for such tables. Suppose if we create local temporary table with name #tt, then a table with name like "#tt_________________________________________________________________________________________________________________000000000038"

is created in tempdb database. The length of name is 128 characters.

Example : create table #tt ( a varchar(20))

Multiple local temporary tables can be created with same name from different connections. In such case, these tables are also created in tempdb database with name slightly varying last suffix number. A normal programmer will use local temp table more than 90% of times.

Global Temporary Table is a table created with "##" preceding the name of table. It also exists till the connection to database, which has created it, lasts. But the table is globally accessible by other connections also. But, when the connection creating it terminates, then other connections also cannot use it. These tables are also created in tempdb database of SQL Server. It is created with same name as provided by user.

Example : create table ##tt ( a varchar(20))

As the table has global scope, the table name should be unique. Often, the global temp table can be replaced by temporary nature of permanent table. I mean better create a permanent table (with no # and ## in prefix) with a column to identify accessing users like SPID (Stored Procedure ID) or hostname or username to track and separate users. This permanent table has to be wiped out with user data whenever he/she finishes using it. This will remove need to recreate the table every time. In this case, benefit of global temp table becomes that, it does not consume space in database unlike permanent table.


Read more...

Monday, October 27, 2008

Probable causes of high memory usage by SQL Server

Under normal conditions, 2 GB RAM memory of database server dedicated to hold SQL Server databases for a multi-user application is more than enough. But, some times the memory usage becomes so high that, application users will not be able to use the application, letting system to knees. Then, the database administrator will have to restart the SQL Server service to clear the memory usage requiring some down time. So, it's always better to prevent SQL Server from using so much high memory.

 

So, what may be the causes for high memory usage by SQL Server? I have listed out some of the most probable causes.

 

  1. Of course, too many users are using the application at the same time, this is likely and a general case.
  2. Some other external process or virus or malware may be causing the problem.
  3. A lot of uncommitted transactions in SQL may also cause this problem.
  4. Many open connections to SQL Database by application increase the use of memory in database server. For a web application, it's likely that users do not close the application by properly logging out. Due to this, the connection to database remains open till the garbage collector finds it and terminates the connection. If a user initiates a time consuming process in SQL from application and closes the web application, the process keeps running in back end and keeps using the memory.
  5. Excessive use of full outer joins in SQL procedures or query uses more memory while executing.
  6. Excessive use of temporary tables also uses more memory.
  7. Use of repetitive and many dead locks in SQL Server cause the increase in memory usage.

 

Usually, SQL server has not tendency to free memory space after it has finished using. This means, if the usage reaches 100 MB sometime due to some process, even after the process is completed, SQL Server will the free unneeded memory space.

 

The SQL Server memory usage can be controlled by SQL Server Enterprise Manager. First open Enterprise Manager; expand the Microsoft SQL Servers, SQL Server group and the server; right click the SQL Server instance and select properties. In the memory tab of properties window, select "Use a fixed memory size (MB)" and then slide the slider to limit the SQL Server memory usage. This is the memory usage for SQL Server instance only not for extended procedures, dlls and other external process. So, SQL Server may be using a little more that allocated over here sometimes.

 

 

 

Read more...

How to find the cause of deadlock in SQL Server?

If you are a database administrator or technical support person for a large application, you may have come across this problem. Sometimes users say that their application is hanging while doing some usual operations, like running report, fetching details, etc. The cause is due to dead lock in some table of SQL Server.

 

If a user at some end is generating Purchase Order and another user at other end is running a Purchase Order Report which fetches Purchase Order details, then this is a likely case of dead lock. These two processes most probably use the same tables. If a user is inserting in Purchase Order table, then he will lock the table stopping others to select data from there until the insertion completes. Usually the insertion takes in no time, so in small process, dead lock is rare case. But, in large applications there are processes which take hours to run and complete. So, if the process locks the tables and another user runs select on that table, then the later user is kept hold.

 

There may be some cases when a user process A (say) is waiting for another process B (say) to complete while B is waiting for A to complete. Then, this is a dead lock. None of the process completes and it makes system hang. This is also likely case when the application does not handle it properly. If A is locking some table1 and waiting to use table2, while B is locking table2 and waiting for table1 to release, it is a case of deadlock. You can find out who is dead locking the system by logging to ISQLW ( SQL Server Query Analyzer) and running sp_who and SP_WHO2 commands.

 

Example : sp_who2 'active'

 

This gives the spid, status, login, hostname, BlkBy (blocked by), DBname (Database Name),  etc. If BlkBy field is filled by some value, the value is the SPID of blocking process. Then find out row in output whose id is the blocking id. From the hostname and login you will be able to find out who is the blocking user. You can then call the user to ask what he is doing and tell him to run the process sometime after.

 

Output of sp_who2.

SPID

Status

Login

HostName

BlkBy

DBName

Command

51

sleeping                     

SURAJSHRESTHA\Suraj Shrestha

SURAJSHRESTHA

  . 

master

AWAITING COMMAND

53

sleeping                     

NT AUTHORITY\SYSTEM

SURAJSHRESTHA

  . 

msdb

AWAITING COMMAND

54

RUNNABLE                     

Tech

Techcreeze

  . 

TESTDB

UPDATE         

55

sleeping                     

sa

SURAJSHRESTHA

54 

TESTDB

AWAITING COMMAND

 

In above case, process 55 is blocked by process 54 run by login tech from computer with name Techcreeze.

 

Read more...

Saturday, October 25, 2008

SQL: Datatype, Smalldatetime does not store second.

Smalldatetime datatype is less precision version of datatime datatype. Datetime variable takes 4 bytes while smalldatetime takes 2 bytes of memory. If you do not require precision to second level then, it's ok to use smalldatetime. But problem comes when you use datetime and smalldatetime variables interchangeably.

When you convert a datetime variable to smalldatetime, values with 29.998 seconds or lower are rounded down to nearest minute whereas values with 29.999 seconds or higher are rounded up to nearest minute. Here are two examples.

When following query is run in ISQLW (SQL Query Analyzer),

Select convert(smalldatetime,'2008-10-25 23:59:29.998')

The output is 2008-10-25 23:59:00.

Now, if we run the following query,

Select convert(smalldatetime,'2008-10-25 23:59:29.999')

The output is 2008-10-26 00:00:00.

The difference is obvious.

If we take only year, month and day from the variables and compare with operators like >, <, = then, the difference becomes 1 day.

This type of problem may not arise frequently.

But, if it comes, rounding of dates may not come to your mind at first.

After I notice, I have stopped using smalldatetime for just saving 2 bytes of memory.


Read more...

Friday, October 24, 2008

SQL- Concatenate data in Table

 
If you want to merge strings in different rows a table separated by a character (say comma[,]),
then you can do so easily with a simple SQL Trick without requiring any loop.
 
You just have to declare a varchar variable long enough to hold all data.
and write a select statement for the table. The following example illustrates this more.
 
First create a test table with some test data.
 
create table #tbl_test ( address varchar(50))
insert into #tbl_test values ( 'Lubhu')
insert into #tbl_test values ( 'Lalitpur')
insert into #tbl_test values ( 'Kathmandu')

 
Now, declare the variable and write select statement as below.
 
declare @Result varchar(8000)
set  @Result = ''

select  @Result = @Result + case when len(@Result)>0 then ',' else '' end + address
from #tbl_test
 
select @Result

 
You will be surprised by how it works.
The output will be Lubhu,Lalitpur,Kathmandu.
 
Remeber that, the variable should be long enough to hold all data otherwise it will lose excessive data.
Varchar variable cannot hold more that 8000 characters in a single variable.
Also, the separtion character is not compulsory or can be any. No obligation on that.
 

Read more...

SQL: The table '#tbl_result' is ambiguous.

 
If you are SQL programmer, there may be cases where you want to join same table multiple times to pull out same data.
This is ok for select operation. But in case of update and delete operation, it may not be easy. The error
"The table 'tablename' is ambiguos' comes while performing such update operation.
The error can be overcomed by simple trick of sql. You can use a sub-query instead of table name.
 
Here is an example.
 
First a test table is created.
 
create table #tbl_result
(
 head varchar(20),
 item varchar(20),
 data numeric(18,3)
)

 
Some sample data is entered.
insert into #tbl_result values ( 'Volume', 'A', 10.2)
insert into #tbl_result values ( 'Volume', 'B', 11.2)
insert into #tbl_result values ( 'GTO', 'A', 1020)
insert into #tbl_result values ( 'GTO', 'B', 627.2)
insert into #tbl_result values ( 'Avg Price', 'A', 0)
insert into #tbl_result values ( 'Avg Price', 'B', 0)

 
--
Then following select statement works fine even though it contains same table multiple times

select *
from #tbl_result a
inner join #tbl_result b
 on a.item = b.item
 and a.head = 'Volume'
 and b.head = 'GTO'

 
But following update statement does not work and displays error message
-- Server: Msg 8154, Level 16, State 1, Line 1
-- The table '#tbl_result' is ambiguous.
 
update #tbl_result
set data = case when isnull(a.data,0) <> 0 then  b.data / a.data end
from #tbl_result a
inner join #tbl_result b
 on a.item  = b.item
 and b.head = 'GTO'
inner join #tbl_result c
 on a.item = c.item
 and c.head = 'Volume'
where a.head = 'Avg Price'

 
The update can be changed with a little trick to make it work. Here the table name is replaced with a sub query.

update #tbl_result
set data = case when isnull(c.data,0) <> 0 then  b.data / c.data end
from #tbl_result a
inner join ( select * from #tbl_result where head = 'GTO') b
 on a.item = b.item
inner join ( select * from #tbl_result where head = 'Volume') c
 on a.item = c.item
where a.head = 'Avg Price'

 
You can check out result by following select statement.
select *
from #tbl_result

 

Read more...

Thursday, October 23, 2008

How to change the columns of SQL Query output or table to rows?

If you are database programmer, you may have come across this issue. There may be cases in which user should be allowed to enter data column wise.

 Here is an example. Suppose, for a manufacturing company, a user should enter plan volume to be produced in month wise basis. The screen provided should be like this.

 

Head

Year

Shrawan

Bhadra

Aswin

Kartik

Mangsir

Poush

Magh

Falgun

Chiatra

Baiskh

Jestha

Asadh

Plan Volume

2065

2.3

33.2

12

2

4

5

2.1

3.2

2.0

1.2

5.6

2.1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

In above figure, Shrawan to Asadh are Nepali Months. The application should provide the user to enter Plan Volume data from screen as shown above. So, the main table structure should be same as above. But for calculation purpose and manipulation, it is often required to retrieve same data as shown below.

 

Head

Year

Month

Amt

Plan Volume

2065

Shrawan

2.3

Plan Volume

2065

Bhadra

33.2

Plan Volume

2065

Aswin

12

Plan Volume

2065

Kartik

2

Plan Volume

2065

Mangsir

4

Plan Volume

2065

Poush

5

Plan Volume

2065

Magh

2.1

Plan Volume

2065

Falgun

3.2

Plan Volume

2065

Chaitra

2.0

Plan Volume

2065

Baisakh

1.2

Plan Volume

2065

Jestha

5.6

Plan Volume

2065

Asadh

2.1

 

The data are same as above.

This can be achieved by a simple trick of SQL. The second data structure can be achieved by creating a view. This is logical as the no. of columns is known previously.

Suppose, if the previous data table name is "Tbl_plan". The created view will be like this.

 

create view Tbl_plan_vw

as

 select    [head], [year], 'Shrawan' [Month], [Shrawan]

from     Tbl_plan

union all

select    [head], [year], 'Bhadra' [Month], [Bhadra]

from     Tbl_plan

union all

select    [head], [year], 'Aswin' [Month], [Aswin]

from     Tbl_plan

union all

select    [head], [year], 'Kartik' [Month], [Bhadra]

from     Tbl_plan

union all

select    [head], [year], 'Mangsir' [Month], [Mangsir]

from     Tbl_plan

union all

select    [head], [year], 'Poush' [Month], [Poush]

from     Tbl_plan

union all

select    [head], [year], 'Magh' [Month], [Magh]

from     Tbl_plan

union all

select    [head], [year], 'Falgun' [Month], [Magh]

from     Tbl_plan

union all

select    [head], [year], 'Chaitra' [Month], [Chaitra]

from     Tbl_plan

union all

select    [head], [year], 'Baisakh' [Month], [Baisakh]

from     Tbl_plan

union all

select    [head], [year], 'Jestha' [Month], [Jestha]

from     Tbl_plan

union all

select    [head], [year], 'Asadh' [Month], [Asadh]

from     Tbl_plan

 

 

The above technique is more appropriate when the no. of columns is less.

If the data in Tbl_plan is to be shown directly in report (Excel Report, Crystal Report) then, pivoting can be directly done in the report from Tbl_plan, without needing to create additional view.

 

Read more...

Warning: Null value is eliminated by an aggregate or other SET operation.


If you are a programmer or database administrator, you must have come across this problem. But, this does not make a lot of difference usually. But we should be always aware of such warnings too.

This problem usually comes while using multiple joins and aggregate functions like sum(), avg(), etc in SQL Server. The main cause is due to the fact the while aggregating some data may have null. And we know that when we add, subtract, multiply or divide with null, it will return null. So, the warning alerts that the result may not be correct or aggregate function is returning null due to null value being manipulated with other numerical value.

Once in SQL, I encountered with same problem while using
Isnull(sum(e.tcd_amt),0)
in a query statement.

The reason is that e.tcd_amt is sometimes null so problem in aggregating.
So, I replaced the code with following.
sum(isnull(e.tcd_amt,0))

The code worked fine without warning as it changes the null value to 0 before summing up, so not a problem for other normal numerical values.

Read more...