SQL — DDL and DML · SQL — DDL y DML
| English | Español |
|---|---|
| SQL/ˌes kjuː ˈel/ | SQL |
| Data Definition Language/ˈdeɪtə ˌdefɪˈnɪʃn ˈlæŋɡwɪdʒ/ | Lenguaje de Definición de Datos |
| Data Manipulation Language/ˈdeɪtə məˌnɪpjʊˈleɪʃn ˈlæŋɡwɪdʒ/ | Lenguaje de Manipulación de Datos |
| INNER JOIN/ˈɪnə dʒɔɪn/ | INNER JOIN |
| aggregate functions/ˈæɡrɪɡeɪt ˈfʌŋkʃnz/ | funciones agregadas |
The language your grandparents' programmers also used
- In 1974 two IBM researchers designed a query language for Codd's tables and called it SEQUEL: Structured English Query Language. The name was trimmed to SQL 结构化查询语言, and the language never went away.
- Fifty years later, every bank, airline, hospital and website you use runs on it. A student typing
SELECTtoday is writing the same statement a programmer wrote before her parents were born. - It has two halves, and the exam asks you to read either and to write both: the Data Definition Language 数据定义语言 that builds the structure, and the Data Manipulation Language 数据操纵语言 that fills, changes and questions the data.
- This lesson is the subset of SQL on the syllabus, statement by statement, with the marks each one carries.
El lenguaje que también usaban los programadores de tus abuelos
- En 1974, dos investigadores de IBM diseñaron un lenguaje de consultas para las tablas de Codd y lo llamaron SEQUEL: Structured English Query Language. El nombre se acortó a SQL 结构化查询语言, y el lenguaje nunca dejó de existir.
- Cincuenta años después, cada banco, aerolínea, hospital y sitio web que utilizas funciona con él. Un estudiante que escribe
SELECThoy está escribiendo la misma instrucción que un programador escribió antes de que sus padres nacieran. - Tiene dos mitades, y el examen te pide leer cualquiera de ellas y escribir ambas: el Data Definition Language (DDL) 数据定义语言 que construye la estructura, y el Data Manipulation Language (DML) 数据操纵语言 que rellena, modifica e interroga los datos.
- Esta lección es el subconjunto de SQL en el temario, instrucción por instrucción, con los puntos que vale cada una.
DDL and DML
- The DBMS carries out all creation and modification of the database's structure through its DDL: creating a database, creating and altering tables, adding keys.
- It carries out all queries and maintenance of the data through its DML: selecting, inserting, updating and deleting rows.
- SQL is the industry standard for both. Sorting a statement into the right half is a common one-mark question:
CREATE TABLEis DDL,SELECTis DML.
Structure on one side, data on the other
DDL y DML
- El SGBD lleva a cabo toda creación y modificación de la estructura de la base de datos a través de su DDL: crear una base de datos, crear y alterar tablas, añadir claves.
- Lleva a cabo todas las consultas y mantenimiento de los datos a través de su DML: seleccionar, insertar, actualizar y eliminar filas.
- SQL es el estándar industrial para ambos. Clasificar una instrucción en la mitad correcta es una pregunta habitual de un punto:
CREATE TABLEes DDL,SELECTes DML.

