T-SQL

COUNT() a eliminace NULL hodnot

Agregační funkce v SQL serveru ignorují hodnoty NULL. V praxi to znamená, že pokud agregujeme data ve sloupcích a některé řádky obsahují NULL hodnoty, tyto hodnoty se do naší agregace nezapočítají. Pro funkce typu SUM() je to očekávané chování, ale již ne tak pro AVG() nebo COUNT(). Funkce COUNT() se…

Read more
T-SQL

Window funkce v T-SQL

Základní window funkce v SQL Serveru známe všichni: ROW_NUMBER(),  RANK(), DENSE_RANK() a NTILE(). K nim se v dalších verzích SQL Serveru přidaly ještě funkce LEAD() a LAG(), na ty se ale podíváme někdy příště. Dnešní článek se nebude věnovat detailům jednotlivých funkcí, ale měl se stát spíše rozcestníkem, do něhož…
T-SQL

Vygenerování náhodného čísla pomocí NEWID()

Generování náhodných čísel v SQL Serveru může být čas od času pěkný oříšek, zejména pokud začínající vývojáři sáhnout po funkci RAND(). První, na co narazí, je, že tato funkce generuje stále stejné hodnoty, pokud ji chceme použít v dotazu s více řádky, jak je hezky vidět v tomto příkladu: SELECT…
T-SQL

CTE with multiple anchors

Common Table Expression (CTE) offers a lot of options on how to play with it. One of them is using recursion with an anchor which is in the standard scenario one row. But we can have a more complex anchor: instead of one row, it can be i.e. union on…

Read more
T-SQL

Rounding DATETIME values to midnight

DATETIME data type precision for milliseconds is rounded to increments of .000, .003, or .007 which leads to some unexpected behavior from time to time. I.e. if we will try to extract at which day event logged with milliseconds occurred. The example below demonstrates it pretty: Event occurring at 20101205…
T-SQL

Examples of TOP syntax

This article is just a short summary of TOP clause variants we can use. Especially the last one with a subquery isn’t so common and can be something new for you. Consider official documentation for more details on TOP usage and if you have any other interesting example don’t hesitate…
T-SQL

Composable DML

Composable DML is an extension SQL Server 2008 extension of the OUTPUT clause which one was originally published in SQL Server 2005. OUTPUT is generally returning all rows from the DML where it’s used without an option to filter the results set. Composable DML extends this concept for INSERT…SELECT scenarios…

Read more