Labels

Saturday, April 11, 2026

ISNULL vs COALESCE


FeatureISNULLCOALESCE
OriginT-SQL Specific (Microsoft)ANSI SQL Standard (Universal)
ParametersAccepts only 2 arguments.Accepts 2 or more arguments.
Data TypeUses the type of the first argument.Uses the type with the highest precedence.
PerformanceSlightly faster for simple 1-to-1 checks.Can be slightly slower in complex subqueries.
EvaluationEvaluates the first argument once.May evaluate the expression multiple times.
Key Differences Explained

1. Number of Arguments
  • ISNULL: Limited to checking one value and providing one replacement.
                SELECT ISNULL(Price, 0) FROM Products;

  • COALESCE: Can check multiple columns/values in order and returns the first non-null one.
                SELECT COALESCE(Mobile, HomePhone, OfficePhone, 'N/A') FROM Contacts;

2. Data Type Handling

This is often where developers run into unexpected results or errors.
  • ISNULL is rigid. It looks at the data type of the first expression and tries to convert the replacement to match it. If the replacement is longer than the first argument, it may even truncate the data.
  • COALESCE follows "Data Type Precedence." It looks at all arguments and converts everything to the type that ranks highest.

3. Performance in SQL Server

In most standard queries, the performance difference is negligible. However:
  • ISNULL is built directly into the SQL Server engine as a function.
  • COALESCE is actually translated by the engine into a CASE statement.
  • Best Practice: Use ISNULL for high-frequency, simple null-to-zero conversions where performance is critical. Use COALESCE for multi-column logic or when writing code that needs to be portable to other databases like PostgreSQL or MySQL.

Note :
Use ISNULL when you are sure you only have two values and want to force a specific data type. Use COALESCE when you need flexibility, multiple fallbacks, or are following ANSI standards


Sunday, May 3, 2020

Sorting a Crystal Reports Cross-Tab: A Step-by-Step Guide

Learn how to precisely control the order of your Cross-Tab groups with the "In Specified Order" sorting option.

Introduction 

This feature allows you to sort your Cross-Tab rows and columns with precision. Specifically, the 'In Specified Order' option is invaluable for organizing data that doesn’t follow standard alphabetical or numerical logic. For example, if you need to arrange a Cross-Tab by month name rather than alphabetically, here is how you can set that up.

1Step 1: Open the Cross-Tab Expert Start by right-clicking your Cross-Tab. When the menu             appears, click "Cross-Tab Expert..." to begin customizing your layout.
Select Cross-Tab Exprert


2. Below the column and row sections, you will find the "Group Options" button. Select the              column or row field that you need to sort in a specific order, and then click this button.
Group Option


3.  Select Common tab and Select In Specified Order from drop down.
In specified order.


4.  Next, select the "Specified Order" tab and click the "New" button to add an item to your custom sort order.

You will then enter the Group Name and select a condition, followed by its corresponding value. For our scenario, you would enter January as the Group Name, select the "is equal to" condition, and enter January as the value.

You will need to repeat this process for all the months of the year to create your desired sort order.
User define order

Wednesday, April 29, 2020

The Ultimate Guide to PIR Sensors

PIR Motion Sensor ( DYP-ME001)


PIR Sensor

An Introduction to PIR Motion Sensor

Passive Infrared (PIR) sensors are primarily used to detect motion, making them especially popular for sensing human movement. Compact, energy-efficient, and cost-effective, these sensors are staples in security and automation projects.While most commonly referred to as PIR sensors, they are also known as pyroelectric or IR motion sensors. At their core, they work by detecting changes in infrared radiation levels within their field of view.Although there are many types of PIR sensor modules available—such as the HC-SR501 and the DYP-ME001—this guide will focus specifically on the DYP-ME001 and how to interface it with an Arduino. (Note: These sensors can also function independently without a microcontroller.)

DYP-ME001


Specification Of  DYP-ME001

Input Voltage - DC 4.5 - 20V
Static Current - 500uA
Block Time - 2.5s
Delay Time - 5s
Sentry Angle < 110
Sentry Range -3m to 7m

The Science Behind Detecting Heat and Motion

When a heat source, such as a human or animal, passes through the sensor's field of view, it first crosses one of the sensor's two infrared-sensitive halves. This creates a positive differential change in infrared radiation between the two sides.

