T-SQL script to find the highly populated tables in database

Sometimes we need to check which tables of our database is highly populated. Below is the T-SQL Script which we can use to find out that.

SELECT 
    t.NAME AS TableName,
    i.name as indexName,
    sum(p.rows) as RowCounts,
    sum(a.total_pages) as TotalPages, 
    sum(a.used_pages) as UsedPages, 
    sum(a.data_pages) as DataPages,
    (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
    (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
    (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM 
    sys.tables t
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE ‘dt%’ AND
    i.OBJECT_ID > 255 AND   
    i.index_id <= 1
GROUP BY 
    t.NAME, i.object_id, i.index_id, i.name 
–ORDER BY 
—    object_name(i.object_id) 

ORDER BY SUM(p.rows) DESC

Posted in DBA, SQL Advanced, SQL Server | Tagged , | 27 Comments

SQL Script to find the last executed commands on the SQl Server

Sometimes we needs to find out the last executed commands on the database server. 
Below is the SQL script share by one of my friend Ken Watson to find out the last executed queries.

SELECT usecounts, cacheobjtype, objtype, text 
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle) 
WHERE usecounts > 1 
ORDER BY usecounts DESC; 

About Ken
He is working as SQL DBA. 
Blog:-  interflextech.com/blog
Twitter:- @interflextech

Posted in DBA, SQL Advanced, SQL Server | Tagged | 30 Comments

Script to find the Fragmentation of indexes

Script to find the Fragmentation in Indexes

In my previous articles, Fragmentation in SQL Server and Rebuild And Reorganization of Indexes , we talk in detail about Index fragmentation and rebuild or reorganize the indexes. Below is the SQL script which we can use to find the Fragmentation in Indexes created on the database.

SELECT OBJECT_NAME(OBJECT_ID), index_id,index_type_desc,index_level,
avg_fragmentation_in_percent,avg_page_space_used_in_percent,page_count
FROM sys.dm_db_index_physical_stats (DB_ID( N'Database name') , 
NULL, NULL, NULL , 'SAMPLED') ORDER BY avg_fragmentation_in_percent DESC

avg_fragmentation_in_percent represents  logical fragmentation.

If this value is higher than 5% and less than 30%, then we should use

ALTER INDEXREORGANIZE

If this value is higher than 30%, then we should use

ALTER INDEX REBUILD WITH (ONLINE = ON)

Please note:- As per MSDN, rebuilding an index can be executed online or offline. Reorganizing an index is always executed online. To achieve availability similar to the reorganize option, you should rebuild indexes online.

Re-commentated Articles On Indexes

Fragmentation in SQL Server

Indexes in SQL Server

Rebuild And Reorganization of Indexes

 

 

Posted in DBA, SQL Advanced, SQL Indexes, SQL Server | Tagged , | 33 Comments

Script to find all the running queries/jobs on the Database Server

Below is the query to find out all the Queries and their details like SSID etc. running on the SQL Server from all databases. It helps in finding out which queries/jobs running on the server. It can be helpful in detecting the blocking queries also.

USE Master
SET NOCOUNT ON   
SET ANSI_PADDING ON
SET QUOTED_IDENTIFIER ON  
DECLARE @record_id int, @SQLProcessUtilization int, @CPU int,@EventTime datetime–,@MaxCPUAllowed int   
select  top 1  @record_id =record_id,
      @EventTime=dateadd(ms, -1 * ((SELECT ms_ticks from sys.dm_os_sys_info) – [timestamp]), GetDate()),– as EventTime,
      @SQLProcessUtilization=SQLProcessUtilization,
      –SystemIdle,
      –100 – SystemIdle – SQLProcessUtilization as OtherProcessUtilization,
      @CPU=SQLProcessUtilization + (100 – SystemIdle – SQLProcessUtilization) –as CPU_Usage
from (
      select
            record.value(‘(./Record/@id)[1]’, ‘int’) as record_id,
            record.value(‘(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]’, ‘int’) as SystemIdle,
            record.value(‘(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]’, ‘int’) as SQLProcessUtilization,
            timestamp
      from (
            select timestamp, convert(xml, record) as record
            from sys.dm_os_ring_buffers
            where ring_buffer_type = N’RING_BUFFER_SCHEDULER_MONITOR’
            and record like ‘%<SystemHealth>%’) as x
      ) as y
order by record_id desc 
SELECT           
            x.session_id as [Sid],
            COALESCE(x.blocking_session_id, 0) as BSid,
            @CPU as CPU,   
            @SQLProcessUtilization as SQL,  
                             
            x.Status,  
            x.TotalCPU as [T.CPU],
            x.Start_time,    
            CONVERT(nvarchar(30), getdate()-x.Start_time, 108) as Elap_time, –x.totalElapsedTime as ElapTime,
            x.totalReads as [T.RD], — total reads
            x.totalWrites as [T.WR], –total writes     
            x.Writes_in_tempdb as [W.TDB],
            (
                  SELECT substring(text,x.statement_start_offset/2,
                        (case when x.statement_end_offset = -1
                        then len(convert(nvarchar(max), text)) * 2
                        else x.statement_end_offset end – x.statement_start_offset+3)/2)
                  FROM sys.dm_exec_sql_text(x.sql_handle)
                  FOR XML PATH(”), TYPE
            ) AS Sql_text,
            db_name(x.database_id) as dbName,
            (SELECT object_name(objectid) FROM sys.dm_exec_sql_text(x.sql_handle)) as object_name,           
            x.Wait_type,
            x.Login_name,
            x.Host_name,
            CASE LEFT(x.program_name,15)
            WHEN ‘SQLAgent – TSQL’ THEN 
            (     select top 1 ‘SQL Job = ‘+j.name from msdb.dbo.sysjobs (nolock) j
                  inner join msdb.dbo.sysjobsteps (nolock) s on j.job_id=s.job_id
                  where right(cast(s.job_id as nvarchar(50)),10) = RIGHT(substring(x.program_name,30,34),10) )
            WHEN ‘SQL Server Prof’ THEN ‘SQL Server Profiler’
            ELSE x.program_name
            END as Program_name,
            x.percent_complete,
            x.percent_complete, 
            (
                  SELECT
                        p.text
                  FROM
                  (
                        SELECT
                             sql_handle,statement_start_offset,statement_end_offset
                        FROM sys.dm_exec_requests r2
                        WHERE
                             r2.session_id = x.blocking_session_id
                  ) AS r_blocking
                  CROSS APPLY
                  (
                  SELECT substring(text,r_blocking.statement_start_offset/2,
                        (case when r_blocking.statement_end_offset = -1
                        then len(convert(nvarchar(max), text)) * 2
                        else r_blocking.statement_end_offset end – r_blocking.statement_start_offset+3)/2)
                  FROM sys.dm_exec_sql_text(r_blocking.sql_handle)
                  FOR XML PATH(”), TYPE
                  ) p (text)
            )  as blocking_text,
            (SELECT object_name(objectid) FROM sys.dm_exec_sql_text(
            (select top 1 sql_handle FROM sys.dm_exec_requests r3 WHERE r3.session_id = x.blocking_session_id))) as blocking_obj
       
      FROM
      (
            SELECT
                  r.session_id,
                  s.host_name,
                  s.login_name,
                  r.start_time,
                  r.sql_handle,
                  r.database_id,
                  r.blocking_session_id,
                  r.wait_type,
                  r.status,
                  r.statement_start_offset,
                  r.statement_end_offset,
                  s.program_name,
                  r.percent_complete,               
                  SUM(cast(r.total_elapsed_time as bigint)) /1000 as totalElapsedTime, –CAST AS BIGINT to fix invalid data convertion when high activity
                  SUM(cast(r.reads as bigint)) AS totalReads,
                  SUM(cast(r.writes as bigint)) AS totalWrites,
                  SUM(cast(r.cpu_time as bigint)) AS totalCPU,
                  SUM(tsu.user_objects_alloc_page_count + tsu.internal_objects_alloc_page_count) AS writes_in_tempdb
            FROM sys.dm_exec_requests r
            JOIN sys.dm_exec_sessions s ON s.session_id = r.session_id
            JOIN sys.dm_db_task_space_usage tsu ON s.session_id = tsu.session_id and r.request_id = tsu.request_id
            WHERE r.status IN (‘running’, ‘runnable’, ‘suspended’)
            GROUP BY
                  r.session_id,
                  s.host_name,
                  s.login_name,
                  r.start_time,
                  r.sql_handle,
                  r.database_id,
                  r.blocking_session_id,
                  r.wait_type,
                  r.status,
                  r.statement_start_offset,
                  r.statement_end_offset,
                  s.program_name,
                  r.percent_complete
      ) x
      where x.session_id <> @@spid
      order by x.totalCPU desc
GO

I have get these helpful standard scripts through other sites like MSDN, technet etc. Just sharing so that other can also get benefited by using it.

Posted in DBA, SQL Advanced, SQL Server | Tagged , | 3 Comments

How to pass Microsoft Certification Exams

Many times I was asked how to pass Microsoft certifications and how difficult it is. In my point of view, it simple to crack Microsoft certification exams if you have worked hard on basic concepts and implemented most of the questions and scenarios mention in your study books/blogs on your system.

1) Take out the list of all the topics which are the part of your certification exams. You can take this from the Microsoft certification site.

2) Buy a study book specific for Microsoft exam preparation. This book will help you in tracking of topics which you have covered and which is remaining. Also these books contains practice sessions which help in passing the examination.
In my case, I bought the book recommended by the Microsoft and its practices examples help me a lot in passing the Microsoft certification

