Modulo 2 - Query di Base

Modulo 2 - Query di Base Modulo 2 - Query di Base
Modulo 2 - Query di Base

Modulo 2: Query di Base

Benvenuto al Modulo 2! Qui entriamo nel vivo di SQL, imparando a estrarre dati da un database con query semplici ma potenti. Presupponiamo che tu abbia già impostato un RDBMS dal Modulo 1 (es. MySQL o SQLite) e un database di test con una tabella semplice. Per gli esempi, userò un database ipotetico di un "negozio" con una tabella prodotti che ha colonne come id, nome, prezzo, categoria e quantita. Se non ce l'hai, crea una tabella di esempio con questi comandi:

CREATE TABLE prodotti (
    id INT PRIMARY KEY,
    nome VARCHAR(50),
    prezzo DECIMAL(5,2),
    categoria VARCHAR(20),
    quantita INT
);

INSERT INTO prodotti VALUES 
(1, 'Laptop', 999.99, 'Elettronica', 50),
(2, 'Smartphone', 499.99, 'Elettronica', 100),
(3, 'Libro SQL', 29.99, 'Libri', 200),
(4, 'Tazza', 9.99, 'Casa', 150),
(5, 'Monitor', 199.99, 'Elettronica', 30);
CREATE TABLE prodotti (
    id INT PRIMARY KEY,
    nome VARCHAR(50),
    prezzo DECIMAL(5,2),
    categoria VARCHAR(20),
    quantita INT
);

INSERT INTO prodotti VALUES 
(1, 'Laptop', 999.99, 'Elettronica', 50),
(2, 'Smartphone', 499.99, 'Elettronica', 100),
(3, 'Libro SQL', 29.99, 'Libri', 200),
(4, 'Tazza', 9.99, 'Casa', 150),
(5, 'Monitor', 199.99, 'Elettronica', 30);

Ora, approfondiamo i punti del modulo con spiegazioni, sintassi, esempi e consigli. Userò codice SQL standard; testa tutto nel tuo ambiente!

1. Struttura di una Query SQL: SELECT, FROM, WHERE

  • Panoramica: Una query base in SQL è come una richiesta: "Seleziona colonne da una tabella, con optional filtri". La sintassi minima è SELECT colonna FROM tabella;, ma spesso aggiungi WHERE per filtrare.

  • SELECT: Specifica cosa vuoi (colonne o * per tutte). Es. SELECT nome, prezzo FROM prodotti; restituisce solo nomi e prezzi.

  • FROM: Indica la tabella sorgente.

  • WHERE: Filtra righe basate su condizioni (es. prezzo > 100).

  • Esempio completo:

    SELECT * 
    FROM prodotti 
    WHERE categoria = 'Elettronica';
    SELECT * 
    FROM prodotti 
    WHERE categoria = 'Elettronica';

    Risultato atteso:

    id nome prezzo categoria quantita
    1 Laptop 999.99 Elettronica 50
    2 Smartphone 499.99 Elettronica 100
    5 Monitor 199.99 Elettronica 30
  • Consigli: Usa * solo per test; specifica colonne per efficienza. Le query sono case-insensitive (es. select = SELECT), ma i nomi di tabelle/colonne dipendono dal RDBMS (MySQL è case-sensitive su Linux).

2. Filtrare Dati con Condizioni (AND, OR, LIKE, IN)

  • Operatori base: =, !=, >, <, >=, <= per confronti. IS NULL o IS NOT NULL per valori nulli.

  • AND/OR: Combina condizioni. AND richiede tutte vere; OR almeno una.

    • Esempio AND: WHERE prezzo > 100 AND categoria = 'Elettronica'; (prodotti elettronici costosi).
    • Esempio OR: WHERE categoria = 'Elettronica' OR categoria = 'Libri';.
  • LIKE: Per pattern matching con wildcard. % per qualsiasi stringa, _ per un singolo carattere.

    • Esempio: WHERE nome LIKE 'L%'; (nomi che iniziano con L, es. Laptop, Libro).
  • IN: Controlla se un valore è in una lista.

    • Esempio: WHERE categoria IN ('Elettronica', 'Casa'); (prodotti in queste categorie).
  • Esempio combinato:

    SELECT nome, prezzo 
    FROM prodotti 
    WHERE (prezzo BETWEEN 10 AND 500) AND nome LIKE '%phone%';
    SELECT nome, prezzo 
    FROM prodotti 
    WHERE (prezzo BETWEEN 10 AND 500) AND nome LIKE '%phone%';

    (Usa BETWEEN per range; qui trova Smartphone).

  • Consigli: Usa parentesi per raggruppare condizioni complesse. Evita LIKE su grandi dataset (lento senza indici).