As the warm body continues moving and crosses the second half, the reverse occurs, generating a negative differential change. The sensor's onboard circuitry detects these rapid, alternating voltage spikes—first positive, then negative—and translates them into a motion detection signal.


PIR Setting

Trigger Mode Jumper

Unlike some PIR sensors, the DYP-ME001 module lacks user-configurable jumper pins for selecting trigger modes. Instead, it is hardwired to operate in the 'H' (Repeatable Trigger) mode by default. In contrast, modules like the widely used HC-SR501 feature adjustable jumpers, allowing you to easily toggle between repeatable ('H') and non-repeatable ('L') trigger configurations

L position

When a warm body moves in front of the sensor, it will trigger an output signal.

The behavior of this signal depends on the mode the sensor is configured for:

Non-Retriggering (Single Trigger) Mode: In this mode, the sensor triggers once when motion is first detected. It will then remain 'ON' for a pre-set duration and will not re-trigger, even if motion is still present. This means that after the initial trigger, the output will turn 'OFF' after its set time has expired and will not turn on again until a new motion event is detected.

Retriggering Mode (Commonly set as 'H' on HC-SR501): This is the more common mode. As long as motion is continuously detected, the sensor's output will stay 'ON'. The timer will reset every time motion is detected, ensuring the signal remains active. The output only turns 'OFF' after motion has ceased for the duration of the pre-set time.

H position

Sensor will turn on entire time that something is moving. So we call this as retriggering or repeatable trigger mode.

Sensitivity and Time Adjustment

Sensitivity

According to PIR motion sensor (DYP-ME001) specification adjustable range is from 3m to 7m. Here is way adjust.

Clockwise or Right side -- decrease sensitivity, so it fully right and range will be approximately 3m.

Counter Clockwise or Left side --increase sensitivity , so it fully right and range will be   approximately 7m.

Time Adjustment

This adjustment  determined how long of  PIR sensor will remain high after motion detected.

Clockwise or Right side -- Increase  delay,So it fully right and delay will be approximately 5 second.

Counter Clockwise or Left side -- decrease delay , So it fully left and delay will be approximately 3 second


Code Sample 

int motion_in =2;
int led_out=3; 

void setup() {
pinMode(motion_in ,INPUT);
pinMode(led_out,OUTPUT);    }

void loop() {
  // put your main code here, to run repeatedly:
 
int pir_read = digitalRead(motion_in);
if(pir_read==1)

  digitalWrite(led_out ,HIGH);
  delay(1000);
}
else
{
    digitalWrite(led_out,LOW);
    delay(300);
}}




Wednesday, July 26, 2017

Livit Fitness Band

  



I recently picked up the Dialog LIVIT Fitness Band, and after putting it through its paces for a couple of weeks, I’m ready to share my thoughts.

If you’re looking for a wearable that won't break the bank, this might be on your radar. I managed to snag mine at a discounted price of just 1,745 LKR, which firmly places it in the ultra-budget category.

The Verdict: Value for Money?
At this price point, expectations should be managed, but I actually think it’s a solid value for what you pay. It handles the basics well enough for someone just starting their fitness journey or looking for a simple notification tracker.

The Trade-off
The biggest "catch" to be aware of is the hardware. The Dialog LIVIT does not include a heartbeat sensor. While many modern wearables treat heart rate monitoring as a standard feature, its absence here is clearly how they’ve managed to keep the cost so low.

Final Thoughts
If you need a low-cost entry into the world of fitness trackers and don't mind missing out on heart rate data, the LIVIT is a decent "bang for your buck" option. However, if health metrics like BPM are a priority for your training, you might want to save up for a slightly higher-tier model.

What do you think? Is a heart rate sensor a dealbreaker for you in 2017, or is the price too good to pass up? Let me know in the comments!

 Features

  1. All day activity tracking (steps,distance,calories burned,active minits,hourly activity).
  2. Notification and calender alerts - (Call,text,facebook,Twitter,WhatApps,skype,Gmail).
  3. Reminder to move (encorage you to take steps every hour).
  4. Auto Sleep Traking (how long well you sleep).
  5. Sync Wirless (Bluetooth 4.0 with Android and Apple devices).
  6. USB Charge.
  7. Easy Touch and Gesture Control (High sensitivity  touch screen).

Support

 IOS : 4S/ 5/ 5S/ 5C/ IPad 3 IOS 8.0 above.
 Android : Android 4.4 above

