Você está na página 1de 16

Cheatsheets / Learn SQL

Manipulation

Column Constraints Restrições de coluna


Column constraints are the rules applied to the values of individual columns: CREATE TABLE student (
As restrições de coluna são as regras aplicadas aos valores de colunas id INTEGER PRIMARY KEY,
individuais:
name TEXT UNIQUE,
• PRIMARY KEY constraint can be used to uniquely identify the row.
• A restrição PRIMARY KEY pode ser utilizada para identificar a linha grade INTEGER NOT NULL,
de forma exclusiva. age INTEGER DEFAULT 10
• UNIQUE columns have a different value for every row.
• As colunas UNIQUE têm um valor diferente para cada linha.
• NOT NULL columns must have a value.
• As colunas NOT NULL devem ter um valor.
• DEFAULT assigns a default value for the column when no value is specified.
• DEFAULT atribui um valor por defeito à coluna quando não é CREATE TABLE table_name (
especificado qualquer valor. columnl datatype,
There can be only one PRIMARY KEY column per table and multiple column2 datatype,
UNIQUE columns.
column3 datatype
Só pode haver uma coluna PRIMARY KEY por tabela e várias colunas
UNIQUE.

CREATE TABLE Statement


The CREATE TABLE statement creates a new table in a database. It allows one to
specify the table’s name and each column in the table.

A instrução CREATE TABLE cria uma tabela numa base de dados. Permite
especificar o nome da tabela e o nome de cada coluna da tabela.
devem ser eliminados. Se a cláusula WHERE for omitida,
INSERT Statement (Instrução INSERT) todos os registos serão eliminados.

The INSERT INTO statement is used to add a new record (row) to a

UPDATE Statement
table.

A instrução INSERT INTO é utilizada para adicionar um novo The UPDATE statement is used to edit records (rows) in a table. It
registo (linha) a uma tabela. includes a SET clause that indicates the column to edit and a
• Insert into columns in order. WHERE clause for specifying the record(s).
• Inserir nas colunas por ordem.
• Insert into columns by name. A instrução UPDATE é utilizada para editar registos (linhas)
• Inserir em colunas por nome. numa tabela. Inclui uma cláusula SET que indica a coluna a
editar e uma cláusula WHERE para especificar o(s) registo(s)

-- Insert into columns in order:


INSERT INTO table_name

ALTER TABLE Statement


VALUES (value, value2);

-- Insert into columns by name:


The ALTER TABLE statement is used to modify the columns of an existing table. INSERT INTO table_name (column, column2)
When combined with the ADD COLD clause, it is used to add a new column.
VALUES (value, value2);
A instrução ALTER TABLE é utilizada para modificar as colunas de uma
tabela existente. Quando combinada com a cláusula ADD COLUMN, é
utilizada para adicionar uma nova coluna.

ALTER TABLE table_name

DELETE Statement
ADD column_name datatype;

The DELETE statement is used to delete records (rows) in


a table. The WHERE clause specifies which record or
records that should be deleted. If the WHERE clause is DELETE FROM table name
omitted, all records will be deleted. WHERE some column some value;

A instrução DELETE é utilizada para eliminar registos (linhas) numa


tabela. A cláusula WHERE especifica qual o registo ou registos que
SELECT model
UPDATE table_name FROM cars
SET columnl = valuel, column2 = value2 WHERE color = 'blue'
AND year > 2014;
WHERE some_column = some_value;

AS Clause

Queries Columns or tables can be aliased using


the AS clause. This allows columns or
tables to be specifically renamed in
the returned result set. The given
query will return a result set with
the column for name renamed to

AND Operator movie_title.

As colunas ou tabelas podem ser objeto


de apelidos utilizando a cláusula AS.
The AND operator allows multiple conditions
Isto permite que as colunas ou tabelas
to be combined. Records must match both
sejam especificamente renomeadas no
conditions that are joined by AND to be
conjunto de resultados devolvido. A
included in the result set. The given query
consulta dada retornará um conjunto de
will match any car that is blue and made
resultados com a coluna para o nome
after 2014.
renomeado para movie_title.
O operador AND permite a combinação de
várias condições. Os registos devem
corresponder a ambas as condições unidas SELECT name AS 'movie_title'

por AND para serem incluídos no conjunto de FROM movies;

resultados. A consulta dada corresponderá a


qualquer carro azul fabricado depois de
2014.
O wildcard % pode ser utilizado num
OR Operator
padrão do operador LIKE para
corresponder a zero ou mais caracteres
The OR operator allows multiple conditions
não especificados. A consulta dada
to be combined. Records matching either
corresponderá a qualquer filme que
condition joined by the OR are included in
comece com The, seguido de zero ou
the result set. The given query will match
mais de quaisquer caracteres.
customers whose state is either 'CA' or
'NY'.
SELECT name
O operador OR permite a combinação de várias
FROM movies
condições. Os registos que correspondem a
WHERE name LIKE 'The%';
uma das condições unidas pelo operador OR
são incluídos no conjunto de resultados. A
consulta fornecida corresponderá a clientes
cujo estado seja "CA" ou "NY". SELECT Statement

SELECT name The SELECT * statement returns all

FROM customers columns from the provided table in the


WHERE state = 'CA' result set. The given query will fetch

OR state = 'NY'; all columns and records (rows) from


the movies table.

A instrução SELECT * devolve todas as


colunas da tabela fornecida no
% Wildcard
conjunto de resultados. A consulta
fornecida irá obter todas as colunas e
The % wildcard can be used in a LIKE registos (linhas) da tabela de filmes.
operator pattern to match zero or more
unspecified character(s). The given query
will match any movie that begins with The, SELECT *
followed by zero or more of any characters. FROM movies;
ordered in two ways:

A cláusula ORDER BY pode ser utilizada


para ordenar o conjunto de resultados
por uma determinada coluna, quer
_ Wildcard alfabeticamente quer numericamente.
Pode ser ordenada de duas formas:
The _ wildcard can be used in a LIKE operator  DESC is a keyword used to sort
pattern to match any single unspecified the results in descending order.
character. The given query will match any
 DESC é uma palavra-chave
movie which begins with a single character,
utilizada para ordenar os
followed by ove.
resultados por ordem descendente.
O WILDCARD _ pode ser usado num padrão do
 ASC is a keyword used to sort the
operador LIKE para corresponder a qualquer
results in ascending order
caractere não especificado. A consulta dada
(default).
corresponderá a qualquer filme que comece
com um único carácter, seguido de ove.  ASC é uma palavra-chave utilizada
para ordenar os resultados por
ordem ascendente
(predefinição/padrão).

SELECT name
FROM movies
WHERE name LIKE '_ove';

SELECT *
FROM contacts
ORDER BY Clause
ORDER BY birth_date DESC;

The ORDER BY clause can be used to sort the


result set by a particular column either
alphabetically or numerically. It can be
Os valores únicos de uma coluna podem

LIKE Operator ser seleccionados utilizando uma


consulta DISTINCT. Para uma tabela
contact_details com cinco linhas em
The LIKE operator can be used inside of que a coluna city contém Chicago,
a WHERE clause to match a specified pattern. Madison, Boston, Madison e Denver, a
The given query will match any movie that consulta dada devolveria:
begins with Star in its title.
 Chicago
O operador LIKE pode ser utilizado dentro de
 Madison
uma cláusula WHERE para corresponder a um
padrão especificado. A consulta dada  Boston

corresponderá a qualquer filme que comece  Denver


com Star no seu título.

SELECT DISTINCT city


SELECT name FROM contact_details;
FROM movies
WHERE name LIKE 'Star%';

BETWEEN Operator

DISTINCT Clause
The BETWEEN operator can be used to
filter by a range of values. The range
Unique values of a column can be selected of values can be text, numbers, or
using a DISTINCT query. For a date data. The given query will match
table contact_details having five rows in any movie made between the years 1980
which the city column contains Chicago, and 1990, inclusive.
Madison, Boston, Madison, and Denver, the
O operador BETWEEN pode ser utilizado
given query would return:
para filtrar por um intervalo de
valores. O intervalo de valores pode ser
texto, números ou dados de data. A consulta
NULL Values
dada corresponderá a qualquer filme feito
entre os anos 1980 e 1990, inclusive.
Column values can be NULL, or have no
value. These records can be matched
SELECT * (or not matched) using the IS
FROM movies NULL and IS NOT NULL operators in
WHERE year BETWEEN 1980 AND 1990; combination with the WHERE clause. The
given query will match all addresses
where the address has a value or is
not NULL.

LIMIT Clause Os valores das colunas podem ser NULL,


ou seja, não têm valor. Estes registos
podem ser correspondidos (ou não
The LIMIT clause is used to narrow, or limit, correspondidos) utilizando os
a result set to the specified number of operadores IS NULL e IS NOT NULL em
rows. The given query will limit the result combinação com a cláusula WHERE. A
set to 5 rows.
consulta dada corresponderá a todos os
A cláusula LIMIT é utilizada para endereços em que o endereço tem um
restringir, ou limitar, um conjunto de valor ou não é NULL.
resultados ao número especificado de linhas.
A consulta dada limitará o conjunto de
SELECT address
resultados a 5 linhas.
FROM records
WHERE address IS NOT NULL;
SELECT *
FROM movies
LIMIT 5;
WHERE Clause Column References

The WHERE clause is used to filter records The GROUP BY and ORDER BY clauses can
(rows) that match a certain condition. The reference the selected columns by
given query will select all records where number in which they appear in
the pub_year equals 2017. the SELECT statement. The example query
will count the number of movies per
A cláusula WHERE é utilizada para filtrar
rating, and will:
registos (linhas) que correspondem a uma
determinada condição. A consulta dada As cláusulas GROUP BY e ORDER BY podem

selecionará todos os registos em que o referenciar as colunas selecionadas

pub_year é igual a 2017. pelo número em que aparecem na


instrução SELECT. A consulta de exemplo
irá contar o número de filmes por
SELECT title
classificação e irá:
FROM library
 GROUP BY column 2 (rating)
WHERE pub_year = 2017;
 GROUP BY coluna 2 (classificação)

 ORDER BY column 1 (total_movies)

 ORDER BY coluna 1 (total_movies)

SELECT COUNT(*) AS 'total_movies',

Aggregate Functions
rating
FROM movies
GROUP BY 2
ORDER BY 1;
SUM() Aggregate Function COUNT() Aggregate Function

The SUM() aggregate function takes the name The COUNT() aggregate function returns
of a column as an argument and returns the the total number of rows that match
sum of all the value in that column. the specified criteria. For instance,
to find the total number of employees
A função de agregação SUM() utiliza o nome
who have less than 5 years of
de uma coluna como argumento e devolve a
experience, the given query can be
soma de todos os valores dessa coluna.
used.

A função agregada COUNT() devolve o


SELECT SUM(salary)
número total de linhas que
FROM salary_disbursement;
correspondem aos critérios
especificados. Por exemplo, para
encontrar o número total de empregados

MAX() Aggregate Function com menos de 5 anos de experiência,


pode ser utilizada a consulta
apresentada.
The MAX() aggregate function takes the name
of a column as an argument and returns the Note: A column name of the table can

largest value in a column. The given query also be used instead of *.

will return the largest value from Unlike COUNT(*), this

the amount column. variation COUNT(column) will not


count NULL values in that column.
A função agregada MAX() utiliza o nome de
uma coluna como argumento e devolve o maior Nota: Também pode ser utilizado um
valor de uma coluna. A consulta fornecida nome de coluna da tabela em vez de *.
devolverá o maior valor da coluna amount. Ao contrário de COUNT(*), esta variação
COUNT(coluna) não contará valores NULL
nessa coluna.
SELECT MAX(amount)
FROM transactions;
SELECT COUNT(*) SELECT rating,
FROM employees COUNT(*)
WHERE experience < 5; FROM movies
GROUP BY rating;

GROUP BY Clause

The GROUP BY clause will group records in a MIN() Aggregate Function


result set by identical values in one or
more columns. It is often used in
The MIN() aggregate function returns
combination with aggregate functions to
the smallest value in a column. For
query information of similar records.
instance, to find the smallest value
The GROUP BY clause can come
of the amount column from the table
after FROM or WHERE but must come before
named transactions, the given query can
any ORDER BY or LIMIT clause. be used.
A cláusula GROUP BY agrupa os registos num A função agregada MIN() devolve o valor
conjunto de resultados por valores idênticos mais pequeno de uma coluna. Por
numa ou mais colunas. É frequentemente exemplo, para encontrar o valor mais
utilizada em combinação com funções pequeno da coluna de montante da
agregadas para consultar informações de tabela denominada transactions, pode
registos semelhantes. A cláusula GROUP BY ser utilizada a consulta fornecida.
pode vir depois de FROM ou WHERE, mas deve
vir antes de qualquer cláusula ORDER BY ou
SELECT MIN(amount)
LIMIT.
FROM transactions;
The given query will count the number of
movies per rating.

A consulta dada contará o número de filmes


por rating.
AVG() Aggregate Function movies were released per year.

A cláusula HAVING é utilizada para


filtrar ainda mais os grupos de
The AVG() aggregate function returns the
conjuntos de resultados fornecidos
average value in a column. For instance, to
pela cláusula GROUP BY. HAVING é
find the average salary for employees who
frequentemente utilizada com funções
have less than 5 years of experience, the
agregadas para filtrar os grupos do
given query can be used.
conjunto de resultados com base numa
A função de agregação AVG() devolve o valor propriedade agregada. A consulta dada
médio numa coluna. Por exemplo, para selecionará apenas os registos
encontrar o salário médio dos empregados que (linhas) dos anos em que foram lançados
têm menos de 5 anos de experiência, pode ser mais de 5 filmes por ano.
utilizada a consulta apresentada.
The HAVING clause must always come
after a GROUP BY clause but must come
SELECT AVG (salary) before any ORDER BY or LIMIT clause.
FROM employees
A cláusula HAVING deve vir sempre
WHERE experience < 5;
depois de uma cláusula GROUP BY, mas
deve vir antes de qualquer cláusula
ORDER BY ou LIMIT.

HAVING Clause

The HAVING clause is used to further filter


SELECT year,
the result set groups provided by the GROUP COUNT(*)
BY clause. HAVING is often used with FROM movies
aggregate functions to filter the result set GROUP BY year
groups based on an aggregate property. The HAVING COUNT(*) > 5;
given query will select only the records
(rows) from only years where more than 5
Aggregate Functions dois argumentos: um número e um número
de casas decimais. Pode ser combinada
com outras funções de agregação, como
Aggregate functions perform a calculation on
se mostra na consulta dada. Esta
a set of values and return a single value:
consulta calculará a classificação
As funções agregadas efetuam um cálculo num média dos filmes de 2015, arredondando
conjunto de valores e devolvem um único para 2 casas decimais.
valor:

 COUNT()
SELECT year,
 SUM() ROUND(AVG(rating), 2)
FROM movies
 MAX()
WHERE year = 2015;
 MIN()

 AVG()

ROUND() Function

The ROUND() function will round a number


Multiple Tables
value to a specified number of places. It
takes two arguments: a number, and a number
of decimal places. It can be combined with
other aggregate functions, as shown in the
given query. This query will calculate the Outer Join
average rating of movies from 2015, rounding
to 2 decimal places.
An outer join will combine rows from
A função ROUND() arredonda um valor numérico different tables even if the join
para um número especificado de casas. Recebe condition is not met. In a LEFT JOIN,
every row in the left table is returned in (temporary_movies) utilizando um
the result set, and if the join condition is alias.
not met, then NULL values are used to fill in Multiple temporary tables can be
the columns from the right table. defined with one instance of

Uma junção externa combinará linhas de the WITH keyword.

diferentes tabelas, mesmo que a condição de Podem ser definidas várias tabelas
junção não seja satisfeita. Numa LEFT JOIN, temporárias com uma instância da
todas as linhas da tabela da esquerda são palavra-chave WITH.
devolvidas no conjunto de resultados e, se a
condição de união não for satisfeita, são
utilizados valores NULL para preencher as WITH temporary_movies AS (

colunas da tabela da direita. SELECT *


FROM movies
)
SELECT column_name(s) SELECT *
FROM table1 FROM temporary_movies
LEFT JOIN table2 WHERE year BETWEEN 2000 AND 2020;
ON table1.column_name = table2.column_name;

UNION Clause
WITH Clause
The UNION clause is used to combine
The WITH clause stores the result of a query results that appear from
in a temporary table (temporary_movies) multiple SELECT statements and filter
using an alias. duplicates.

A cláusula WITH armazena o resultado de uma A cláusula UNION é utilizada para


consulta numa tabela temporária combinar resultados que aparecem em
várias instruções SELECT e filtrar
CROSS JOIN Clause
duplicados.

For example, given a first_names table with a


The CROSS JOIN clause is used to
column name containing rows of data “James”
combine each row from one table with
and “Hermione”, and a last_names table with a
each row from another in the result
column name containing rows of data “James”,
set. This JOIN is helpful for creating
“Hermione” and “Cassidy”, the result of this all possible combinations for the
query would contain three names: “Cassidy”, records (rows) in two tables.
“James”, and “Hermione”.
A cláusula CROSS JOIN é utilizada para
Por exemplo, dada uma tabela first_names com combinar cada linha de uma tabela com
um nome de coluna contendo linhas de dados cada linha de outra no conjunto de
"James" e "Hermione", e uma tabela resultados. Este JOIN é útil para criar
last_names com um nome de coluna contendo todas as combinações possíveis para os
linhas de dados "James", "Hermione" e
registos (linhas) em duas tabelas.
"Cassidy", o resultado desta consulta
The given query will select
conteria três nomes: "Cassidy", "James" e
the shirt_color and pants_color columns
"Hermione".
from the result set, which will
contain all combinations of combining
the rows in the shirts and pants tables.
If there are 3 different shirt colors
SELECT name
in the shirts table and 5 different
FROM first_names
UNION pants colors in the pants table then

SELECT name the result set will contain 3 x 5 = 15

FROM last_names rows.

A consulta dada selecionará as colunas


cor_da_camisa e cor_das_calças do
conjunto de resultados, que conterá
todas as combinações de linhas nas
tabelas de camisas e calças. Se houver 3 vital. Por exemplo, para registar
cores diferentes de camisas na tabela de todas as encomendas de um cliente
camisas e 5 cores diferentes de calças na específico, a tabela order (ilustrada
tabela de calças, o conjunto de resultados na parte inferior da imagem) pode

conterá 3 x 5 = 15 linhas. conter uma chave estrangeira.

SELECT shirts.shirt_color,
pants.pants_color
FROM shirts
CROSS JOIN pants;

Foreign Key

A foreign key is a reference in one table’s


records to the primary key of another table.
To maintain multiple records for a specific
row, the use of foreign key plays a vital
role. For instance, to track all the orders
of a specific customer, the
table order (illustrated at the bottom of the
image) can contain a foreign key.

Uma chave estrangeira é uma referência nos


Primary Key
registos de uma tabela à chave primária de
outra tabela. Para manter vários registos A primary key column in a SQL table is
para uma linha específica, a utilização de used to uniquely identify each record
uma chave estrangeira desempenha um papel in that table. A primary key cannot
be NULL. In the example, customer_id is the default JOIN and it will only return
primary key. The same value cannot re-occur results matching the condition
in a primary key column. Primary keys are specified by ON.
often used in JOIN operations.
A cláusula JOIN permite o retorno de
Uma coluna de chave primária numa tabela SQL resultados de mais de uma tabela,
é utilizada para identificar de forma única juntando-os a outros resultados com
cada registo nessa tabela. Uma chave base em valores de coluna comuns
primária não pode ser NULL. No exemplo, especificados através de uma cláusula
customer_id é a chave primária. O mesmo ON. INNER JOIN é o JOIN padrão e só
valor não pode voltar a ocorrer numa coluna retornará resultados que correspondam à
de chave primária. As chaves primárias são condição especificada por ON.
frequentemente utilizadas em operações JOIN.

SELECT *
FROM books
JOIN authors
ON books.author_id = authors.id;

Inner Join

The JOIN clause allows for the return of


results from more than one table by joining
them together with other results based on
common column values specified using
an ON clause. INNER JOIN is the

Você também pode gostar