3)Prepare hard for each topic. Make sure you have a very good conceptual understanding of most of the topics covered in the exam. There are lots of blogs/forums where one can find good knowledge about these topics individually. 

4) Try to implements maximum practices questions and scenarios found in the study book and blogs in your system. More you practice these question easier it become to pass the examinations

6) Purchase Microsoft exam voucher and fixed the date at which you are comfortable. Sometimes Microsoft exam comes with offer where one retake is free. So if you failed in first attempt you can retry once more free of cost. I also benefited by this offer.

7) Be calm at the examination and read the questions carefully. Sometimes you can get the hints of possible answers from reading the question itself.

8) Even if you didn’t get the passing score don’t be disheartened. Few people passed the exam in their first attempt. Most of the people takes around 2 -3 attempts for passing the certification exams.

Please don’t go for dump or question bank offered by many sites as you may pass the exam but you never get the knowledge and the basic purpose of getting the certification get defeated. There is no short cut to success.When you pass any certification, expectation become high from you and without knowledge, it start hurting your changes of getting good job by using your certification.

Even if you not able to pass the exam in first attempt, the knowledge you get while preparing for your exam will put you ahead from the other people.

One can also read about the benefits of Microsoft examination from this site.

If you any query/question/feedback regarding this article you can drop a mail to us at askvivekjohari@gmail.com.

