Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Friday, 17 November 2017

GROUPBY VS PARTITIONBY

They're used in different places. PARTITION BY is analytic, while GROUP BY is aggregate. In order to use PARTITION BY, you have to contain it with an OVER clause.

GROUP BY

1. It normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row.
2. It actually groups the result set returning one row per group, which results therefore in SQL Server only allowing in the SELECT list aggregate functions or columns that are part of the GROUP BY clause (in which case SQL Server can guarantee that there are unique results for each group).
GROUP BY modifies the entire query, like:
select customerId, count(*) as orderCount
from Orders
group by customerId

PARTITION BY

1. It divides the result set into partitions. The window function is applied to each partition separately and computation restarts for each partition.
2. It does not affect the number of rows returned, but it changes how a window function's result is calculated.
3. It doesn't actually roll up the data. It allows you to reset something on a per group basis.
Partition by just works on a window function, like row_number:
select row_number() over (partition by customerId order by orderId)
    as OrderNumberForThisCustomer
from Orders

Friday, 1 September 2017

Difference between Inner Join and Left Semi Join

Semi joins will not have any syntax in SQL.
The following are the logical join operators that SQL Server supports:
  • Inner join
  • Outer join
  • Cross join
  • Cross apply
  • Semi-join
  • Anti-semi-join

An INNER JOIN returns the columns from both tables. A LEFT SEMI JOIN only returns the records from the left-hand table. It's equivalent to (in standard SQL):

SELECT name 
FROM table_1 a 
WHERE EXISTS(
SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the column of right-side table, an INNER JOIN will return one row for each matching column, while a LEFT SEMI JOIN only returns the matching rows from the left table. That's why you're seeing a different number of rows in your result.

Example:

Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:

TableA:
Id Data
1 DataA11
1 DataA12
1 DataA13
2 DataA21
3 DataA31

TableB:
Id Data
1 DataB11
2 DataB21
2 DataB22
2 DataB23
4 DataB41

Inner Join on column Id will return columns from both the tables and only the matching records:
Id Data Id Data
1 DataA11  1 DataB11
1 DataA12  1 DataB11
1 DataA13  1 DataB11
2 DataA21  2 DataB21
2 DataA21  2 DataB22
2 DataA21  2 DataB23

Left Join (or Left outer join) on column Id will return columns from both the tables and matching records with records from left table (Null values from right table):
Id Data Id Data
1 DataA11  1 DataB11
1 DataA12  1 DataB11
1 DataA13  1 DataB11
2 DataA21  2 DataB21
2 DataA21  2 DataB22
2 DataA21  2 DataB23
3 DataA31

Right Join (or Right outer join) on column Id will return columns from both the tables and matching records with records from right table (Null values from left table):
Id Data Id Data
1 DataA11 1 DataB11
1 DataA12 1 DataB11
1 DataA13 1 DataB11
2 DataA21 2 DataB21
2 DataA21 2 DataB22
2 DataA21 2 DataB23
4 DataB41
    
Outer Join (or Full outer join) on column Id will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):
Id Data Id Data
1 DataA11 1 DataB11
1 DataA12 1 DataB11
1 DataA13 1 DataB11
2 DataA21 2 DataB21
2 DataA21 2 DataB22
2 DataA21 2 DataB23
3 DataA31
4 DataB41
    
Left Semi Join on column Id will return columns only from left table and matching records only from left table:
Id Data
1 DataA11
1 DataA12
1 DataA13
2 DataA21

Please refer the below link for other types of semi joins.
https://blog.jooq.org/2015/10/13/semi-join-and-anti-join-should-have-its-own-syntax-in-sql/
https://blogs.msdn.microsoft.com/craigfr/2006/07/19/introduction-to-joins/
https://technet.microsoft.com/en-us/library/ms191255(v=sql.105).aspx

Thursday, 31 August 2017

Difference between Logical and Physical database joins

Most of us know about JOINS in SQL Server and their types. But do we really know how they are interpreted in SQL Server internally. Today I found lot of informative, interesting and important sources regarding Logical and Physical joins in SQL Server (links below).

JOINS are mainly classified into 2 types:

1. Logical Joins: These joins are simple joins that we apply in our SQL queries, like INNER JOIN, RIGHT/LEFT OUTER JOIN, CROSS JOIN, OUTER APPLY, etc.

2. Physical Joins: These are the joins that users don’t use/write in their SQL queries. Instead these are implemented inside SQL Server engine as operators or algorithms to implement the Logical Joins. Their types are Nested Loop, Merge and Hash.
For a particular SQL query when you try to view an Estimated Execution Plan or execute a query by selecting Actual Execution Plan, you can clearly see these Physical Joins under the Execution Plan tab in SSMS.


References for Physical Joins:
Nested Loop Joins: https://blogs.msdn.microsoft.com/craigfr/2006/07/26/nested-loops-join
Merge Joins: https://blogs.msdn.microsoft.com/craigfr/2006/08/03/merge-join/
Hash Joins: https://blogs.msdn.microsoft.com/craigfr/2006/08/10/hash-join/