Estructura en un lado, datos en el otro
Which is part of the Data Definition Language (DDL)? · ¿Cuál es parte del Lenguaje de Definición de Datos (DDL)?
DDL changes the structure (CREATE, ALTER, DROP). SELECT/INSERT/UPDATE/DELETE are DML (working with data). · DDL cambia la estructura (CREATE, ALTER, DROP). SELECT/INSERT/UPDATE/DELETE son DML (trabajo con datos).
DDL defines the structure (e.g. CREATE TABLE), while DML works with the data inside it (SELECT, INSERT, UPDATE, DELETE). · DDL define la estructura (ej. CREATE TABLE), mientras que DML trabaja con los datos dentro de ella (SELECT, INSERT, UPDATE, DELETE).
Definition vs Manipulation: DDL shapes the tables; DML reads and changes the rows. · Definición vs Manipulación: DDL da forma a las tablas; DML lee y cambia las filas.
DDL: creating the structure
- Data types on the syllabus:
CHARACTER(a fixed number of characters),VARCHAR(n)(up to n characters),BOOLEAN,INTEGER,REAL,DATE,TIME. PRIMARY KEY (field)names the key;ALTER TABLE … ADDadds an attribute to an existing table.
DDL: creando la estructura
CREATE DATABASE Shop;
CREATE TABLE CUSTOMER (
CustomerID INTEGER,
Name VARCHAR(50),
Town VARCHAR(30),
Joined DATE,
Active BOOLEAN,
PRIMARY KEY (CustomerID)
);
ALTER TABLE CUSTOMER ADD Email VARCHAR(100);
- Tipos de datos en el temario:
CHARACTER(un número fijo de caracteres),VARCHAR(n)(hasta n caracteres),BOOLEAN,INTEGER,REAL,DATE,TIME. PRIMARY KEY (field)nombra la clave;ALTER TABLE … ADDañade un atributo a una tabla existente.
Match each item of data to the SQL data type for it. · Asocia cada elemento de datos con el tipo de dato SQL correspondiente.
Two states, variable-length text, a number with a fractional part, a calendar date. INTEGER is for whole counts and TIME for a time of day. · Dos estados, texto de longitud variable, un número con parte fraccionaria, una fecha de calendario. INTEGER es para conteos enteros y TIME para una hora del día.
Worked example: two tables with a foreign key
- Write the SQL to create an
ORDERStable withOrderIDas primary key,CustomerIDas a foreign key toCUSTOMER, and anOrderDate.
- The marks:
CREATE TABLEwith the name; each attribute with a suitable type; thePRIMARY KEY; theFOREIGN KEY … REFERENCESnaming the table and its field.
Ejemplo resuelto: dos tablas con una clave foránea
- Escribe el SQL para crear una tabla
ORDERSconOrderIDcomo clave primaria,CustomerIDcomo clave foránea haciaCUSTOMER, y unOrderDate.
CREATE TABLE ORDERS (
OrderID INTEGER,
CustomerID INTEGER,
OrderDate DATE,
PRIMARY KEY (OrderID),
FOREIGN KEY (CustomerID) REFERENCES CUSTOMER(CustomerID)
);
- Los puntos:
CREATE TABLEcon el nombre; cada atributo con un tipo adecuado; laPRIMARY KEY; laFOREIGN KEY … REFERENCESnombrando la tabla y su campo.
DML: asking a question with SELECT
SELECTlists the fields to output (*for all),FROMnames the table,WHEREkeeps only the rows that meet a condition,ORDER BYsorts the result,ASCorDESC.- Strings go in single quotes; numbers do not. Comparisons:
=,<,>,<=,>=,<>; conditions join withAND,OR,NOT;LIKE 'A%'matches text starting with A;BETWEEN 10 AND 20gives a range.
Only the rows that pass the WHERE reach the result
DML: hacer una pregunta con SELECT
SELECT Name, Town
FROM CUSTOMER
WHERE Town = 'London'
ORDER BY Name ASC;
SELECTenumera los campos para la salida (*para todos),FROMnombra la tabla,WHEREconserva solo las filas que cumplen una condición,ORDER BYordena el resultado,ASCoDESC.- Las cadenas van entre comillas simples; los números no. Comparaciones:
=,<,>,<=,>=,<>; las condiciones se unen conAND,OR,NOT;LIKE 'A%'coincide con texto que comienza con A;BETWEEN 10 AND 20da un rango.

