SQL — DDL and DML · SQL — DDL e DML
| English | Português |
|---|---|
| SQL/ˌes kjuː ˈel/ | SQL |
| Data Definition Language/ˈdeɪtə ˌdefɪˈnɪʃn ˈlæŋɡwɪdʒ/ | Linguagem de Definição de Dados |
| Data Manipulation Language/ˈdeɪtə məˌnɪpjʊˈleɪʃn ˈlæŋɡwɪdʒ/ | Linguagem de Manipulação de Dados |
| INNER JOIN/ˈɪnə dʒɔɪn/ | INNER JOIN |
| aggregate functions/ˈæɡrɪɡeɪt ˈfʌŋkʃnz/ | funções 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.
A linguagem que os programadores dos seus avós também usavam
- Em 1974, dois pesquisadores da IBM projetaram uma linguagem de consulta para as tabelas de Codd e a chamaram SEQUEL: Structured English Query Language. O nome foi abreviado para SQL 结构化查询语言, e a linguagem nunca deixou de existir.
- Cinquenta anos depois, todo banco, companhia aérea, hospital e site que você usa roda nele. Um aluno digitando
SELECThoje está escrevendo a mesma instrução que um programador escreveu antes de seus pais nascerem. - Ela tem duas partes, e a prova pede para você ler qualquer uma e escrever ambas: a Data Definition Language 数据定义语言 que constrói a estrutura, e a Data Manipulation Language 数据操纵语言 que preenche, altera e questiona os dados.
- Esta lição é o subconjunto de SQL no programa escolar, instrução por instrução, com as marcas que cada uma vale.
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 e DML
- O SGBD realiza todas as criações e modificações da estrutura do banco de dados através de seu DDL: criando um banco de dados, criando e alterando tabelas, adicionando chaves.
- Ele realiza todas as consultas e manutenções dos dados através de seu DML: selecionando, inserindo, atualizando e excluindo linhas.
- SQL é o padrão industrial para ambos. Classificar uma instrução na parte correta é uma pergunta comum de uma marca:
CREATE TABLEé DDL,SELECTé DML.

*Estrutura de um lado, dados do outro
Which is part of the Data Definition Language (DDL)? · Qual é parte da Linguagem de Definição de Dados (DDL)?
DDL changes the structure (CREATE, ALTER, DROP). SELECT/INSERT/UPDATE/DELETE are DML (working with data). · DDL altera a estrutura (CREATE, ALTER, DROP). SELECT/INSERT/UPDATE/DELETE são DML (trabalhar com dados).
DDL defines the structure (e.g. CREATE TABLE), while DML works with the data inside it (SELECT, INSERT, UPDATE, DELETE). · DDL define a estrutura (ex. CREATE TABLE), enquanto DML trabalha com os dados dentro dela (SELECT, INSERT, UPDATE, DELETE).
Definition vs Manipulation: DDL shapes the tables; DML reads and changes the rows. · Definição vs Manipulação: DDL molda as tabelas; DML lê e altera as linhas.
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: criando a estrutura
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 dados no programa escolar:
CHARACTER(um número fixo de caracteres),VARCHAR(n)(até n caracteres),BOOLEAN,INTEGER,REAL,DATE,TIME. PRIMARY KEY (field)nomeia a chave;ALTER TABLE … ADDadiciona um atributo a uma tabela existente.
Match each item of data to the SQL data type for it. · Associe cada item de dado ao tipo de dado SQL correspondente.
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. · Dois estados, texto de comprimento variável, um número com parte fracionária, uma data de calendário. INTEGER é para contagens inteiras e TIME para uma hora do dia.
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.
Exemplo resolvido: duas tabelas com uma chave estrangeira
- Escreva o SQL para criar uma tabela
ORDERScomOrderIDcomo chave primária,CustomerIDcomo chave estrangeira paraCUSTOMER, e umOrderDate.
CREATE TABLE ORDERS (
OrderID INTEGER,
CustomerID INTEGER,
OrderDate DATE,
PRIMARY KEY (OrderID),
FOREIGN KEY (CustomerID) REFERENCES CUSTOMER(CustomerID)
);
- As marcas:
CREATE TABLEcom o nome; cada atributo com um tipo adequado; aPRIMARY KEY; aFOREIGN KEY … REFERENCESnomeando a tabela e seu 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: fazendo uma pergunta com SELECT
SELECT Name, Town
FROM CUSTOMER
WHERE Town = 'London'
ORDER BY Name ASC;
SELECTlista os campos a serem exibidos (*para todos),FROMnomeia a tabela,WHEREmantém apenas as linhas que atendem a uma condição,ORDER BYordena o resultado,ASCouDESC.- Strings vão entre aspas simples; números não. Comparações:
=,<,>,<=,>=,<>; condições são unidas porAND,OR,NOT;LIKE 'A%'corresponde a texto começando com A;BETWEEN 10 AND 20dá uma faixa.

