Tuesday, October 30, 2012

Magic of Derived Tables


Using Derived Tables to Simplify the SQL Server Query Process

Problem
Sometimes querying data is not that simple and there may be the need to create temporary tables or views to predefine how the data should look prior to its final output.  Unfortunately there are problems with both of these approaches if you are trying to query data on the fly. 
With the temporary tables approach you need to have multiple steps in your process, first to create the temporary table, then to populate the temporary table, then to select data from the temporary table and lastly cleanup of the temporary table.
With the view approach you need to predefine how this data will look, create the view and then use the view in your query.  Granted if this is something that you would be doing over and over again this might make sense to just create a view, but let's look at a totally different approach.

Solution
With SQL Server you have the ability to create derived tables on the fly and then use these derived tables within your query.  In concept this is similar to creating a temporary table and then using the temporary table in your query, but the approach is much simpler, because it can all be done in one step.
Let's take a look at an example where we query the Sales database to try to find out how many customers fall into various categories based on sales.  The categories that we have predefined are as follows:
Ø  Total Sales between 0 and 5,000 = Micro
Ø  Total Sales between 5,001 and 10,000 = Small
Ø  Total Sales between 10,001 and 15,000 = Medium
Ø  Total Sales between 15,001 and 20,000 = Large
Ø  Total Sales > 20,000 = Very Large
There are several ways that this data can be pulled, but let's look at an approach using a derived table.
The first step is to find out the total sales by each customer, which can be done with the following statement.
SELECT   o.CustomerID, 
         SUM(UnitPrice * Quantity) AS TotalSales 
FROM     [Order Details] AS od 
         INNER JOIN Orders AS o 
           ON od.OrderID = o.OrderID 
GROUP BY o.CustomerID

This is a partial list of the output:
CustomerID
TotalSales
ALFKI 
4596.2000
ANATR
1402.9500
ANTON
7515.3500
...

WOLZA
3531.9500

The next step is to classify the TotalSales value into the OrderGroups that were specified above:
SELECT   o.CustomerID, 
         SUM(UnitPrice * Quantity) AS TotalSales, 
         CASE  
           WHEN SUM(UnitPrice * Quantity)  
               BETWEEN 0 AND 5000 THEN 'Micro' 
           WHEN SUM(UnitPrice * Quantity)  
               BETWEEN 5001 AND 10000 THEN 'Small' 
           WHEN SUM(UnitPrice * Quantity)  
               BETWEEN 10001 AND 15000 THEN 'Medium' 
           WHEN SUM(UnitPrice * Quantity)  
               BETWEEN 15001 AND 20000 THEN 'Large' 
           WHEN SUM(UnitPrice * Quantity)  
               > 20000 THEN 'Very Large' 
         END AS OrderGroup 
FROM     [Order Details] AS od 
         INNER JOIN Orders AS o  
          ON od.OrderID = o.OrderID 
GROUP BY o.CustomerID

This is a partial list of the output:
CustomerID
TotalSales
OrderGroup
ALFKI 
4596.2000
Micro
ANATR
1402.9500
Micro
ANTON
7515.3500
Small
...


WOLZA
3531.9500
Micro
The next step is to figure out how many customers fit into each of these groups and this is where the derived table comes into play.  Take a look at the following query which uses a derived table called OG.  What we are doing here is using the same query from the step above, but calling this derived table OG. Then we are selecting data from this derived table for our final output just like we would with any other query.  All of the columns that are created in the derived table are now available for our final query.
SELECT   OG.OrderGroup, 
         COUNT(OG.OrderGroup) AS OrderGroupCount 
