Chuyển đến nội dung chính
eLearner.app
Mô-đun 6 · Bài học 1 trong tổng số 421/57 trong khóa học~12 min
Bài học theo mô-đun (1/4)

Hàm chuỗi

PostgreSQL has dozens of functions for manipulating strings. In this lesson we look at the ones most common in real work: normalizing (LOWER/UPPER), measuring (LENGTH), composing (|| / CONCAT), extracting (SUBSTRING), cleaning up (TRIM), substituting (REPLACE), and pattern searching (LIKE / ILIKE).

The functions we will use

SQL
LOWER('Alice')                -- 'alice'
UPPER('alice')                -- 'ALICE'
LENGTH('alice')               -- 5
'a' || 'b'                    -- 'ab'  (concatenazione)
CONCAT('a', 'b', 'c')         -- 'abc' (versione "funzione")
SUBSTRING('hello' FROM 2 FOR 3) -- 'ell'
TRIM(' alice ')               -- 'alice'
REPLACE('foo bar', 'bar','x') -- 'foo x'

|| is the standard SQL operator for concatenating strings; CONCAT is more permissive (it ignores NULLs, while || propagates them: 'a' || NULLNULL).

LIKE and ILIKE: searching by pattern

LIKE searches for a pattern: % = any sequence, _ = a single character. It is case-sensitive. ILIKE is the PostgreSQL case-insensitive variant:

SQL
WHERE name LIKE  '%Cuffie%'   -- match esatto "Cuffie"
WHERE name ILIKE '%cuffie%'   -- match anche "CUFFIE", "Cuffie", "cuffie"
WHERE email LIKE  '%@example.com'
WHERE first_name LIKE 'A_____'  -- inizia per A, lungo 6 (A + 5 caratteri)

To search for a literal % or _ inside the pattern, use ESCAPE:

SQL
WHERE titolo LIKE '%50\%%' ESCAPE '\';   -- contiene "50%"

Combining functions

Functions compose like in any language:

SQL
-- Email "normalizzata" e iniziali in maiuscolo:
SELECT LOWER(email) AS email_norm,
       UPPER(SUBSTRING(first_name FROM 1 FOR 1)) || '.'
       || UPPER(SUBSTRING(last_name  FROM 1 FOR 1)) || '.' AS iniziali
FROM   customers
ORDER BY id;

Try it

tập thể dục#sql.m6.l1.e1
Nỗ lực: 0Đang tải…

For each customer, show the email in lowercase (column email) and the full name as 'first_name last_name' (column full_name). Order by id.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

LOWER for the first column, || to concatenate with a space in between.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#sql.m6.l1.e2
Nỗ lực: 0Đang tải…

Find all products that contain the word 'laptop' (in any case) in the name. Show only the name column. Order by name.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

ILIKE is case-insensitive. Use '%laptop%' to match 'laptop' in any position.

Giải pháp khả dụng sau 3 lần thử