*Apenas as linhas que passam no WHERE chegam ao resultado
Which SQL keyword retrieves data from a table? (one word) · Qual palavra-chave SQL recupera dados de uma tabela? (uma palavra)
SELECT lists the fields to retrieve; FROM names the table. · SELECT lista os campos a serem recuperados; FROM nomeia a tabela.
The WHERE clause in a SELECT statement: · A cláusula WHERE em uma instrução SELECT:
WHERE filters rows by a condition; ORDER BY sorts; the SELECT list chooses columns. · WHERE filtra linhas por condição; ORDER BY ordena; a lista SELECT escolhe colunas.
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.
Exemplo resolvido: escreva a consulta
- Escreva um script SQL para exibir os nomes e endereços de e-mail de todos os clientes ativos em Manchester, em ordem alfabética de nome.
SELECT Name, Email
FROM CUSTOMER
WHERE Town = 'Manchester' AND Active = TRUE
ORDER BY Name;
- Uma marca cada: os campos certos após
SELECT; a tabela certa apósFROM; oWHEREcom ambas as condições e a string entre aspas simples;ORDER BY Name. Use os nomes exatos de tabela e campo que a questão fornece.
Put the clauses of a SELECT statement in the order they are written. · Coloque as cláusulas de uma instrução SELECT na ordem em que são escritas.
Fields, table, filter, sort. ORDER BY is always last, and the statement ends with a semicolon. · Campos, tabela, filtro, ordenação. ORDER BY vem sempre por último, e a instrução termina com ponto e vírgula.
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.
Duas tabelas: INNER JOIN
SELECT CUSTOMER.Name, ORDERS.OrderDate
FROM CUSTOMER INNER JOIN ORDERS
ON CUSTOMER.CustomerID = ORDERS.CustomerID
WHERE ORDERS.OrderDate >= '2024-01-01';
- Um INNER JOIN 连接 combina as linhas de duas tabelas onde a chave estrangeira em uma corresponde à chave primária na outra, nomeada na cláusula
ON. - Prefixe um campo com sua tabela quando o mesmo nome aparecer em ambas. O programa escolar pede consultas em no máximo duas tabelas.
Stitch two tables with INNER JOIN · Unir duas tabelas com 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. · Um join combina linhas onde a chave estrangeira é igual à chave primária — aqui Orders.CustomerID = Customer.CustomerID — e une cada par correspondente em uma linha mais larga.
An INNER JOIN is used to: · Um INNER JOIN é usado para:
A JOIN combines two tables on a relationship (usually a foreign key matching a primary key). · Um JOIN combina duas tabelas com base em um relacionamento (geralmente uma chave estrangeira correspondendo a uma chave primária).
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 e 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;
- Funções agregadas 聚合函数 resumem muitas linhas em um único valor:
COUNTcontar as linhas,SUMsomar um total,AVGcalcular uma média. GROUP BYcria uma linha de resumo por valor de um campo: o número de pedidos por cliente. Sem isso, um agregado resume toda a tabela.
What does COUNT(*) return? · O que COUNT(*) retorna?
COUNT() counts rows; SUM/AVG/MIN/MAX are the other aggregate functions. · COUNT() conta linhas; SUM/AVG/MIN/MAX são as outras funções agregadas.
To output the number of orders placed by each customer, the query needs: select all · todos that apply. · Para exibir o número de pedidos feitos por cada cliente, a consulta precisa: selecione todos os que se aplicam.
Count the rows, one group per customer, from the orders table. Sorting is optional. · Conte as linhas, um grupo por cliente, a partir da tabela de pedidos. A ordenação é 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.
Alterando os dados: 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 … VALUESadiciona uma linha: liste os campos, depois os valores na mesma ordem.UPDATE … SET … WHEREaltera linhas correspondentes.DELETE FROM … WHEREremove-as.- Sempre dê a
UPDATEeDELETEuma cláusulaWHERE, ou a alteração atingirá todas as linhas da tabela.
What happens if you run UPDATE or DELETE without a WHERE clause? · O que acontece se você executar UPDATE ou DELETE sem uma cláusula WHERE?
With no WHERE, the operation affects all rows — a common and dangerous mistake. · Sem WHERE, a operação afeta todas as linhas — um erro comum e perigoso.
Match each DML statement to what it does. · Associe cada instrução DML ao que ela faz.
SELECT reads; INSERT adds; UPDATE changes; DELETE removes — the four core DML verbs. · SELECT lê; INSERT adiciona; UPDATE altera; DELETE remove — os quatro verbos principais 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.
Exemplo resolvido: leia a instrução
SELECT Name
FROM CUSTOMER INNER JOIN ORDERS
ON CUSTOMER.CustomerID = ORDERS.CustomerID
WHERE OrderDate = '2024-05-01'
ORDER BY Name DESC;
- Afirme o que este script exibe. Os nomes de todos os clientes que fizeram um pedido em 1º de maio de 2024, uma linha por tal pedido, em ordem alfabética reversa.
- Leia-o na ordem de execução: junte as tabelas pelo ID do cliente, mantenha as linhas daquela data, exiba o nome, ordene descendente. Um cliente com dois pedidos naquele dia aparece duas vezes.
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.
Marcas que escapam
- Strings entre aspas simples, números nus:
Town = 'London',CustomerID = 101. ORDER BYvem depois deWHERE; um join precisa de sua cláusulaON; toda instrução termina com ponto e vírgula.COUNT(*)conta linhas, não valores distintos; a questão por grupo precisa deGROUP BY.CREATE,ALTERePRIMARY KEYsão DDL;SELECT,INSERT,UPDATE,DELETEsão DML. Use os nomes exatos que a questão fornece.
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
Entendeu?
- DDL cria e altera a estrutura:
CREATE DATABASE,CREATE TABLEcom atributos tipados,PRIMARY KEY,FOREIGN KEY … REFERENCES,ALTER TABLE … ADD· DML trabalha com os dados - tipos:
CHARACTER,VARCHAR(n),BOOLEAN,INTEGER,REAL,DATE,TIME SELECT fields FROM table WHERE condition ORDER BY field;INNER JOIN … ONpara duas tabelas;COUNT,SUM,AVGcomGROUP BYpara uma linha por grupoINSERT INTO … VALUES,UPDATE … SET … WHERE,DELETE FROM … WHERE: nunca uma atualização ou exclusão semWHERE