Posted in Miscellaneous, SQL Advanced, SQL Server | Tagged , | 15 Comments

Interview questions for database developer

Technical Round Database Interview Questions

1) What are the different types of Trace flags which we used for detecting the Deadlock?
2) What are the different types of database backups?
3) How do you perform the Error handling in SQL Server?
4) What is the ACID property in SQL Server?
5) What are the best practices in Database programming?
6) What are the different isolation level in SQL Server
7) What is the default isolation level in SQL Server
8) What is dirty read in SQL Server
9) What are the Serializable isolation level in SQL Server
10)What are the Rank functions in SQL server
11) What is Replication in SQL Server
12) What is the stuff function in SQL Server?
13) What is the Difference between Stuff command and Replace command in SQL Server
14) What is the merge command in SQL Server?
15) What is the Pivot/Unpivot table in SQL Server?
16) What is Derived table in SQL Server?
17) What is the Output clause in SQL Server?
18) What is the temporary tables in SQL Server?
19) What are the different types of database in SQL Server?
20) What is CTE in SQL Server?
21) What are the benefits of using CTE SQL Server  
22) What are cursors in SQL Server?
23) What are Views in SQL Server?
24) What are Triggers in SQL Server?
25) What are magic tables in SQL Server?
26) What are the difference between Stored Procedure and SQL triggers in SQL Server?
27)If no rows are affected by the SQL query, will after trigger will execute?
28) How can we improve the performance of an stored procedure?
29) What are the heap table in SQL Server?
30) Where we need to use table variable and where we should use temporary tables?
31) What is log shipping in SQL Server?
32) What is fragmentation in SQL Server?
33) What is the difference between logical and physical fragmentation?
34) In which database temporary tables are created?
35) What is the difference between Except command and Intersect command?
36) What is the BCNF in SQL Server?
37) What is database collation?
38) Suppose there are two
tables A and B and we need to write 3 SQL queries which returns
the record set as shown in the below figure.
 
39) Suppose we have to
design a database in which employees can work on multiple projects.There
are many designation defined in the organization to which each employee
can belongs.
 
