Think before writing a SQL Query

  1. Understand Business Requirements: understand the requirement properly first from the Stakeholder/ Product Owner/ Team.
  2. Follow the 5 W’s: Who? What? Where? When? Why?
  3. Follow the most optimized way
  4. The sequence of keywords (SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY)
  5. Always use capital letters for keywords

Things to keep in mind

New Features

Condition Drop Statement

Whenever we create any temp table, we drop it after use, it's a best practice.

Example to drop a temp table.

SQL
IF OBJECT_ID(N'tempdb..#tmpTable) IS NOT NULL
BEGIN
DROP TABLE #tmpTable
END

But, now we have a new way to do it by using Conditional drop statement, which will be applicable for Table, Procedure, Function, etc.,

SQL
DROP TABLE IF EXISTS #tmpTable
DROP PROC IF EXISTS Proc_Name

CONCAT_WS

CONCAT_WS can concatenate strings that might have "blank" or Null values - for example,

SQL
SELECT CONCAT_WS(',','SQL', NULL, NULL, 'Server', 'New', 'Feature', 2017) AS 'Result';

It will simply ignore Null values.

OUTPUT

SQL,Server,New,Feature,2017

TRIM

Earlier we were using LTRIM() and RTRIM() to remove white spaces from both sides of string. Now in SQL Server 2017 we have a new keyword TRIM() which handle white space cleanup from both side.

APPROX_COUNT_DISTINCT

Until now we used Count(distinct column name) to get the count of record. Now in SQL Server 2019 we have a new function APPROX_COUNT_DISTINCT(). It uses less memory and CPU resources.