-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15-ReplacingNullValues.sql
More file actions
63 lines (55 loc) · 1.3 KB
/
15-ReplacingNullValues.sql
File metadata and controls
63 lines (55 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
create table tblOffice
(
EmployeeID Int NOT NULL identity(1,1) Primary key,
Name nvarchar(50) NOT NULL,
ManagerID int NULL,
)
--insert data into tblOffice tabel
insert into tblOffice(name, ManagerID) values ('Mike', 3),('Rob', 1), ('Todd', NULL), ('Ben',1), ('Sam', 1);
--show data
select * from tblOffice
/*
Replacing NULL Values
Three ways to replace NULL values - ISNULL() function, CASE statement & COALESCE() function
--ISNULL
Select E.Name as Employee, ISNULL(M.Name, 'No Manager') as Manager
From tblOffice E
left join tblOffice M
ON E.ManagerID = M.EmployeeID
*/
--ISNULL
Select E.Name as Employee, ISNULL(M.Name, 'No Manager') as Manager
From tblOffice E
left join tblOffice M
ON E.ManagerID = M.EmployeeID
/*
Mike Todd
Rob Mike
Todd No Manager
Ben Mike
Sam Mike
*/
--use COALESCE()
Select E.Name as Employee, COALESCE(M.Name, 'No Manager') as Manager
From tblOffice E
left join tblOffice M
ON E.ManagerID = M.EmployeeID
/*
Mike Todd
Rob Mike
Todd No Manager
Ben Mike
Sam Mike
*/
--case function
Select E.Name as Employee, CASE WHEN M.Name is NULL THEN 'No Manager' ELSE M.Name END as Manager
From tblOffice E
left join tblOffice M
ON E.ManagerID = M.EmployeeID
/*
Mike Todd
Rob Mike
Todd No Manager
Ben Mike
Sam Mike
*/