For
example, Software engineer, Team lead, Project Manager, Project lead,
QC engineer, QC Lead, QC manager etc. An employee can belong to one
designation
at a time.  It means at a time an employee can either be Software
engineer or team lead or project manager but not software engineer as
well team lead at a same time.

Also the projects can work on different technologies like .Net, SQL
Server, Oracle, HTML5 etc. Every project has a start data and end date. A
project can work can include many technologies like .net, SQL Server ,
Java script, HTML5 etc. Most of the time every project work include a
front end server technology like JAVA. Asp.net, uses Java script, HTML,
CSS as client side technologies and SQL Server, oracle as back end
database server. So In this ways a project work can include many
technologies as in above example,  suppose a project can use Asp.net as
server end front end technology, java script, HTML, CSS , AJAX as client
side technology and SQL server as back end database server.

What should be the design the database schema (tables, their foreign keys, primary keys etc.?

40) Suppose we have a table named tbl_charactername have only one column say “charactername”.

It contains 10 rows. First 5 rows contains “Vivek Johari” and the next 5 rows contains “Abhinav Golwalkar”
tbl_charactername
———————
Vivek Johari
Vivek Johari
Vivek Johari
Vivek Johari
Vivek Johari
Abhinav Golwalkar
Abhinav Golwalkar
Abhinav Golwalkar
Abhinav Golwalkar
Abhinav Golwalkar
Now we need a SQL Query which can return the result in the form
Desired Result:-
Vivek Johari
Abhinav Golwalkar
Vivek Johari
Abhinav Golwalkar
Vivek Johari
Abhinav Golwalkar
Vivek Johari
Abhinav Golwalkar
Vivek Johari
Abhinav Golwalkar

Query should work even if the table has 30 rows with first 15 contains “vivek johari” and next 15 contains “Abhinav Golwalkar” or 40 rows with first 20 contains “vivek johari” and next 20 contains “Abhinav Golwalkar” etc. But output should contains “Vivek Johari” and “Abhinav Golwalkar” in alternate rows.
41)  Suppose we have a table says tbl_students whose structure is given below:-

Create table tbl_students(Studentid int identity(1,1) , Studentname nvarchar(150))

Suppose it contains the following data:-

Studentid  Studentname
1               Vivek Johari
2               Chandra Singh
4               Avinash Dubey
6               Akhil
7               Sunny Rana
10             Saurabh

As one can see from the data that some rows are deleted from the table as some studentids are missing.

So write a query which gives the studentid which are deleted from this table
Project Manager Round Questions:-

1) Give me your brief introduction.
2) What your current project and your role in it?
3) How is your team size?

4) what is the hierarchy in your organization?

5) Have you any experience of DBA activity?
6) How big your database size?
7) How you optimize database (same technical question but this time PM just want to know just an overview)?
8) What best practices you follow in your company?
9) Any tools your company uses for database designing?

10) Do your company follow Agile methodology ?

11) Any challenges you faces in your current project?
12) Why you want to change your current organization
13) Would you like to work on C#, web services, Java (in case of Oracle) if required?
14) How early you can join(want to know your notice period or possibility of early joining)?
15) Do you want to ask any question from us?

Posted in Interview Questions | Tagged | 32 Comments

My Best LinkedIn Articles

Posted in Miscellaneous | Tagged | 21 Comments

My Best Technical Sites and Blogs

Many times my friends ask me which technical sites they should refers for finding the solutions, so below is the list of tech sites which I used to refer most of the times for learning technologies and finding the solutions

Mssqltips.com:- I like this site because I find here some very good tutorials in SQL which are very simple to understand and gives some good knowledge for a person which is not expert in SQL Server.

Simple-talk.com:- I love this site since it has some brilliant authors who share their knowledge through some very good articles.  
Technet.microsoft.com:- This is Microsoft sites where you can get help on any topic however small it may be. Some in depth information with easy to understand language.
Stackoverflow.com:- This is one of my favorite discussion forum where you can get the solutions of most of your problems. Also from multiple answers , you can also mention which is working or which is best which help others.
Codeproject.com:- This site needs no introduction as it contains lots of articles on each technology. Lots of technical professional share their knowledge on this site. You can ask your question in this site ask question section. You can get many quality articles on this site. Also best articles of the month competition is always going on where you can win some good prizes by submitting your articles and winning the competition. 
Techmixing.com:-This is my blog where I share my technical knowledge though articles. I always reads the articles on this site before going for any interview or whenever I needs to brush up my knowledge. So always trying to maintains the quality of articles on this site.
SQLServerCentral.com:- Like Simple-talk, this is one of the best site for database. Have so many brilliant database experts as its author. Daily publish so many quality articles and also mentions good articles from other sites too. Its Question of the Day sections always comes up with a very good objective questions.
Sqlauthority.com:- Whenever you search for any SQL topic or issue , Google always show the link of this site in first few entries. Run by one of the best Indian database legend Pinal Dave, this site contains lots of SQL articles from small to complex topics. This is the site which helps me a lot in learning the SQL Server.
  
