SQL ISNULL function

SQL ISNULL function

SQL ISNULL function

SQLShack

SQL Server training Español

SQL ISNULL function

May 10, 2019 by Rajendra Gupta This article explores the SQL ISNULL function to replace NULL values in expressions or table records with examples.

Introduction

We define the following parameters while designing a table in SQL Server Data types for a particular column Allow NULL or Not Null values in SQL Server 123456 CREATE TABLE table_name( column1 datatype [ NULL], column2 datatype [NOT NULL ], ...); If we do not provide any value for column allow NULL values, SQL Server assumes NULL as default value. 12345 CREATE TABLE Employee(EmployeeID INT IDENTITY(1, 1) NOT NULL, EmployeeName VARCHAR(50) NOT NULL, EmployeeSalary INT NULL); Let’s insert a few records in the Employee table. 12345678910 INSERT INTO Employee(EmployeeName, EmployeeSalary)VALUES('Rajendra', 55645);INSERT INTO Employee(EmployeeName)VALUES('Rajendra'); View the records in the table, and we can see a NULL value against EmployeeID 2 because we did not insert any value for this column. We might have a requirement to replace NULL values with a particular value while viewing the records. We do not want to update values in the table. We can do this using SQL ISNULL Function. Let’s explore this in the upcoming section.

SQL Server ISNULL Function overview

We can replace NULL values with a specific value using the SQL Server ISNULL Function. The syntax for the SQL ISNULL function is as follow. SQL Server ISNULL (expression, replacement) Expression: In this parameter, we specify the expression in which we need to check NULL values Replacement: We want to replace the NULL with a specific value. We need to specify replacement value here The SQL Server ISNULL function returns the replacement value if the first parameter expression evaluates to NULL. SQL Server converts the data type of replacement to data type of expression. Let’s explore SQL ISNULL with examples.

Example 1 SQL Server ISNULL function in an argument

In this example, SQL ISNULL function returns the second argument value because the first argument is NULL: 1 SELECT ISNULL(NULL, 100) result; In the following examples, we can see the following. If the first argument is NULL, it returns the value of the second argument. If the first argument is NOT NULL, it returns the first argument value as output. 12 SELECT ISNULL(NULL, 'SQLServer') result; SELECT ISNULL('SQLShack', 'SQLServer') result;

Example 2 SQL Server ISNULL to replace a value in existing column values

At the beginning of this article, we created the Employee table and inserted NULL values in it. We can use SQL ISNULL to replace existing NULL values with a specific value. For example, we want to return Employee salary 10,000 if it is NULL in the Employee table. In the following query, we used SQL ISNULL function to replace the value. 123 SELECT Employeeid, ISNULL(EmployeeSalary, 10000) EmployeeSalary FROM Employee; Let’s update the NULL value in the Employee table using the following update statement. 1 Update Employee set EmployeeSalary =65656 where EmployeeID =2 We do not have any NULL value in the table now; therefore if we run the query with SQL Server ISNULL, it returns actual values of the rows.

Example 3 SQL Server ISNULL with aggregate functions

We can use SQL ISNULL with aggregate functions such as SUM, AVG as well. Suppose we want to perform sum of EmployeeSalary present in Employee table. If EmployeeSalary is NULL, it should be replaced with 10000 before adding the salaries. Before we move, update the EmployeeSalary as NULL for EmployeeID 2 using the following query. 1 Update Employee set EmployeeSalary =NULL where EmployeeID =2 In the following query, we replaced the NULL value with value 10000 first and then performed SUM on it. You can visualize it with the following screenshot. 12 SELECT SUM(ISNULL(EmployeeSalary, 10000))FROM Employee; Similarly, we can use SQL ISNULL function to replace NULL values and calculate the average value with AVG() function. 12 SELECT AVG(ISNULL(EmployeeSalary, 10000))FROM Employee;

Example 4 Difference between SQL Server ISNULL with IS NULL

You might confuse between SQL Server ISNULL and IS NULL. We use IS NULL to identify NULL values in a table. For example, if we want to identify records in the employee table with NULL values in the Salary column, we can use IS NULL in where clause. 123 SELECT *FROM EmployeeWHERE EmployeeSalary IS NULL; In the following screenshot, we cannot use SQL Server ISNULL to find NULL values. We use it to replace NULL values with a specific value. In the second part, we can see the employee having a NULL salary.

Example 5 SQL Server ISNULL to replace the NULL value with a custom message

Consider the example in which we have NULL values in DeliveryAddressLine2 column. We want to print a message in [DeliveryAddressLine2] if the actual values from DeliveryAddressLine2 have NULL values. 12345678 Select[CustomerName], [AccountOpenedDate], [DeliveryAddressLine1], [DeliveryAddressLine2], ISNULL([DeliveryAddressLine2], 'Address Same as DeliveryAddressLine1') AS DeliveryAddressLine2, [DeliveryPostalCode] from customers You can see the message in DeliveryAddressLine2 column.

Implicit conversion of data type in SQL Server ISNULL

If we have multiple data types in an expression, SQL Server converts the lower precedence data types into a higher precedence data type. SQL Server ISNULL also performs similarly. If SQL ISNULL is not able to escalate the data type, it returns an error message. As per MSDN, SQL Server uses the following precedence order for data types: user-defined data types (highest) sql_variantXML datetimeoffset datetime2 DateTime smalldatetime date time float real decimal money smallmoney bigint int smallint tinyint bit ntext text image timestamp uniqueidentifier nvarchar (including nvarchar(max) ) nchar varchar (including varchar(max) ) char varbinary (including varbinary(max) ) binary (lowest) In the following image, we can all possible implicit and explicit allowed data type conversions. ( Image Reference: Microsoft Docs) Let’s understand data type precedence with SQL NULL using the following example. In the above table, we can see that the precedence of INT is higher than the timestamp data type. Execute the following query. In this query, we defined a variable @ID of integer type. We try to replace the NULL value in this parameter with Current timestamp. 1 DECLARE @ID int We get the following error message. It cannot convert data type from datetime to integer. We can use SQL Convert functions to convert appropriate data type. Msg 257, Level 16, State 3, Line 2
Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query. Now, let’s replace data type of parameter @ID from integer to datatime2. In the data precedence table, the precedence of datatime2 data type is higher than the timestamp data type. 12 DECLARE @ID DateTime2SELECT ISNULL(@ID, CURRENT_TIMESTAMP);

Conclusion

In this article, we explored the SQL ISNULL function and its usage in replacing NULL values with a specified value or string. Feel free to ask question or provide comments in the feedback below Author Recent Posts Rajendra GuptaHi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book "DP-300 Administering Relational Database on Microsoft Azure". I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at [email protected]

View all posts by Rajendra Gupta Latest posts by Rajendra Gupta (see all) Copy data from AWS RDS SQL Server to Azure SQL Database - October 21, 2022 Rename on-premises SQL Server database and Azure SQL database - October 18, 2022 SQL Commands to check current Date and Time (Timestamp) in SQL Server - October 7, 2022

Related posts

Overview of the SQL REPLACE function Using the SQL Coalesce function in SQL Server Querying data using the SQL Coalesce function SQL CAST and SQL CONVERT function overview SQL date format Overview; DateDiff SQL function, DateAdd SQL function and more 163,304 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ▼Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!