Modulo 3: Operazioni su Dati (DML - Data Manipulation Language)
Benvenuto al Modulo 3! Dopo aver imparato a estrarre dati con le query di base nel Modulo 2, ora passiamo a modificare i dati nel database. DML sta per Data Manipulation Language, che include i comandi per inserire, aggiornare ed eliminare record. Questi sono essenziali per gestire un database dinamico, ma attenzione: le modifiche sono permanenti, quindi usa un database di test!
Useremo la tabella prodotti dal Modulo 2 come esempio. Se non ce l'hai, ricreala con i dati iniziali. Approfondiamo i punti con sintassi, esempi e best practices. Tutti i comandi sono standard SQL; testali nel tuo RDBMS.
1. Inserire Dati (INSERT INTO)
-
Panoramica: Aggiunge nuove righe a una tabella. Puoi inserire un singolo record o multipli. Specifica le colonne (opzionale, ma consigliato per chiarezza) e i valori.
-
Sintassi base:
INSERT INTO tabella (colonna1, colonna2, ...) VALUES (valore1, valore2, ...);
INSERT INTO tabella (colonna1, colonna2, ...) VALUES (valore1, valore2, ...); -
Esempio singolo:
INSERT INTO prodotti (id, nome, prezzo, categoria, quantita) VALUES (6, 'Cuffie', 79.99, 'Elettronica', 80);
INSERT INTO prodotti (id, nome, prezzo, categoria, quantita) VALUES (6, 'Cuffie', 79.99, 'Elettronica', 80);(Aggiunge un nuovo prodotto. Verifica con
SELECT * FROM prodotti;) -
Esempio multiplo:
INSERT INTO prodotti (id, nome, prezzo, categoria, quantita) VALUES (7, 'Mouse', 29.99, 'Elettronica', 120), (8, 'Libro Python', 39.99, 'Libri', 150);
INSERT INTO prodotti (id, nome, prezzo, categoria, quantita) VALUES (7, 'Mouse', 29.99, 'Elettronica', 120), (8, 'Libro Python', 39.99, 'Libri', 150);(Inserisce due righe in una query sola, efficiente per batch.)
-
Consigli: Se ometti le colonne, i valori devono matching l'ordine della tabella. Usa apostrofi per stringhe (
'Elettronica'). In caso di auto-increment (es. ID con AUTO_INCREMENT), ometti la colonna ID.
2. Aggiornare Dati (UPDATE)
-
Panoramica: Modifica valori esistenti in una o più righe. Sempre usa
WHEREper limitare, altrimenti aggiorni tutta la tabella! -
Sintassi base:
UPDATE tabella SET colonna1 = valore1, colonna2 = valore2 WHERE condizione;
UPDATE tabella SET colonna1 = valore1, colonna2 = valore2 WHERE condizione; -
Esempio semplice:
UPDATE prodotti SET prezzo = 449.99 WHERE nome = 'Smartphone';
UPDATE prodotti SET prezzo = 449.99 WHERE nome = 'Smartphone';(Abbassa il prezzo dello Smartphone.)
-
Esempio avanzato:
UPDATE prodotti SET quantita = quantita + 50, categoria = 'Accessori' WHERE id IN (4, 7);
UPDATE prodotti SET quantita = quantita + 50, categoria = 'Accessori' WHERE id IN (4, 7);(Aumenta la quantità di 50 per ID 4 e 7, e cambia categoria.)
-
Consigli: Testa con
SELECTprima (es.SELECT * FROM prodotti WHERE condizione;) per vedere cosa modifichi. In transazioni (vedremo dopo), puoi rollback se sbagli.
3. Eliminare Dati (DELETE)
-
Panoramica: Rimuove righe. Come UPDATE, usa
WHEREper precisione; senza, svuoti la tabella! -
Sintassi base:
DELETE FROM tabella WHERE condizione;
DELETE FROM tabella WHERE condizione; -
Esempio:
DELETE FROM prodotti WHERE quantita = 0;
DELETE FROM prodotti WHERE quantita = 0;(Elimina prodotti esauriti.)
-
Esempio con sottquery (anticipo del Modulo 6):
DELETE FROM prodotti WHERE prezzo < (SELECT AVG(prezzo) FROM prodotti);
DELETE FROM prodotti WHERE prezzo < (SELECT AVG(prezzo) FROM prodotti);(Elimina prodotti sotto la media prezzi.)
-
Consigli: Per svuotare tutta la tabella, usa
TRUNCATE TABLE prodotti;(più veloce, ma non rollbackabile in alcuni RDBMS). Backup prima di DELETE massivi!
4. Gestione di Valori NULL e Default
-
NULL: Rappresenta "nessun valore". Non è zero o vuoto; è assenza. Usa
IS NULLnelle query. -
Default: Definisci valori predefiniti in CREATE TABLE (es.
quantita INT DEFAULT 0;). -
Esempi:
- Inserire NULL:
INSERT INTO prodotti (id, nome, prezzo) VALUES (9, 'Tablet', NULL);(prezzo sconosciuto). - Aggiornare a NULL:
UPDATE prodotti SET categoria = NULL WHERE id = 9;. - Query con NULL:
SELECT * FROM prodotti WHERE prezzo IS NULL;. - Default in creazione: Aggiungi colonna con
ALTER TABLE prodotti ADD descrizione VARCHAR(100) DEFAULT 'Non specificato';.
- Inserire NULL:
-
Consigli: Evita NULL se possibile (usa default). NULL può complicare aggregazioni (es. AVG ignora NULL).
Obiettivi del Modulo
- Modificare i dati in modo sicuro e controllato.
- Capire l'impatto di INSERT, UPDATE, DELETE.
- Gestire casi edge come NULL per dati robusti.
Esercizi Suggeriti
- Esercizio 1: Inserisci 3 nuovi prodotti nella tabella. Poi, aggiorna il prezzo di uno del 10% in meno.
- Esercizio 2: Elimina tutti i prodotti con categoria 'Libri'. Verifica con SELECT prima e dopo.
- Esercizio 3: Crea una nuova tabella
clienti(con colonne id, nome, email – email DEFAULT NULL). Inserisci dati con alcuni NULL, poi query per trovare NULL. - Bonus: Prova un errore intenzionale (es. INSERT con ID duplicato) e gestiscilo.
English version
Module 3: Data Operations (DML - Data Manipulation Language)
Welcome to Module 3! After learning how to extract data with basic queries in Module 2, we now move on to modifying data in the database. DML stands for Data Manipulation Language, which includes commands for inserting, updating, and deleting records. These are essential for managing a dynamic database, but be careful: changes are permanent, so use a test database!
We will use the products table from Module 2 as an example. If you don't have it, recreate it with the initial data. We delve deeper into the points with syntax, examples and best practices. All commands are standard SQL; test them in your RDBMS.
1. Insert Data (INSERT INTO)
-
Overview: Add new rows to a table. You can insert a single record or multiple. Specify columns (optional, but recommended for clarity) and values.
-
Basic syntax:
INSERT INTO table (column1, column2, ...) VALUES (value1, value2, ...);
INSERT INTO table (column1, column2, ...)
VALUES (value1, value2, ...); - Single example:
INSERT INTO products (id, name, price, category, quantity) VALUES (6, 'Headphones', 79.99, 'Electronics', 80);
INSERT INTO products (id, name, price, category, quantity)
VALUES (6, 'Headphones', 79.99, 'Electronics', 80); (Adds a new product. Check with SELECT * FROM products;)
- Multiple example:
INSERT INTO products (id, name, price, category, quantity) VALUES (7, 'Mouse', 29.99, 'Electronics', 120), (8, 'Python Book', 39.99, 'Books', 150);
INSERT INTO products (id, name, price, category, quantity)
VALUES
(7, 'Mouse', 29.99, 'Electronics', 120),
(8, 'Python Book', 39.99, 'Books', 150); (Inserts two rows into a single, batch-efficient query.)
- Tips: If you omit the columns, the values must match the table order. Use apostrophes for strings (
'Electronics'). In case of auto-increment (e.g. ID with AUTO_INCREMENT), omit the ID column.
2. Update Data (UPDATE)
-
Overview: Edit existing values in one or more rows. Always use
WHEREto limit, otherwise update the entire table! -
Basic syntax:
UPDATE table SET column1 = value1, column2 = value2 WHERE condition;
UPDATE table
SET column1 = value1, column2 = value2
WHERE condition; - Simple example:
UPDATE products SET price = 449.99 WHERE name = 'Smartphone';
UPDATE products
SET price = 449.99
WHERE name = 'Smartphone'; (Lowers the price of the Smartphone.)
- Advanced example:
UPDATE products SET quantity = quantity + 50, category = 'Accessories' WHERE id IN (4, 7);
UPDATE products
SET quantity = quantity + 50, category = 'Accessories'
WHERE id IN (4, 7); (Increase quantity by 50 for IDs 4 and 7, and change category.)
- Tips: Test with
SELECTfirst (e.g.SELECT * FROM products WHERE condition;) to see what you change. In transactions (we'll see later), you can rollback if you make a mistake.
3. Delete Data (DELETE)
-
Overview: Remove rows. Like UPDATE, use
WHEREfor precision; without it, empty the table! -
Basic syntax:
DELETE FROM table WHERE condition;
DELETE FROM table
WHERE condition; - Example:
DELETE FROM products WHERE quantity = 0;
DELETE FROM products
WHERE quantity = 0; (Delete out of stock products.)
- Example with subquery (advance of Module 6):
DELETE FROM products WHERE price < (SELECT AVG(price) FROM products);
DELETE FROM products
WHERE price < (SELECT AVG(price) FROM products); (Eliminate products below average prices.)
- Tips: To empty the entire table, use
TRUNCATE TABLE products;(faster, but not rollbackable in some RDBMS). Backups before massive DELETEs!
4. Management of NULL and Default Values
-
NULL: Represents "no value". It is not zero or empty; it is absence. Use
IS NULLin queries. -
Default: Define default values in CREATE TABLE (e.g.
quantity INT DEFAULT 0;). -
Examples:
-
Insert NULL:
INSERT INTO products (id, name, price) VALUES (9, 'Tablet', NULL);(price unknown). -
Update to NULL:
UPDATE products SET category = NULL WHERE id = 9;. -
Query with NULL:
SELECT * FROM products WHERE price IS NULL;. -
Default during creation: Add column with
ALTER TABLE products ADD description VARCHAR(100) DEFAULT 'Not specified';. -
Tips: Avoid NULL if possible (use default). NULL can complicate aggregations (e.g. AVG ignores NULL).
Module Objectives
- Edit data in a safe and controlled way.
- Understand the impact of INSERT, UPDATE, DELETE.
- Handle edge cases as NULL for robust data.
Suggested Exercises
- Exercise 1: Insert 3 new products in the table. Then, upgrade the price to one 10% less.
- Exercise 2: Delete all products with the 'Books' category. Check with SELECT before and after.
- Exercise 3: Create a new
customerstable (with columns id, name, email – email DEFAULT NULL). Insert data with some NULLs, then query to find NULLs. - Bonus: Try an intentional error (e.g. INSERT with duplicate ID) and deal with it.
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
Posta un commento