Tuesday, 29 August 2017

Maximum number of rows that can be stored in Temp table or a Table variable.

Temp Table:

No, there is no records limit for temporary table (the limit is the disk space). But be careful, because temporary tables are physically created in tempdb database, and this database must be placed on the disk with appropriate size.
The differences between tempdb and any other database are minimal, especially when it comes to limits. If you can store it in a user table, you can store it in a temporary table as well. It does not have to fit into RAM as the tempdb is stored on disk just like any other database (only with more aggressive caching and less logging).

Table Variable:

As such the official MSDN site where the Maximum Capacity Specifications for SQL Server there is no such upper limit defined for table variables because it depends on the database size and the free memory available for the storage. You can also refer the MSDN forum discussing the same; Maximum Capicity of Table Variable

Temp table VS Table variable in SQL Server



There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp) listed below:

  1. As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables.
  2. Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.
  3. Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. 
  4. Table variables don't participate in transactions and SELECTs are implicitly with NOLOCK. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!
  5. When using a #temp table within a user transaction locks can be held longer than for table variables (potentially until the end of transaction vs end of statement dependent on the type of lock and isolation level) and also it can prevent truncation of the tempdb transaction log until the user transaction ends. So this might favour the use of table variables.
  6. If you will be repeatedly adding and deleting large numbers of rows from the table then use a #temporary table. That supports TRUNCATE (which is more efficient than DELETE for large tables) and additionally subsequent inserts following a TRUNCATE can have better performance than those following a DELETE.
  7. If the optimal plan using the table will vary dependent on data then use a #temporary table. That supports creation of statistics which allows the plan to be dynamically recompiled according to the data (though for cached temporary tables in stored procedures the recompilation behaviour needs to be understood separately).
  8. If the optimal plan for the query using the table is unlikely to ever change then you may consider a table variable to skip the overhead of statistics creation and recompiles (would possibly require hints to fix the plan you want).
  9. If the source for the data inserted to the table is from a potentially expensive SELECT statement then consider that using a table variable will block the possibility of this using a parallel plan.
  10. If you need the data in the table to survive a rollback of an outer user transaction then use a table variable. A possible use case for this might be logging the progress of different steps in a long SQL batch.
  11. Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.
  12. Within stored routines, both table variables and temporary tables can be cached. The metadata maintenance for cached table variables is less than that for #temporary tables. This can cause additional contention on system tables under conditions of high concurrency. Additionally, when dealing with small quantities of data this can make a measurable difference to performance.
  13. You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.
  14. You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).
  15.  If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.
  16. Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (ref). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.
  17. Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.

Monday, 27 July 2015

Filtered Indexes?

Filtered index:

Filtered indexes for SQL Server were introduced in SQL Server 2008. Put simply, filtered indexes are nonclustered indexes that have the addition of a WHERE clause. Although the WHERE clause in a filtered index allows only simple predicates, it provides notable improvements over a traditional nonclustered index. This allows the index to target specific data values – only records with certain values will be added to the index – resulting in a much smaller, more accurate, and more efficient index.
The basic syntax for creating a filtered index is:

CREATE NONCLUSTERED INDEX <index name> ON <table> (<columns>) WHERE <criteria>; GO

Advantages of using filtered indexes

Reduced index maintenance costs. Insert, update, delete, and merge operations are not as expensive, since a filtered index is smaller and does not require as much time for reorganization or rebuilding.
Reduced storage cost. The smaller size of a filtered index results in a lower overall index storage requirement.
More accurate statistics. Filtered index statistics cover only the rows the meet the WHERE criteria, so in general, they are more accurate than full-table statistics.
Optimized query performance. Because filtered indexes are smaller and have more accurate statistics, queries and execution plans are more efficient.

Limitations

  • Statistics may not get updated often enough, depending on how often filtered column data is changed. Because of how SQL Server decides when to update statistics (when about 20% of a column’s data has been modified), statistics could become quite out of date. The solution to this issue is to set up a job to run UPDATE STATISTICS more frequently.
  • Filtered indexes cannot be created on views. However, a filtered index on the base table of a view will still optimize a view’s query.
  • XML indexes and full-text indexes cannot be filtered. Only nonclustered indexes are able to take advantage of the WHERE clause.
  • The WHERE clause of a filtered index will accept simple predicates only.

Friday, 1 August 2014

Database View's


A view is a virtual table which can be created over a single or multiple tables.
Eg: CREATE VIEW view_name1 AS (SELECT col1, col2 FROM table_name WHERE col2>25)
OR
CREATE VIEW view_name2 AS (SELECT t1.col1, t1.col3, t2.col1, t2.col4 FROM table_name1 LEFT OUTER JOIN table_name2 ON t1.col2=t2.col2 )

Internals:

  1. There will not be any physical existence for a view.
  2. Actually only the select query which is used in creating a view will be saved under the view name (“view_name” in the above example).
  3. View is a separate database object like other's (table, procedure, function, login, trigger, cursor, sequence and etc.,).
  4. So, a view can be queried like table.
    Eg: SELECT colx, coly FROM view_name1
  5. The above query will be thought of the below:
    Eg: SELECT colx, coly FROM (SELECT col1, col2 FROM table_name WHERE col2>25)-> “This query is taken from the creation statement of view 'view_name1' “.