Friday, July 21, 2017

SQL Server Database Mail Configuration

Setting up automated notifications in SQL Server can be a lifesaver for DBAs and developers alike. Whether it’s alerting you to a failed job or sending out scheduled reports, Database Mail is the go-to feature.In this guide, I’ll walk you through the configuration process step-by-step. Let’s dive in.

Step 1: Access the Database Mail Configuration Wizard.

  • Connect to SQL Server: Launch SQL Server Management Studio (SSMS) and connect to the appropriate server instance.
  • Navigate to Management: In the Object Explorer, expand the Management node.
  • Launch the Wizard: Locate Database Mail, right-click it, and select Configure Database Mail.



Step 02: Navigating the Setup Wizard.

Once you've launched the configuration tool, the Welcome screen will appear. This window provides a brief overview of what the wizard can do, such as managing accounts and profiles.

Simply click the Next button to move forward and start defining your configuration.

 

Step 03: Choosing the Configuration Type.

On the Select Configuration Task screen, you'll see a few different options. Since we are starting from scratch, select the first option: “Set up Database Mail by performing the following tasks.” Once you’ve made that selection, click Next.



Step 04: Enabling the Feature and Creating Your Profile.

If this is a fresh SQL Server installation, the wizard might throw a quick pop-up letting you know that the Database Mail feature is currently disabled. Don't sweat it—this is just a standard security precaution. Simply click Yes to enable it and keep the momentum going.

Once enabled, you’ll be greeted by the New Profile window. Here’s what you need to do:
  • Profile Name: Give your profile a clear, recognizable name (e.g., Admin_Alerts or System_Notifications).
  • Description: While optional, it’s a total pro-move to add a quick note about what this profile is for.
  • Add SMTP Account: Now for the important part—click the Add... button on the right side to start linking your actual email server settings to this profile.



Step 05: Configuring Your SMTP Settings.

This is the "meat" of the configuration where we link SQL Server to your actual email provider. In the New Database Mail Account window, you’ll need to fill in the following details:

1. Account Identity
  • Account Name: Give this specific account a name.
  • Description: Briefly describe what this account does (e.g., "Main Gmail SMTP Account").

2. Outgoing Mail Server (SMTP)
Here’s where you plug in the technical specs:
  • Email Address: The email address you’ll be sending from.
  • Display Name: What you want people to see in their inbox (e.g., SQL-Alert-Service).
  • Reply Email: Optional, but handy if you want replies sent to a specific person.
  • Server Name: The SMTP server address (e.g., smtp.gmail.com or mail.yourdomain.com).
  • Port Number: This depends on your provider, but it’s usually 25, 465, or 587.
3. SMTP Authentication
Most modern mail servers require security, so under the SMTP Authentication section:
  • Select the Basic Authentication radio button.
  • Username: Enter your full email address.
  • Password: Enter your email password (or an "App Password" if you’re using MFA).

Click OK (or Add) to save the configuration.



Step 06

 Then window will appear. it shows your created profile and click Next.

Step 07

 Then another window will , the Configure System Parameters description is shown.


Step 08

Then Click Next. It will show confirmation about your profile , so click Finish.



Step 09

Now SQL server was configured email service and click close .

Step 10
Run following SQL Query

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO

How to test SQL Sever mail

Then again right click on Database Mail and select Send Test Email. Then select Database mail profile and enter receiver mail address ,  mail subject.



How to view Database Mail Log

Right click on the Database mail and select View Database Mail Log
 
  

Wednesday, June 14, 2017

T-SQL Trick: How to Find Monday (or Any Day) of the Current Week

Ever needed to filter a report so it only shows data starting from the beginning of the current week? In SQL Server, calculating the date for "this past Monday" is a classic challenge that every dev faces eventually.

While there are many ways to do it, the most efficient method uses a clever combination of DATEDIFF and DATEADD.

The Logic: How It Works

The secret sauce is calculating the number of weeks that have passed since "Day 0" (which is 1900-01-01, a Monday) and then adding those weeks back to that same starting point.

Here is the cleanest way to write it:

-- Using the 'WK' shorthand

SELECT DATEADD(WK, DATEDIFF(WK, 0, GETDATE()), 0) AS MondayOfCurrentWeek;

-- Or using the full 'WEEK' keyword for readability

SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) AS MondayOfCurrentWeek;

