Tuesday, December 27, 2011

What is the use of Index

A database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of slower writes and increased storage space. Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records. The disk space required to store the index is typically less than that required by the table (since indices usually contain only the key-fields according to which the table is to be arranged, and exclude all the other details in the table), 


 Indexes speed up the querying process by providing swift access to rows in the data tables, similarly to the way a book’s index helps you find information quickly within that book.

SQL Optimization





Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.

SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.
For Example: Write the query as
SELECT id, first_name, last_name, age, subject FROM student_details;
Instead of:
SELECT * FROM student_details;9) To store large binary objects, first place them in the file system and add the file path in the database.
8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause. 
For Example: Write the query as
SELECT id FROM employee 
WHERE name LIKE 'Ramesh%' 
and location = 'Bangalore';
Instead of:
SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee 
WHERE name LIKE 'Ramesh%';

9) To store large binary objects, first place them in the file system and add the file path in the database.
10) To write queries which provide efficient performance follow the general SQL standard rules.
a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space
d) Right or left aligning verbs within the initial SQL verb


SQL Tuning

Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.



SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.
For Example: Write the query as
SELECT id, first_name, last_name, age, subject FROM student_details;
Instead of:
SELECT * FROM student_details;9) To store large binary objects, first place them in the file system and add the file path in the database.
8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause. 
For Example: Write the query as
SELECT id FROM employee 
WHERE name LIKE 'Ramesh%' 
and location = 'Bangalore';
Instead of:
SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee 
WHERE name LIKE 'Ramesh%';

9) To store large binary objects, first place them in the file system and add the file path in the database.
10) To write queries which provide efficient performance follow the general SQL standard rules.
a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space
d) Right or left aligning verbs within the initial SQL verb

SQL Alias


SQL Aliases are defined for columns and tables. Basically aliases is created to make the column selected more readable.



For Example: To select the first name of all the students, the query would be like:

Aliases for columns:

SELECT first_name AS Name FROM student_details;
or
SELECT first_name Name FROM student_details;
In the above query, the column first_name is given a alias as 'name'. So when the result is displayed the column name appears as 'Name' instead of 'first_name'.
Output:
Name
-------------
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra

Aliases for tables:

SELECT s.first_name FROM student_details s; 
In the above query, alias 's' is defined for the table student_details and the column first_name is selected from the table.
Aliases is more useful when
  • There are more than one tables involved in a query,
  • Functions are used in the query,
  • The column names are big or not readable,
  • More than one columns are combined together

Difference between DELETE and TRUNCATE Statements


DELETE Statement: This command deletes only the rows from the table based on the condition given in the where clause or deletes all the rows from the table if no condition is specified. But it does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the table and free the space containing the table.

Difference between DROP and TRUNCATE Statement

If a table is dropped, all the relationships with other tables will no longer be valid, the integrity constraints will be dropped, grant or access privileges on the table will also be dropped, if want use the table again it has to be recreated with the integrity constraints, access privileges and the relationships with other tables should be established again. But, if a table is truncated, the table structure remains the same, therefore any of the above problems will not exist.

Difference between TRUNCATE and DELETE


TruncateDelete
TRUNCATE is a DDL commandDELETE is a DML command
TRUNCATE TABLE always locks the table and page but not each rowDELETE statement is executed using a row lock, each row in the table is locked for deletion
Cannot use Where ConditionWe can specify filters in where clause
It Removes all the dataIt deletes specified data if where condition exists.
TRUNCATE TABLE cannot activate a trigger because the operation does not log individual row deletions.Delete activates a trigger because the operation are logged individually.
Faster in performance wise, because it doesn’t keep any logsSlower than truncate because, it keeps logs
Rollback is not possibleRollback is possible
 Drop all object’s statistics and marks like High Water Mark free extents and leave the object really empty with the first extent. zero pages are left in the tablekeeps object’s statistics and all allocated space. After a DELETE statement is executed, the table can still contain empty pages.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction loThe DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row
If the table contains an identity column, the counter for that column is reset to the seed value that is defined for the columnDELETE retain the identity




Delete works at row level, thus row level constrains apply
Restrictions on using Truncate Statement 
1. Are referenced by a FOREIGN KEY constraint. 
2. Participate in an indexed view. 
3. Are published by using transactional replication or merge replication.

Sunday, December 4, 2011

Copy table from one database to another database

Example:

             SELECT * INTO db1.dbo.table1
             FROM db2.dbo.table2

Please mind that this query only copies table schema and data only.

All constraints, indexes, statatics, you need to use alternatives 

Database BackUp and Restore Script

For .Net developer a very common task is to take reguler backup and restore of SQL Server Database. Most of the time developer does that thru UI of Sql Server Management Studio. It is acully nice to know the Scripts which we can run and take backup and restore easily.


       To BackUp :-      
     BACKUP DATABASE [DatabaseName] TO DISK = 'C:\FileName.bak' WITH FORMAT
       To Restore :-
           RESTORE DATABASE [DatabaseName] FROM DISK = 'C:\FileName.bak'


Also when ever you do any database opration thru UI of Sql Server Management Studio you can always have look to the Script behind that opration. Its good practise to look at the script run by Sql Server to do any database realted opration.

How to insert multiple records with single insert query


    USE [Demo]
         GO
    --Create Demo Table—
       
    CREATE TABLE DemoTable(Data VARCHAR(50))       

    --The way we used to—

    INSERT INTO DemoTable(Data)
        VALUES ('DATA 1');
    INSERT INTO DemoTable(Data)
        VALUES ('DATA 2');
    INSERT INTO DemoTable(Data)
        VALUES ('DATA 3');
    INSERT INTO DemoTable(Data)
        VALUES ('DATA 4');
       
       
Solution 1:

    CREATE TABLE DemoTable(Data VARCHAR(50))       


    INSERT INTO DemoTable(data)
        VALUES ('DATA 1'),('DATA 2'),('DATA 3'),('DATA 4');


Solution 2:

    CREATE TABLE DemoTable(Data VARCHAR(50))       

    INSERT INTO DemoTable(data)
    SELECT 'DATA 1'
    UNION ALL
    SELECT 'DATA 2'
    UNION ALL
    SELECT 'DATA 3'
    UNION ALL
    SELECT 'DATA 4'