FROM     (SELECT   o.CustomerID, 
                   SUM(UnitPrice * Quantity) AS TotalSales, 
                   CASE  
                     WHEN SUM(UnitPrice * Quantity)  
                       BETWEEN 0 AND 5000 THEN 'Micro' 
                     WHEN SUM(UnitPrice * Quantity)  
                       BETWEEN 5001 AND 10000 THEN 'Small' 
                     WHEN SUM(UnitPrice * Quantity)  
                       BETWEEN 10001 AND 15000 THEN 'Medium' 
                     WHEN SUM(UnitPrice * Quantity)  
                       BETWEEN 15001 AND 20000 THEN 'Large' 
                     WHEN SUM(UnitPrice * Quantity)  
                       > 20000 THEN 'Very Large' 
                   END AS OrderGroup 
          FROM     [Order Details] AS od 
                   INNER JOIN Orders AS o 
                     ON od.OrderID = o.OrderID 
          GROUP BY o.CustomerID) AS OG 
GROUP BY OG.OrderGroup

This is the complete list of the output from the above query.

OrderGroup
OrderGroupCount
Large
10
Medium
11
Micro
33
Small
15
Very Large
20

Tuesday, July 17, 2012

Query to Display Foreign Key Relationships and Name of the Constraint for Each Table in Database



SELECT K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT I1.TABLE_NAME, I2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS I1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE I2
ON I1.CONSTRAINT_NAME = I2.CONSTRAINT_NAME
WHERE I1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
ORDER BY 1,2,3,4

Wednesday, July 11, 2012

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;

2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as
SELECT subject, count(subject) 
FROM student_details 
WHERE subject != 'Science' 
AND subject != 'Maths' 
GROUP BY subject;
Instead of:
SELECT subject, count(subject) 
FROM student_details 
GROUP BY subject 
HAVING subject!= 'Vancouver' AND subject!= 'Toronto';

3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as
SELECT name 
FROM employee 
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age) 
FROM employee_details) 
AND dept = 'Electronics'; 
Instead of:
SELECT name 
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details) 
AND age = (SELECT MAX(age) FROM employee_details) 
AND emp_dept = 'Electronics';

4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.
For Example: Write the query as
Select * from product p 
where EXISTS (select * from order_items o 
where o.product_id = p.product_id)
Instead of:
Select * from product p 
where product_id IN 
(select product_id from order_items

5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as
SELECT d.dept_id, d.dept 
FROM dept d 
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);
Instead of:
SELECT DISTINCT d.dept_id, d.dept 
FROM dept d,employee e 
WHERE e.dept = e.dept;

6) Try to use UNION ALL in place of UNION.
For Example: Write the query as
SELECT id, first_name 
FROM student_details_class10 
UNION ALL 
SELECT id, first_name 
FROM sports_team;
Instead of:
SELECT id, first_name, subject 
FROM student_details_class10 
UNION 
SELECT id, first_name 
FROM sports_team;

7) Be careful while using conditions in WHERE clause.
For Example: Write the query as
SELECT id, first_name, age FROM student_details WHERE age > 10;
Instead of:
SELECT id, first_name, age FROM student_details WHERE age != 10;
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE first_name LIKE 'Chan%';
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE SUBSTR(first_name,1,3) = 'Cha';
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE first_name LIKE NVL ( :name, '%');
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE first_name = NVL ( :name, first_name);
Write the query as
SELECT product_id, product_name 
FROM product 
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)
Instead of:
SELECT product_id, product_name 
FROM product 
WHERE unit_price >= MAX(unit_price) 
and unit_price <= MIN(unit_price)
Write the query as
SELECT id, name, salary 
FROM employee 
WHERE dept = 'Electronics' 
AND location = 'Bangalore';
Instead of:
SELECT id, name, salary 
FROM employee 
WHERE dept || location= 'ElectronicsBangalore';
Use non-column expression on one side of the query because it will be processed earlier.
Write the query as
SELECT id, name, salary 
FROM employee 
WHERE salary < 25000;
Instead of:
SELECT id, name, salary 
FROM employee 
WHERE salary + 10000 < 35000;
Write the query as
SELECT id, first_name, age 
FROM student_details 
WHERE age > 10;
Instead of:
SELECT id, first_name, age 
FROM student_details 
WHERE age NOT = 10;
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

