LIKE, IN และ BETWEEN
= only matches text exactly. To match a pattern, use LIKE with two wildcards:
%stands for any run of characters (including none)_stands for exactly one character
SELECT name FROM student WHERE name LIKE 'S%';
'S%' means "starts with S". '%a%' means "contains an a". '_o%' means "an o as the second letter".
Two more handy tests:
IN (…)matches any value in a list:WHERE form IN ('11A', '11C')BETWEEN low AND highmatches a range, including both ends:
SELECT name, score FROM student WHERE score BETWEEN 70 AND 90;
Both are shorter than writing several ORs.
Question. Show the name of every student whose name has a as its second letter.
Answer. _ stands for exactly one character, so _a means "any first letter, then a". The % lets the rest of the name be anything:
SELECT name FROM student WHERE name LIKE '_a%';
name
Jamal
Sara
'%a%' would be the wrong pattern here: it means "an a anywhere", and would also match a name such as Ana.
BETWEENwants the smaller value first.BETWEEN 90 AND 70matches nothing; writeBETWEEN 70 AND 90.%and_only work withLIKE.WHERE name = 'S%'looks for a name that is literallyS%.- Case. In SQLite,
LIKEignores the difference between capital and small letters A to Z, so's%'also finds Sara. Some other databases do not.
ตัวกรองรูปแบบและช่วง
LIKE / IN / BETWEEN ล้วนเป็น WHERE — เพื่อเก็บเฉพาะแถวที่ตรงตามเงื่อนไข
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
แสดง name ของนักเรียนทุกคนwhose ชื่อ มีตัวอักษร a ใช้ LIKE ร่วมกับ %
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
แสดง name และ score ของนักเรียนwhose คะแนนอยู่ ระหว่าง 70 ถึง 90 (รวมขอบเขต) ใช้ BETWEEN
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
แสดง name และ form ของทุกคนในชั้น 11B หรือ 11C ใช้ IN พร้อมรายการชั้นทั้งสอง
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
แสดง name ของทุกคนwhoseชื่อมี สามตัวอักษรพอดี แต่ละ _ แทนหนึ่งตัวอักษร
คลิก Run เพื่อดูผลลัพธ์ที่นี่