Pluralsight.com:- A video tutorial site contains lots of video tutorials for each
and every technology. All tutorials contains good explanations of the concepts with some very good demo. You can also took pre course online test to judge your knowledge before starting the course and also took post course test to judge your increased knowledge.You only has to subscribe on it which cost you some monthly fees. It has 2 options of subscription

Developer.android.com:-This is the best site for learning Android development. All tutorials on this site has been written in a very simple language which is easy to understand. I must say it is a must read site for any developer who want to learn android or working on it.
There are some other popular sites also like beyondrelational.com, C#corner, DatabaseJournal.com, Tutorialpoint.com which you can refers for finding your solutions. If you refers some other quality technical site or blog, please mention it as a comment so that others also get benefited. 
Posted in Miscellaneous, SQL Server, SQL Tips | Tagged | 6 Comments

SQLTea – New SQL tutorial app in Google play store

SQLTea – Our new SQL Tutorial App on Google Play Store

We are happy to announce our new SQL tutorial app SQLTea  ( Native android app) for SQL learning which includes articles from this blog.

This application includes 

1) Articles for basic concepts like Normalization, Constrains, Joins, SQL Functions, SQL commands etc and also advance concepts like SQL Triggers, Views, Cursors, Stored Procedures and many more.
2) Every article is explained with the help of examples.
Techmixing.com new apptechmixing.com new app

3) Once installed, it will work in offline mode (No Internet needed). You can read articles easily even if you don’t have Internet connections

4) Includes many popular articles from this blog.
5) Light weight and fast
6) Will going to frequently update this App with new blog articles.
7) Simple to use and navigates.
So please download this app and gives your valuable comments on it.
Posted in Interview Questions, Miscellaneous | Tagged , | 18 Comments

How to restore database backup in SQL SERVER

In this article, I am going to explain the process of  Database restoration using the SQL Server Management Studio. In this article, I will try to explain this process in a simple way so that a database developer having little knowledge of DBA can restore that database using the database backup.

For database restoration process, we need to follow the below steps:-

Step 1:- Open the SQL Sever Management Studio. For this we have to follow the following path:-

START –> All Programs –> Microsoft SQL Server 2008R2 –> Click on SQL Sever Management Studio (SSMS) –> Open the SQL Server Management Studio using Login information (Username & password or Window authentication )

Please note:- Above path can be changed depending on the Window version.

Step 2:- Once SQL Sever Management Studio is opened, opened the Object Explorer. By default it will be already opened. If it is not opened, then follow the below steps to open it.

Click on the View(Top menu) –> Click on Object Explorer.

Step 3:- Under the Databases node, select the database for Restoration and right click on it. Then choose Tasks, click on Restore and then choose the Database… as shown in the below figure. Here we choose the Company_DB as database.

Select Database for restore process

Step 4:- On the click of Database.. link,  we get the Restore Database window. In this window, we can select the database backup file, first by selecting the Device radio button and then click on the Add button, as shown in the below figure:-

Select Backup file location

Step 5:- When we click on the Add button, Locate Backup File Window is opened. On this window, we have to choose the backup file of the database as shown in the below figure.

Select Database backup file

Step 6:- When user selected the database backup file and click on the OK button, it will close the Locate Backup File window. Now on the Restore database window we can see the selected database backup file as shown in the below figure.

Selected backup file

Step 7:- When we click on the Options link, below screen will be shown

Database restoration Options
In this screen, we can see many options like overwrite the existing database and many others. We can leave this screen with default values. we usually choose the option of overwrite the existing database, but user can choose other options as per his/her requirement.

If you want to know this process and its all option in detail, you can refer below link of MSDN

Restore a Database Backup (SQL Server Management Studio)

DMCA.com
Posted in SQL Advanced, SQL Database Restoration, SQL Server | Tagged , | 30 Comments