Friday, May 25, 2012

Table Variables Vs Temporary Tables

Feature
Table Variables
Temporary Tables
Scope
Current batch
Current session, nested stored procedures. Global: all sessions.
Usage
UDFs, Stored Procedures, Triggers, Batches.
Stored Procedures, Triggers, Batches.
Creation
DECLARE statement only.
CREATE TABLE statement.
SELECT INTO statement.
Table name
Maximum 128 characters.
Maximum 116 characters.
Column data types
Can use user-defined data types.
Can use XML collections.
User-defined data types and XML collections must be in tempdb to use.
Collation
String columns inherit collation from current database.
String columns inherit collation from tempdb database.
Indexes
Can only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement.
Indexes can be added after the table has been created.
Constraints
PRIMARY KEY, UNIQUE, NULL, CHECK, but they must be incorporated with the creation of the table in the DECLARE statement. FOREIGN KEY not allowed.
PRIMARY KEY, UNIQUE, NULL, CHECK. Can be part of the CREATE TABLE statement, or can be added after the table has been created. FOREIGN KEY not allowed.
Post-creation DDL (indexes, columns)
Statements are not allowed.
Statements are allowed.
Data insertion
INSERT statement (SQL 2000: cannot use INSERT/EXEC).
INSERT statement, including INSERT/EXEC.
SELECT INTO statement.
Insert explicit values into identity columns (SET IDENTITY_INSERT).
The SET IDENTITY_INSERT statement is not supported.
The SET IDENTITY_INSERT statement is supported.
Truncate table
Not allowed.
Allowed.
Destruction
Automatically at the end of the batch.
Explicitly with DROP TABLE statement. Automatically when session ends. (Global: also when other sessions have no statements using table.)
Transactions
Last only for length of update against the table variable. Uses less than temporary tables.
Last for the length of the transaction. Uses more than table variables.
Stored procedure recompilations
Not applicable.
Creating temp table and data inserts cause procedure recompilations.
Rollbacks
Not affected (Data not rolled back).
Affected (Data is rolled back).
Statistics
Optimizer cannot create any statistics on columns, so it treats table variable has having 1 record when creating execution plans.
Optimizer can create statistics on columns. Uses actual row count for generation execution plan.
Pass to stored procedures
SQL 2008 only, with predefined user-defined table type.
Not allowed to pass, but they are still in scope to nested procedures.
Explicitly named objects (indexes, constraints).
Not allowed.
Allowed, but be aware of multi-user issues.
Dynamic SQL
Must declare table variable inside the dynamic SQL.
Can use temporary tables created prior to calling the dynamic sql.

Tuesday, May 22, 2012

Difference between @@IDENTITY, SCOPE_IDENTITY, IDENT_CURRENT

What SCOPE_IDENTITY is

SCOPE_IDENTITY is:

  • SCOPE_IDENTITY returns the last IDENTITY value inserted into an IDENTITY column in the same scope.
  • SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.
  • A scope is a module; a Stored Procedure, trigger, function, or batch.
  • Thus, two statements are in the same scope if they are in the same Stored Procedure, function, or batch.
  • The SCOPE_IDENTITY() function will return the NULL value if the function is invoked before any insert statements into an identity column occur in the scope.

What IDENT_CURRENT is

IDENT_CURRENT is:

  • IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
  • IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.

What @@IDENTITY is

@@IDENTITY is:

  • @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
  • After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the last identity value generated by the statement.
  • If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL.
  • If multiple rows are inserted, generating multiple identity values, @@IDENTITY returns the last identity value generated.
  • The @@IDENTITY value does not revert to a previous setting if the INSERT or SELECT INTO statement or bulk copy fails, or if the transaction is rolled back.

Differences

The differences between them are:

  • SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions in that they return values inserted into IDENTITY columns.
  • SCOPE_IDENTITY and @@IDENTITY will return the last identity values generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope. A scope is a module; a Stored Procedure, trigger, function, or batch.