3. Ordinare Risultati (ORDER BY) e Limitare Output (LIMIT/OFFSET)

  • ORDER BY: Ordina i risultati. Aggiungi ASC (ascendente, default) o DESC (discendente). Puoi ordinare per più colonne.

    • Esempio: SELECT * FROM prodotti ORDER BY prezzo DESC; (dal più caro al più economico).
    • Multi-colonna: ORDER BY categoria ASC, prezzo DESC; (prima per categoria, poi prezzo decrescente).
  • LIMIT/OFFSET: Limita il numero di righe. LIMIT n restituisce i primi n; OFFSET m salta i primi m.

    • Esempio: SELECT * FROM prodotti ORDER BY prezzo ASC LIMIT 2; (i 2 più economici).
    • Paginazione: LIMIT 3 OFFSET 3; (righe 4-6).
  • Esempio completo:

    SELECT nome, prezzo 
    FROM prodotti 
    WHERE quantita > 50 
    ORDER BY prezzo ASC 
    LIMIT 1;
    SELECT nome, prezzo 
    FROM prodotti 
    WHERE quantita > 50 
    ORDER BY prezzo ASC 
    LIMIT 1;

    (Il prodotto più economico con stock >50, es. Tazza).

  • Consigli: ORDER BY è utile per report; LIMIT per test su grandi tabelle. Nota: OFFSET/LIMIT sono standard, ma alcuni RDBMS usano alternative (es. TOP in SQL Server).

4. Alias e Espressioni

  • Alias: Rinomina colonne o tabelle con AS per chiarezza.

    • Esempio: SELECT nome AS prodotto, prezzo * 1.22 AS prezzo_iva FROM prodotti; (calcola IVA e rinomina).
  • Espressioni: Calcoli nelle query, come aritmetica (+, -, *, /) o funzioni (es. ROUND(prezzo, 0)).

    • Esempio: SELECT nome, (quantita * prezzo) AS valore_totale FROM prodotti;.
  • Consigli: Alias non cambia il database, solo l'output. Utile per query leggibili.

Obiettivi del Modulo

  • Estrarre dati da tabelle singole con filtri, ordinamenti e limiti.
  • Scrivere query efficienti e leggibili.
  • Capire come SQL processa le query (prima FROM, poi WHERE, SELECT, ORDER BY).

Esercizi Suggeriti

  • Esercizio 1: Crea la tabella prodotti e inserisci i dati. Poi, scrivi una query per tutti i prodotti con prezzo <50, ordinati per nome ASC.
  • Esercizio 2: Filtra prodotti con categoria 'Elettronica' O quantita >100, usando LIKE per nomi contenenti 'o'.
  • Esercizio 3: Calcola un alias 'sconto_10' (prezzo * 0.9) per prodotti >200, limita a 3 risultati ordinati DESC per prezzo.
  • Bonus: Usa un dataset open (es. da SQLite sample DB) e testa query su dati reali.

English version

Module 2: Basic Query

Welcome to Module 2! Here we get to the heart of SQL, learning how to extract data from a database with simple but powerful queries. We assume you have already set up an RDBMS from Module 1 (e.g. MySQL or SQLite) and a test database with a simple table. For the examples, I will use a hypothetical database of a "store" with a products table that has columns like id, name, price, category and quantity. If you don't have it, create a sample table with these commands:

CREATE TABLE products ( 
id INT PRIMARY KEY, 
name VARCHAR(50), 
price DECIMAL(5,2), 
category VARCHAR(20), 
INT. quantity
);

INSERT INTO products VALUES
(1, 'Laptop', 999.99, 'Electronics', 50),
(2, 'Smartphone', 499.99, 'Electronics', 100),
(3, 'SQL Book', 29.99, 'Books', 200),
(4, 'Cup', 9.99, 'House', 150),
(5, 'Monitor', 199.99, 'Electronics', 30);
CREATE TABLE products ( 
id INT PRIMARY KEY, 
name VARCHAR(50), 
price DECIMAL(5,2), 
category VARCHAR(20), 
INT. quantity
);

INSERT INTO products VALUES
(1, 'Laptop', 999.99, 'Electronics', 50),
(2, 'Smartphone', 499.99, 'Electronics', 100),
(3, 'SQL Book', 29.99, 'Books', 200),
(4, 'Cup', 9.99, 'House', 150),
(5, 'Monitor', 199.99, 'Electronics', 30);

Now, let's delve into the points of the module with explanations, syntax, examples and tips. I will use standard SQL code; test everything in your environment!

