الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 6 · الدرس 1 من 421/57 في الدورة~12 min
دروس الوحدة (1/4)

وظائف السلسلة

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

تمرين#sql.m6.l1.e1
المحاولات: 0جارٍ التحميل…

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.

جارٍ تحميل المحرر…
إظهار التلميح

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

الحل متاح بعد 3 من المحاولات

Review exercise

تمرين#sql.m6.l1.e2
المحاولات: 0جارٍ التحميل…

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

جارٍ تحميل المحرر…
إظهار التلميح

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

الحل متاح بعد 3 من المحاولات