Home [SQL筆記] 條件查詢一
Post
Cancel

[SQL筆記] 條件查詢一

R

  • between and 在兩者之間
  • where in 是否在其中(效能差)

    EXISTS: 直接代入驗證, true/false IN: 挑出大量資料後, 再一一比對true/false

關於SQL語法IN條件式的效能

  • desc 降序
  • asc 升序(默認值,可以不寫)
  • order by len(欄位名) desc 根據(欄位名)長度排序
  • top 5前5個
  • top 10 percent前10%(前百分之10)

  • is null空值。欄位 is null
  • is not null不是空值。欄位 is not null
  • ''空字串。欄位=''

  • null使用者從未輸入過任何值。
  • ''空字串。使用者輸入了,但未指定任何值。

條件查詢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
--查詢性別為女的員工資料
select * from Employee where EmployeeSex = '女'
--查詢薪水大於等於50000的員工資料
select * from Employee where EmployeeSalary >= 50000
--查詢性別為女, 薪水大於等於50000的員工資料(多條件)
select * from Employee where EmployeeSex = '女' and EmployeeSalary >= 50000
--查詢出 出生年月在1980-1-1之後,且月薪大於等於50000的女員工
select * from Employee where EmployeeBirth >= '1980-1-1' and EmployeeSalary >= 50000
--查詢月薪大於等於40000, 或是月薪大於等於50000的女員工
select * from Employee where EmployeeSalary >= 40000 
or (EmployeeSalary >= 50000 and EmployeeSex = '女' )
--查詢月薪在55000-60000之間的員工資料
select * from Employee where EmployeeSalary between 50000 and 60000
--查詢地址在台北或是高雄的員工資料
select * from Employee where EmployeeAddress ='台北' or EmployeeAddress ='上海' 
select * from Employee where EmployeeAddress in('台北','上海')

排序

  • desc 降序
  • asc 升序(默認值,可以不寫)
  • order by len(欄位名) desc 根據(欄位名)長度排序(降序)
  • top 5 前5個
  • top 10 percent 前10%(前百分之10)
1
2
3
4
5
6
7
8
--查詢所有員工資料,根據工資排序,降序
select * from Employee order by EmployeeSalary desc
--查詢所有員工資料,根據名字長度排序(降序)
select * from Employee order by len(EmployeeName) desc
--查詢出工資最高的5個員工資料
select top 5 * from Employee order by EmployeeSalary desc
--查詢出工資最高的10%的員工資料
select top 10 percent * from Employee order by EmployeeSalary desc

is null & is not null

1
2
3
4
5
6
7
8
--null空值
--查詢沒有填寫地址的員工資料
select * from Employee where EmployeeAddress is null
select EmployeeAddress,* from Employee 
where EmployeeAddress is null or EmployeeAddress=''

--查詢有填寫地址的員工資料
select * from Employee where EmployeeAddress is not null

null & 空字串''

null & 空字串''是有區別的:

  • null代表使用者從未輸入過任何資料
  • 空字串''代表使用者輸入了,但未指定任何值

查詢沒有填資料的欄位

  • is null查詢為null的資料
  • 欄位=''查詢為空字串的資料
1
2
3
4
5
6
7
8
9
10
11
--新增一個地址為null的員工資料
insert into Employee(DepartmentId,RankId,EmployeeName,EmployeeSex,EmployeeBirth,EmployeeSalary,EmployeePhone,EmployeeAddTime)
values(8,1,'李四','男','1999-9-9',50000,'098899999',getdate())
--新增一個地址為空字串的員工資料
insert into Employee(DepartmentId,RankId,EmployeeName,EmployeeSex,EmployeeBirth,EmployeeSalary,EmployeePhone,EmployeeAddress,EmployeeAddTime)
values(8,1,'王五','男','1999-9-9',50000,'098899900','',getdate())

--查詢地址為null的員工資料
select EmployeeAddress,* from Employee where EmployeeAddress is null
--查詢地址為空字串的員工資料
select EmployeeAddress,* from Employee where EmployeeAddress=''
This post is licensed under CC BY 4.0 by the author.