Aula 04 - Comandos SQL
Aula 04 - Comandos SQL
Disciplina
12/12/2023 5
MySQL Tipo Texto
12/12/2023 6
MySQL Tipo para Numeros
Type Description
TINYINT(size) Pode conter números de -128 a 127 ou 0 a 255 NÃO SINALIZADO. O comprimento é definido usando parênteses.
SMALLINT(size) Pode conter números de -32768 a 32767 ou 0 a 65535 NÃO SINALIZADO. O comprimento é definido usando parênteses.
MEDIUMINT(size Pode conter números de -8388608 a 8388607 ou 0 a 16777215 NÃO SINALIZADO. O comprimento é definido usando parênteses.
INT(size) Pode conter números de -2147483648 a 2147483647 ou 0 a 4294967295 NÃO SINALIZADO. O comprimento é definido usando parênteses.
BIGINT(size) Pode conter números de -9223372036854775808 a 9223372036854775807 ou 0 a 18446744073709551615 NÃO SINALIZADO. O comprimento é definido usando parênteses.
FLOAT(size,d) Contém um número com um ponto decimal flutuante. O comprimento é definido usando o parâmetro tamanho d.
DOUBLE(size,d) Contém um grande número com um ponto decimal flutuante. O comprimento é definido usando o parâmetro tamanho d.
DECIMAL(size,d) Contém um grande número com um ponto decimal flutuante. Usado para casas decimais fixas. O comprimento é definido usando o parâmetro tamanho d. O tipo de texto acima está contido como string.
12/12/2023 7
MySQL Outros Tipos
12/12/2023 8
2
Comandos SQL
12/12/2023 12
Comandos SQL
ALTER TABLE
ALTER TABLE Developers
ALTER TABLE allows you to add
(ADD) or remove (DROP) columns ADD BirthDate date;
from a table.
12/12/2023 13
Comandos SQL
AS (alias) [1] [2]
SELECT ID as CustomerID, Name AS Customers
AS allows you to rename a column
or table to a more convenient alias FROM Customers;
12/12/2023 14
Comandos SQL
BETWEEN
SELECT * FROM Orders
BETWEEN operator filters the
results and returns only the ones WHERE Price BETWEEN 10 AND 15;
12/12/2023 15
Comandos SQL
CREATE DATABASE
CREATE DATABASE testingDB;
When you need to create a new
database, use the CREATE
DATABASE statement. You must
have admin rights to do that.
12/12/2023 16
Comandos SQL
CREATE TABLE
CREATE TABLE Suppliers (
CREATE TABLE statement creates
a new table in a database. SupplierID int,
FirstName varchar(255),
LastName varchar(255),
City varchar(255),
Country varchar(255)
);
12/12/2023 17
Comandos SQL
CREATE VIEW
CREATE VIEW [Present List Products] AS
CREATE VIEW creates a narrower
version of an existing table by SELECT ID, Name
12/12/2023 18
Comandos SQL
DELETE
DELETE FROM Developers
If you need to remove certain rows
from the table, use the DELETE WHERE Name='Antonio Indigo’;
FROM statement.
12/12/2023 19
Comandos SQL
GRANT
GRANT SELECT, UPDATE ON YOUR_TABLE TO FIRST_USER,
GRANT command is for giving SECOND_USER;
users the access to a database.
12/12/2023 20
Comandos SQL
REVOKE
REVOKE SELECT, UPDATE ON YOUR_TABLE FROM
REVOKE command is for taking FIRST_USER, SECOND_USER;
away users' permisions.
12/12/2023 21
Comandos SQL
COMMIT
DELETE FROM CUSTOMERS
COMMIT command is for saving
every transaction to the database. WHERE AGE = 18;
COMMIT;
12/12/2023 22
Comandos SQL
ROLLBACK
DELETE FROM CUSTOMERS
ROLLBACK command is for
undoing transactions which are not WHERE AGE = 18;
12/12/2023 23
Comandos SQL
SAVEPOINT
SAVEPOINT SAVEPOINT_NAME;
SAVEPOINT command is for
returning a transaction to a specific
point without affecting the whole
transaction.
12/12/2023 24
Comandos SQL
DROP DATABASE
DROP DATABASE db_name
DROP DATABASE is one of the
riskiest statements that should be
used with extra caution. In SQL,
drop means delete – and DROP
DATABASE deletes the whole
specified database together with all
its parameters and data.
12/12/2023 25
Comandos SQL
DROP INDEX
//SQL Server
DROP INDEX will delete the index
you specify. The syntax of this DROP INDEX tbl_name.indx_name
12/12/2023 26
Comandos SQL
DROP TABLE
DROP TABLE tbl_name
DROP TABLE statement deletes
the whole table with its column
parameters and datatype settings. If
you want to remove only the
contents of the rows but keep the
table itself, use another statement –
TRUNCATE TABLE.
12/12/2023 27
Comandos SQL
EXISTS
SELECT id, name
EXISTS operator allows you to
check whether a record exists by FROM customers
writing a subquery. If the record is WHERE EXISTS (SELECT id FROM customer_orders WHERE
customer_orders.customer_id = customers.id AND
found, the result is displayed based customers.city = "Rome");
on the statement you use this
operator with. You can use it with
SELECT, UPDATE, INSERT, and
DELETE.
12/12/2023 28
Comandos SQL
GROUP BY
SELECT COUNT(ID), City
Combine GROUP BY with
SELECT statement in order to FROM Developers
12/12/2023 29
Comandos SQL
HAVING
SELECT COUNT(ID), Country
HAVING specifies that you need to
filter the results to only the rows FROM Pets
12/12/2023 30
Comandos SQL
IN
SELECT * FROM Developers
The IN operator includes multiple
values into the WHERE clause. WHERE Country IN ('USA', 'France', 'India');
12/12/2023 31
Comandos SQL
INSERT INTO
INSERT INTO Developers (Name, City, Country)
INSERT INTO statement inserts
new rows of data into a table. VALUES ('Luke Christon', 'London', 'UK');
12/12/2023 32
Comandos SQL
INNER JOIN
SELECT Orders.ID, Developers.Name
INNER JOIN combines rows from
different tables. FROM Orders
INNER JOIN Developers ON Orders.ID = Developers.ID;
12/12/2023 33
Comandos SQL
LEFT JOIN
SELECT Developers.Name, Customer_orders.ID
LEFT JOIN retrieves records from
the left table that match records in FROM Developers
12/12/2023 34
Comandos SQL
RIGHT JOIN
SELECT Customer_orders.ID, Employees.Last_name,
RIGHT JOIN retrieves records Employees.First_name
from the right table that match FROM Customer_orders
records in the left table. Some RIGHT JOIN Employees ON Customer_orders.employee_id
databases call this statement = Employees.ID
differently – RIGHT OUTER ORDER BY Customer_orders.ID;
JOIN.
12/12/2023 35
Comandos SQL
FULL JOIN
SELECT Customers.Name, Customer_orders.ID
FULL JOIN returns all the records
that match either in left or right FROM Customers
12/12/2023 36
Comandos SQL
LIKE
SELECT * FROM users WHERE email LIKE '%gmail%';
Combine LIKE with the WHERE
clause for finding specific patterns
in columns.
12/12/2023 37
Comandos SQL
ORDER BY
SELECT * FROM users ORDER BY email DESC;
ORDER BY sets the order
(ascending by default) of result
records.
12/12/2023 38
Comandos SQL
SELECT
SELECT username,email
SELECT is one of the main SQL
statements. It selects data from a FROM users;
12/12/2023 39
Comandos SQL
SELECT *
SELECT * FROM Customers;
SELECT used with an asterisk *
operator selects all data records
from a specified table.
12/12/2023 40
Comandos SQL
SELECT DISTINCT
SELECT DISTINCT City FROM Developers;
SELECT DISTINCT returns only
the data that is distinct, and does
not include duplicate entries.
12/12/2023 41
Comandos SQL
SELECT INTO
SELECT * INTO CustomerBackup2018
SELECT INTO statement selects
specified data in a table and copies FROM Customers;
it to another table.
12/12/2023 42
Comandos SQL
SELECT TOP
SELECT * FROM Customers
SELECT TOP specifies the
maximum number or percentage of LIMIT 3;
12/12/2023 43
Comandos SQL
TRUNCATE TABLE
TRUNCATE TABLE tbl_name
TRUNCATE TABLE removes data
entries from a table in a database,
but keeps the table, its datatype and
column parameters.
12/12/2023 44
Comandos SQL
UNION
SELECT City FROM Developers
You can combine multiple result-
sets using the UNION operator UNION
12/12/2023 45
Comandos SQL
UNION ALL
SELECT City FROM Developers
UNION ALL is used to combine
two or more result-sets and keep all UNION ALL
12/12/2023 46
Comandos SQL
UPDATE
UPDATE Developers
UPDATE statement is used with the
WHERE clause to update data in SET City = 'Berlin', Country= 'Germany'
12/12/2023 47
Comandos SQL
WHERE
SELECT * FROM Developers
WHERE clause specifies your
query to filter only the results that WHERE Country='France';
12/12/2023 48
3
SQL Wildcards
12/12/2023 49
SQL Wildcards
• Os Wildcards têm a mesma finalidade que as expressões
regulares;
• Um caractere curinga é um caractere alternativo que
substitui outro (s) caractere (s) em uma string.
• Os curingas SQL são úteis quando você deseja realizar uma
pesquisa mais rápida de dados em um banco de dados.
• [charlist], [^ charlist] e [! charlist] podem ser usados no
SQL Server.
• Você pode combinar vários Wildcards.
12/12/2023 50
Wildcards para Caracteres
%
SELECT * FROM Developers
Uma alternativa para mais de zero WHERE City LIKE 'pa%';
caracteres.
Este exemplo seleciona todos os
desenvolvedores com uma cidade
começando com 'pa'.
12/12/2023 51
Wildcards para Caracteres
%
SELECT * FROM Developers
Este exemplo seleciona todos os WHERE City LIKE '%am%';
desenvolvedores com uma cidade
contendo o padrão 'am'.
12/12/2023 52
Wildcards para Caracteres
_
SELECT * FROM Developers
Uma alternativa para um único WHERE City LIKE ‘_ondon';
carácter.
Este exemplo seleciona todos os
desenvolvedores com uma cidade
começando com qualquer caractere,
seguido por 'ondon'.
12/12/2023 53
Wildcards para Caracteres
_
SELECT * FROM Developers
Este exemplo seleciona todos os WHERE City LIKE ‘D_l_i';
desenvolvedores com uma cidade
começando com 'D', seguido por
qualquer caractere, seguido por 'l',
seguido por qualquer caractere,
seguido por 'i'.
12/12/2023 54
Wildcards para Caracteres
[charlist]
SELECT * FROM Developers
Especifica intervalos de caracteres WHERE City LIKE '[nlm]%';
e conjuntos correspondentes.
Este exemplo seleciona todos os
desenvolvedores com uma cidade
começando com 'n', 'l' ou 'm'.
12/12/2023 55
Wildcards para Caracteres
[charlist]
SELECT * FROM Developers
Este exemplo seleciona todos os WHERE City LIKE '[a-d]%';
desenvolvedores com uma cidade
começando com 'a', 'b', 'c' ou 'd'.
12/12/2023 56
Wildcards para Caracteres
[^charlist] e [!charlist]
SELECT * FROM Developers
Especifica intervalos de caracteres WHERE City LIKE '[!pdm]%';
e define NÃO para corresponder.
Este exemplo seleciona todos os
desenvolvedores com uma cidade
que NÃO começa com 'p', 'd' ou
'm'.
12/12/2023 57
4 Considerações e
Restrições SQL
12/12/2023 58
Considerações e Restrições
• NOT NULL - não há valor NULL contido em uma coluna;
• UNIQUE - cada linha em uma coluna específica precisa de um
valor único;
• PRIMARY KEY - uma combinação de UNIQUE e NOT NULL: as
colunas devem ter uma identidade única. Isso ajuda quando você
precisa localizar um registro de dados específico mais rápido;
• FOREIGN KEY - a integridade referencial SQL de uma tabela
corresponde à de outra tabela;
• CHECK - uma condição definida é atendida dentro do valor;
• DEFAULT - valor da coluna de estoque.
12/12/2023 59
Considerações e Restrições
CONSTRAINS
• NOT NULL CREATE TABLE table_name (
column1 datatype constraint_one,
12/12/2023 61
Step-by-step
• Abrindo o mySQL via console
• Criando SCHEMA
• “Selecione” o SCHEMA
• Criando TABELA
12/12/2023 62
Console mySQL
mysql.exe
• Abra o prompt de comando e vá até a C:\ cd C:\Program Files\MySQL\MySQL Workbench 8.0 CE
<ENTER>
pasta de instalação do mySQL
Workbench (C:\Program Files\MySQL\ C:\Program Files\MySQL\MySQL Workbench 8.0 CE>
MySQL Workbench 8.0 CE); mysql –u root –p
12/12/2023 63
CREATE {DATABASE
CREATE {DATABASE | SC
| SCHEMA }
HEMA}
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
Cria um Banco de Dados [create_option] ...
novo.
create_option: [DEFAULT] {
CHARACTER SET [=] charset_name
| COLLATE [=] collation_name
| ENCRYPTION [=] {'Y' | 'N'}
}
12/12/2023 64
DROP { DATABASE | SCHEMA }
DROP { DATABASE | SCH
EMA } DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
Apaga um Banco de
Dados.
12/12/2023 65
Selecionando um Schema
USE
use db_name;
A instrução USE diz ao USE db1;
MySQL para usar o SELECT COUNT(*) FROM mytable; # selects from
db1.mytable;
banco de dados nomeado USE db2;
como o banco de dados SELECT COUNT(*) FROM mytable; # selects from
db2.mytable;
padrão (atual) para
instruções subsequentes. USE db1;
SELECT author_name,editor_name FROM
author,db2.editor
WHERE author.editor_id = db2.editor.editor_id;
12/12/2023 66
CREATE TABLE
CREATE TABLE
12/12/2023 67
Referência
• Referencia https://www.bitdegree.org/learn/