Both queries will return the exact date of Monday for the current week (e.g., 2026-04-13).


Getting Other Days of the Week

The beauty of this snippet is its flexibility. If you need to find Tuesday, Wednesday, or any other day, you don't need to rewrite the logic—you just need to shift the "anchor" value (the 0 in the formula).

By incrementing the integer, you move the target day forward:

-- Tuesday

SELECT DATEADD(WK, DATEDIFF(WK, 0, GETDATE()), 1) AS Tuesday;

-- Wednesday

SELECT DATEADD(WK, DATEDIFF(WK, 0, GETDATE()), 2) AS Wednesday;

-- Thursday

SELECT DATEADD(WK, DATEDIFF(WK, 0, GETDATE()), 3) AS Thursday;


Why use this instead of DATEPART?

The main advantage here is that this method is deterministic and ignores your server's DATEFIRST settings. Whether your server thinks the week starts on Sunday or Monday, this math always anchors back to that original Monday in 1900, keeping your reports consistent across different environments.

Thursday, May 4, 2017

Measuring Distance with Arduino: A Guide to the HC-SR04 Ultrasonic Sensor



If you’ve ever wanted to give your Arduino projects "vision," the HC-SR04 Ultrasonic Sensor is the perfect place to start. Whether you're building an obstacle-avoiding robot or a digital tape measure, this little module is a staple in the maker community.

Today, I’m going to break down how this sensor works and show you how to get it up and running with your Arduino.

What is the HC-SR04?

The HC-SR04 is an affordable sensor that uses sonar to determine the distance to an object—much like a bat or a dolphin. It has a solid detection range of 2 cm to 400 cm (about 13 feet), which is more than enough for most DIY projects.

How it Works: The "Echo" Principle

The module consists of two main parts: an ultrasonic transmitter and a receiver. Here is the simple physics behind it:
  • The Trigger: The transmitter sends out a high-frequency sound wave (40 kHz).
  • The Bounce: If there is an object in front, the sound wave hits it and bounces back.
  • The Echo: The receiver detects the returning wave and records the time it took for the round trip.
  • By knowing the speed of sound, we can calculate the distance with a bit of simple math!
By knowing the speed of sound, we can calculate the distance with a bit of simple math!

Pros and Cons

Before we start coding, it’s important to know the sensor's limitations:

  1. The Good: Unlike infrared sensors, the HC-SR04 isn't bothered by sunlight or dark-colored objects.
  2. The Bad: It can struggle with soft materials like cloth or wool, which tend to absorb sound waves rather than reflecting them.
  3. The Variable: Keep in mind that temperature and humidity can slightly change the speed of sound, which might affect your accuracy if you're looking for precision.

Hooking it up to Arduino

To get started, you'll need to connect the four pins: VCC (5V), Trig (Trigger), Echo, and GND.


HC-SR04 Ultrasonic sensor Technical Specification

HC-SR04

power supply                  :- 5DC
Quiescent Current           :- 2mA
Working Current               :-15mA
Effect Angle                    :<15 degrees
Distance                           :- 2cm to 400cm
Resolution                        :-0.3cm
Trigger input pulse width :-10us
Ultrasonic Frequency       :-40KHz

Pins


VCC  :- arduino 5v pin
TRIG  :- arduino Digital pin
ECHO :- arduino Digital pin
GND  :- arduino GND pin

The TRIG pin is used to trigger the transmission of the ultrasonic sound pulse, while the ECHO pin is used to listen for the returning signal.

Example

int triggerPin= 8;
int echoPin= 7;
long pulsDuration =0;
long distanceCM =0;
long distanceINC =0;
void setup() {
  // put your setup code here, to run once:
  pinMode(triggerPin,OUTPUT);
  pinMode(echoPin,INPUT);

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
   digitalWrite(triggerPin,LOW);
   delayMicroseconds(5);
   digitalWrite(triggerPin,HIGH);
   delayMicroseconds(10);
   digitalWrite(triggerPin,LOW);

  pulsDuration =pulseIn(echoPin,HIGH);

  distanceCM = (pulsDuration/2) / 29.1;
  distanceINC = (pulsDuration/2) / 74; 

   Serial.println("CM");
  Serial.println(distanceCM);

   Serial.println("INCH");
  Serial.println(distanceINC);

  delay(1000);

   Serial.println("**********************************************");
}