1. Structure of a SQL Query: SELECT, FROM, WHERE

  • Overview: A basic query in SQL is like a request: "Select columns from a table, with optional filters". The minimum syntax is SELECT column FROM table;, but you often add WHERE to filter.

  • SELECT: Specify what you want (columns or * for all). E.g. SELECT name, price FROM products; returns only names and prices.

  • FROM: Indicates the source table.

  • WHERE: Filter rows based on conditions (e.g. price > 100).

  • Full example:

SELECT * 
FROM products 
WHERE category = 'Electronics'; 
SELECT * 
FROM products 
WHERE category = 'Electronics'; 

Expected result:

id name price category quantity
1 Laptops 999.99 Electronics 50
2 Smartphones 499.99 Electronics 100
5 Monitors 199.99 Electronics 30
  • Tips: Use * for testing only; specifies columns for efficiency. Queries are case-insensitive (e.g. select = SELECT), but table/column names depend on the RDBMS (MySQL is case-sensitive on Linux).

2. Filter Data with Conditions (AND, OR, LIKE, IN)

  • Basic operators: =, !=, >, <, >=, <= for comparisons. IS NULL or IS NOT NULL for null values.

  • AND/OR: Combine conditions. AND requires all true; OR at least one.

  • Example AND: WHERE price > 100 AND category = 'Electronics'; (expensive electronic products).

  • Example OR: WHERE category = 'Electronics' OR category = 'Books';.

  • LIKE: For pattern matching with wildcards. % for any string, _ for a single character.

  • Example: WHERE name LIKE 'L%'; (names starting with L, e.g. Laptop, Book).

  • IN: Check if a value is in a list.

  • Example: WHERE category IN ('Electronics', 'Home'); (products in these categories).

  • Combined example:

SELECT name, price 
FROM products 
WHERE (price BETWEEN 10 AND 500) AND name LIKE '%phone%'; 
SELECT name, price 
FROM products 
WHERE (price BETWEEN 10 AND 500) AND name LIKE '%phone%'; 

(Use BETWEEN for range; find Smartphone here.)

  • Tips: Use parentheses to group complex conditions. Avoid LIKE on large datasets (slow without indexes).

3. Order Results (ORDER BY) and Limit Output (LIMIT/OFFSET)

  • ORDER BY: Sorts the results. Add ASC (ascending, default) or DESC (descending). You can sort by multiple columns.

  • Example: SELECT * FROM products ORDER BY price DESC; (from most expensive to cheapest).

  • Multi-column: ORDER BY category ASC, price DESC; (first by category, then price descending).

  • LIMIT/OFFSET: Limit the number of rows. LIMIT n returns the first n; OFFSET sts skips the first sts.

  • Example: SELECT * FROM products ORDER BY price ASC LIMIT 2; (the 2 cheapest).

  • Pagination: LIMIT 3 OFFSET 3; (lines 4-6).

  • Full example:

SELECT name, price 
FROM products 
WHERE quantity > 50 
ORDER BY ASC price 
LIMIT 1; 
SELECT name, price 
FROM products 
WHERE quantity > 50 
ORDER BY ASC price 
LIMIT 1; 

(The cheapest product with stock >50, e.g. Mug).

  • Tips: ORDER BY is useful for reports; LIMIT for testing large tables. Note: OFFSET/LIMIT are standard, but some RDBMS use alternatives (e.g. TOP in SQL Server).

4. Aliases and Expressions

  • Alias: Rename columns or tables with AS for clarity.

  • Example: SELECT name AS product, price * 1.22 AS price_vat FROM products; (calculate VAT and rename).

  • Expressions: Calculations in queries, such as arithmetic (+, -, *, /) or functions (e.g. ROUND(price, 0)).

  • Example: SELECT name, (quantity * price) AS total_value FROM products;.

  • Tips: Alias ​​does not change the database, only the output. Useful for readable queries.

Module Objectives

  • Extract data from single tables with filters, sorts and limits.
  • Write efficient and readable queries.
  • Understand how SQL processes queries (first FROM, then WHERE, SELECT, ORDER BY).

Suggested Exercises

  • Exercise 1: Create the table products and enter the data. Then, write a query for all products with price <50, sorted by ASC name.
  • Exercise 2: Filter products with category 'Electronics' OR quantity >100, using LIKE for names containing 'o'.
  • Exercise 3: Calculate an alias 'discount_10' (price * 0.9) for products >200, limit to 3 results sorted DESC by price.
  • Bonus: Use an open dataset (e.g. from SQLite sample DB) and test queries on real data.

Puoi seguire anche il mio canale YouTube https://www.youtube.com/channel/UCoOgys_fRjBrHmx2psNALow/ con tanti video interessanti


I consigli che offriamo sono di natura generale. Non sono consigli legali o professionali. Quello che può funzionare per una persona potrebbe non essere adatto a un’altra, e dipende da molte variabili.

Commenti