Solo las filas que pasan el WHERE llegan al resultado
Which SQL keyword retrieves data from a table? (one word) · ¿Qué palabra clave de SQL recupera datos de una tabla? (una palabra)
SELECT lists the fields to retrieve; FROM names the table. · SELECT lista los campos para recuperar; FROM nombra la tabla.
The WHERE clause in a SELECT statement: · La cláusula WHERE en una sentencia SELECT:
WHERE filters rows by a condition; ORDER BY sorts; the SELECT list chooses columns. · WHERE filtra filas por una condición; ORDER BY ordena; la lista de SELECT elige columnas.
Worked example: write the query
- Write an SQL script to output the names and email addresses of all active customers in Manchester, in alphabetical order of name.
- One mark each: the right fields after
SELECT; the right table afterFROM; theWHEREwith both conditions and the string in single quotes;ORDER BY Name. Use the exact table and field names the question gives.
Ejemplo resuelto: escribir la consulta
- Escribe un script SQL para的输出 los nombres y direcciones de correo electrónico de todos los clientes activos en Manchester, en orden alfabético de nombre.
SELECT Name, Email
FROM CUSTOMER
WHERE Town = 'Manchester' AND Active = TRUE
ORDER BY Name;
- Un punto cada uno: los campos correctos después de
SELECT; la tabla correcta después deFROM; elWHEREcon ambas condiciones y la cadena entre comillas simples;ORDER BY Name. Usa los nombres exactos de tabla y campo que da la pregunta.
Put the clauses of a SELECT statement in the order they are written. · Coloca las cláusulas de una sentencia SELECT en el orden en que se escriben.
Fields, table, filter, sort. ORDER BY is always last, and the statement ends with a semicolon. · Campos, tabla, filtro, orden. ORDER BY siempre va al final, y la sentencia termina con punto y coma.
Two tables: INNER JOIN
- An INNER JOIN 连接 combines the rows of two tables where the foreign key in one matches the primary key in the other, named in the
ONclause. - Prefix a field with its table when the same name appears in both. The syllabus asks for queries over at most two tables.
Dos tablas: INNER JOIN
SELECT CUSTOMER.Name, ORDERS.OrderDate
FROM CUSTOMER INNER JOIN ORDERS
ON CUSTOMER.CustomerID = ORDERS.CustomerID
WHERE ORDERS.OrderDate >= '2024-01-01';
- Un INNER JOIN 连接 combina las filas de dos tablas donde la clave foránea en una coincide con la clave primaria en la otra, nombradas en la cláusula
ON. - Prefija un campo con su tabla cuando el mismo nombre aparece en ambas. El temario pide consultas sobre como máximo dos tablas.
Stitch two tables with INNER JOIN · Combinar dos tablas con INNER JOIN
A join matches rows where the foreign key equals the primary key — here Orders.CustomerID = Customer.CustomerID — and combines each matching pair into one wider row. · Un join coincide filas donde la clave foránea es igual a la clave primaria — aquí Orders.CustomerID = Customer.CustomerID — y combina cada par coincidente en una sola fila más ancha.
An INNER JOIN is used to: · Se usa un INNER JOIN para:
A JOIN combines two tables on a relationship (usually a foreign key matching a primary key). · Un JOIN combina dos tablas sobre una relación (generalmente una clave foránea que coincide con una clave primaria).
Aggregates and GROUP BY
- Aggregate functions 聚合函数 summarise many rows into one value:
COUNTthe rows,SUMa total,AVGa mean. GROUP BYmakes one summary row per value of a field: the number of orders per customer. Without it, an aggregate summarises the whole table.
Agregados y GROUP BY
SELECT CustomerID, COUNT(*) AS NumOrders
FROM ORDERS
GROUP BY CustomerID;
SELECT AVG(Price) FROM PRODUCT;
SELECT SUM(Quantity) FROM ORDER_LINE WHERE OrderID = 1042;
- Las funciones agregadas 聚合函数 resumen muchas filas en un valor:
COUNTcuenta las filas,SUMsuma un total,AVGcalcula una media. GROUP BYcrea una fila de resumen por cada valor de un campo: el número de pedidos por cliente. Sin esto, un agregado resume toda la tabla.
What does COUNT(*) return? · ¿Qué devuelve COUNT(*)?
COUNT() counts rows; SUM/AVG/MIN/MAX are the other aggregate functions. · COUNT() cuenta filas; SUM/AVG/MIN/MAX son otras funciones agregadas.
To output the number of orders placed by each customer, the query needs: select all · todos that apply. · Para obtener el número de pedidos realizados por cada cliente, la consulta necesita: seleccione todos los que apliquen.
Count the rows, one group per customer, from the orders table. Sorting is optional. · Cuenta las filas, un grupo por cliente, desde la tabla de pedidos. El ordenamiento es opcional.
Changing the data: INSERT, UPDATE, DELETE
INSERT INTO … VALUESadds a row: list the fields, then the values in the same order.UPDATE … SET … WHEREchanges matching rows.DELETE FROM … WHEREremoves them.- Always give
UPDATEandDELETEaWHEREclause, or the change hits every row in the table.
Cambiando los datos: INSERT, UPDATE, DELETE
INSERT INTO CUSTOMER (CustomerID, Name, Town, Joined, Active)
VALUES (101, 'Ada Lovelace', 'London', '2024-03-01', TRUE);
UPDATE CUSTOMER SET Town = 'Bristol' WHERE CustomerID = 101;
DELETE FROM CUSTOMER WHERE CustomerID = 101;
INSERT INTO … VALUESañade una fila: enumere los campos, luego los valores en el mismo orden.UPDATE … SET … WHEREcambia las filas coincidentes.DELETE FROM … WHERElas elimina.- Siempre proporcione una cláusula
UPDATEparaDELETEyWHERE, o el cambio afectará a todas las filas de la tabla.
What happens if you run UPDATE or DELETE without a WHERE clause? · ¿Qué sucede si ejecutas UPDATE o DELETE sin una cláusula WHERE?
With no WHERE, the operation affects all rows — a common and dangerous mistake. · Sin WHERE, la operación afecta todas las filas — un error común y peligroso.
Match each DML statement to what it does. · Asocia cada sentencia DML con lo que hace.
SELECT reads; INSERT adds; UPDATE changes; DELETE removes — the four core DML verbs. · SELECT lee; INSERT añade; UPDATE cambia; DELETE elimina — los cuatro verbos principales DML.
Worked example: read the statement
- State what this script outputs. The names of every customer who placed an order on 1 May 2024, one row per such order, in reverse alphabetical order.
- Read it in execution order: join the tables on the customer ID, keep the rows for that date, output the name, sort descending. A customer with two orders that day appears twice.
Ejemplo resuelto: leer la instrucción
SELECT Name
FROM CUSTOMER INNER JOIN ORDERS
ON CUSTOMER.CustomerID = ORDERS.CustomerID
WHERE OrderDate = '2024-05-01'
ORDER BY Name DESC;
- Indique qué produce este script. Los nombres de cada cliente que realizó un pedido el 1 de mayo de 2024, una fila por tal pedido, en orden alfabético inverso.
- Léalo en orden de ejecución: una las tablas por el ID del cliente, conserve las filas de esa fecha, produzca el nombre, ordene descendente. Un cliente con dos pedidos ese día aparece dos veces.
Marks that slip away
- Strings in single quotes, numbers bare:
Town = 'London',CustomerID = 101. ORDER BYcomes afterWHERE; a join needs itsONclause; every statement ends with a semicolon.COUNT(*)counts rows, not distinct values; the per-group question needsGROUP BY.CREATE,ALTERandPRIMARY KEYare DDL;SELECT,INSERT,UPDATE,DELETEare DML. Use the exact names the question gives.
Puntos que se pierden
- Las cadenas en comillas simples, los números sin formato:
Town = 'London',CustomerID = 101. ORDER BYviene después deWHERE; un join necesita su cláusulaON; cada instrucción termina con punto y coma.COUNT(*)cuenta filas, no valores distintos; la pregunta por grupo necesitaGROUP BY.CREATE,ALTERyPRIMARY KEYson DDL;SELECT,INSERT,UPDATE,DELETEson DML. Use los nombres exactos que da la pregunta.
You've got it
- DDL creates and changes the structure:
CREATE DATABASE,CREATE TABLEwith typed attributes,PRIMARY KEY,FOREIGN KEY … REFERENCES,ALTER TABLE … ADD· DML works with the data - types:
CHARACTER,VARCHAR(n),BOOLEAN,INTEGER,REAL,DATE,TIME SELECT fields FROM table WHERE condition ORDER BY field;INNER JOIN … ONfor two tables;COUNT,SUM,AVGwithGROUP BYfor one row per groupINSERT INTO … VALUES,UPDATE … SET … WHERE,DELETE FROM … WHERE: never an update or delete withoutWHERE
Lo has logrado
- DDL crea y cambia la estructura:
CREATE DATABASE,CREATE TABLEcon atributos tipados,PRIMARY KEY,FOREIGN KEY … REFERENCES,ALTER TABLE … ADD· DML trabaja con los datos - tipos:
CHARACTER,VARCHAR(n),BOOLEAN,INTEGER,REAL,DATE,TIME SELECT fields FROM table WHERE condition ORDER BY field;INNER JOIN … ONpara dos tablas;COUNT,SUM,AVGconGROUP BYpara una fila por grupoINSERT INTO … VALUES,UPDATE … SET … WHERE,DELETE FROM … WHERE: nunca una actualización o eliminación sinWHERE