Are the Views Up-datable?

  1. As we already know that there is no physical existence of view and we have already seen that, data is retrieved from original underlying table when the view is queried.
  2. So, if we update a view then the underlying table should be updated. And the update operation should get executed without any problems.
  3. Hold on..!
  4. Yes, view are up-datable. But only when they are created on a single table as in 'view_name1'.
  5. Hmm. Why so ???
  6. See the creation statement of 'view_name2'. This view is created on joining two tables. In this example in particular, all the column values of the table 'table_name2' will be displayed as NULL's in the result set except the values which satisfy the join condition (ON t1.col2=t2.col2). But the original table 'table_name2' will not be having NULL values in those positions of the result set.
  7. For this reason views which are created from multiple tables cannot be updated.

Usage:


  1. Views are created to grant limited access to the users on the database tables. A security measure.
  2. It will be very efficient to retrieve the actual desired data rather than the entire table. This can be done by creating a view on the desired data and then retrieving that data from the view. A performance measure.

Sunday, 6 July 2014

Rules of GroupBy Clause


Group functions are the built-in SQL functions that act on groups of rows and return one value for the entire group.

Rules of GroupBy clause

The name may be a Column reference. Such a Column is called a grouping Column: its values will be grouped for the final result.

* The group by clause should contain all the columns in the select list expect those used along with the group functions.

Example:
Let us take the below query,
SELECT location, dept, SUM (salary) 
FROM employee 
GROUP BY location, dept;

In the above query, if the columns 'location' and 'dept' are not specified next to GroupBy clause, then it results an error.


* It is upto us to include aggregated columns next to GroupBy. Meaning, in the above mentioned example it is upto us to include column 'salary' next to the GroupBy clause.

* We cannot include a column next to GroupBy, if that particular column is not selected.

Monday, 24 February 2014

"SELECT" Statement


I will take you through two steps in which an SELECT statement will get processed...

Optimizing a Select


1. A SELECT statement is non-procedural.
2. A database server needs to optimize a SELECT statement because it is non-procedural (we cannot know   the exact number of steps that the server would undergo to execute the query).
3. Query optimizer does this optimizing query.
4. Tables, views definitions, indexes and statistics are input to the query optimizer and execution plan is its      output.

A query execution plan is a definition of following:

1. Sequence in which the source tables are accessed.
  • Usually accessed in any way (top to bottom or bottom to top) and it does not matter.
2. The methods used to extract data from each table.
  • Table scan
  • Index scan
  • Index seek

SQL Server Query optimizer:

  1. SQL server query optimizer is cost-based.
  2. It selects a plan which has reasonable cost and returns results faster.
  3. Optimizer relies on statistics which helps in estimating the costs of the resources required to process a query.

Processing a SELECT statement


1. Parser scans the SELECT statement and breaks it into logical units such as keywords, expressions,    operators and identifiers.
2. A query tree or a sequence tree is built describing the logical steps needed to transform the source data  into result set format.
3. The optimizer analyzes different ways the source tables can be accessed.
4. Then the query tree is updated with the exact series of the steps which gives fast results while consuming  less resources.
5. The final optimized version of query tree is the execution plan.
6. The relational engine starts executing the execution plan upon getting the data from the storage engine.
7. The relational engine itself processes the data returned from the storage engine into the result set format and  sends to client.

Thanks for reading...!
Comments and issues are accepted with great respect.

Friday, 21 February 2014

Stored Procedure Vs User Defined Function


I think many of us are not aware of the exact differences between a user defined function and a procedure. So, i would like to share some of the basic differences between a function and a stored procedure from my understanding.

Stored Procedures:
1. Procedures can return more than one value.
2. Can have both input and output parameters.
3. Allow all types of sql statements irrespective of reading(SELECT statement) or writing( DML statements)     statements.
4. A procedure can call a function and a procedure can call another procedure.
5. Exception handling can be done in procedures.
6. Transaction management is allowed.
7. Procedures cannot be used in SELECT or HAVING or WHERE clauses.
8. Used to execute Business Logic.
9. Has a pre-compiled execution plan.
10. Can be written to do one or more tasks.
11. A procedure can return maximum of 1024 values.

User-defined Functions:
1. Functions can return one value which is mandatory.
2. Can only have input parameters.
3. Allow only SELECT  queries or reading statements to be written in them.
4. A function cannot call a procedure.
5. Exception handling cannot be done in functions.
6. Transaction management is not allowed.
7. Functions can be used in SELECT or HAVING or WHERE clauses.
8. Functions that return tables can be treated as another row-set. This can be used in join with other tables.
9. Inline functions can be thought of as views that take parameters and can be used in joining it with another row-set.
10. Used for Computations.
11. Not compiled before hand (pre-compiled).

GROUPBY VS PARTITIONBY