Comandos SQL básicos - a lista de consultas e instruções de banco de dados que você deve saber
SQL significa Structured Query Language. Os comandos SQL são as instruções usadas para se comunicar com um banco de dados para realizar tarefas, funções e consultas com dados.
Os comandos SQL podem ser usados para pesquisar o banco de dados e realizar outras funções, como criar tabelas, adicionar dados a tabelas, modificar dados e eliminar tabelas.
Aqui está uma lista de comandos SQL básicos (às vezes chamados de cláusulas) que você deve saber se for trabalhar com SQL.
SELECIONE e DE
A SELECT
parte de uma consulta determina quais colunas dos dados mostrar nos resultados. Também existem opções que você pode aplicar para mostrar dados que não são uma coluna da tabela.
O exemplo a seguir mostra três colunas SELECT
ed FROM
a tabela “estudante” e uma coluna calculada. O banco de dados armazena o studentID, FirstName e LastName do aluno. Podemos combinar as colunas Nome e Sobrenome para criar a coluna calculada FullName.
SELECT studentID, FirstName, LastName, FirstName + ' ' + LastName AS FullName FROM student;
+-----------+-------------------+------------+------------------------+ | studentID | FirstName | LastName | FullName | +-----------+-------------------+------------+------------------------+ | 1 | Monique | Davis | Monique Davis | | 2 | Teri | Gutierrez | Teri Gutierrez | | 3 | Spencer | Pautier | Spencer Pautier | | 4 | Louis | Ramsey | Louis Ramsey | | 5 | Alvin | Greene | Alvin Greene | | 6 | Sophie | Freeman | Sophie Freeman | | 7 | Edgar Frank "Ted" | Codd | Edgar Frank "Ted" Codd | | 8 | Donald D. | Chamberlin | Donald D. Chamberlin | | 9 | Raymond F. | Boyce | Raymond F. Boyce | +-----------+-------------------+------------+------------------------+ 9 rows in set (0.00 sec)
CRIAR A TABELA
CREATE TABLE
faz exatamente o que parece: cria uma tabela no banco de dados. Você pode especificar o nome da tabela e as colunas que devem estar na tabela.
CREATE TABLE table_name ( column_1 datatype, column_2 datatype, column_3 datatype );
ALTERAR A TABELA
ALTER TABLE
muda a estrutura de uma mesa. Aqui está como você adicionaria uma coluna a um banco de dados:
ALTER TABLE table_name ADD column_name datatype;
VERIFICA
A CHECK
restrição é usada para limitar o intervalo de valores que pode ser colocado em uma coluna.
Se você definir uma CHECK
restrição em uma única coluna, ela permitirá apenas determinados valores para esta coluna. Se você definir uma CHECK
restrição em uma tabela, ela pode limitar os valores de certas colunas com base nos valores de outras colunas da linha.
O seguinte SQL cria uma CHECK
restrição na coluna “Idade” quando a tabela “Pessoas” é criada. A CHECK
restrição garante que você não pode ter qualquer pessoa com menos de 18 anos.
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18) );
Para permitir a nomenclatura de uma CHECK
restrição e para definir uma CHECK
restrição em várias colunas, use a seguinte sintaxe SQL:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, City varchar(255), CONSTRAINT CHK_Person CHECK (Age>=18 AND City="Sandnes") );
ONDE
(AND
,OR
, IN
, BETWEEN
, E LIKE
)
A WHERE
cláusula é usada para limitar o número de linhas retornadas.
Como exemplo, primeiro mostraremos a você uma SELECT
declaração e os resultados sem uma WHERE
declaração. Em seguida, adicionaremos uma WHERE
instrução que usa todos os cinco qualificadores acima.
SELECT studentID, FullName, sat_score, rcd_updated FROM student;
+-----------+------------------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+------------------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 | | 3 | Spencer Pautier | 1000 | 2017-08-16 15:34:50 | | 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | | 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 | | 7 | Edgar Frank "Ted" Codd | 2400 | 2017-08-16 15:35:33 | | 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 | | 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 | +-----------+------------------------+-----------+---------------------+ 9 rows in set (0.00 sec)
Agora, vamos repetir a SELECT
consulta, mas limitaremos as linhas retornadas usando uma WHERE
instrução.
STUDENT studentID, FullName, sat_score, recordUpdated FROM student WHERE (studentID BETWEEN 1 AND 5 OR studentID = 8) AND sat_score NOT IN (1000, 1400);
+-----------+----------------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+----------------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 | | 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | | 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 | +-----------+----------------------+-----------+---------------------+ 5 rows in set (0.00 sec)
ATUALIZAR
Para atualizar um registro em uma tabela, você usa a UPDATE
instrução.
Use a WHERE
condição para especificar quais registros você deseja atualizar. É possível atualizar uma ou mais colunas por vez. A sintaxe é:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
Aqui está um exemplo de atualização do Nome do registro com Id 4:
UPDATE Person SET Name = “Elton John” WHERE Id = 4;
Você também pode atualizar colunas em uma tabela usando valores de outras tabelas. Use a JOIN
cláusula para obter dados de várias tabelas. A sintaxe é:
UPDATE table_name1 SET table_name1.column1 = table_name2.columnA table_name1.column2 = table_name2.columnB FROM table_name1 JOIN table_name2 ON table_name1.ForeignKey = table_name2.Key
Aqui está um exemplo de atualização do gerenciador de todos os registros:
UPDATE Person SET Person.Manager = Department.Manager FROM Person JOIN Department ON Person.DepartmentID = Department.ID
GRUPO POR
GROUP BY
permite combinar linhas e agregar dados.
Esta é a sintaxe de GROUP BY
:
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
TENDO
HAVING
permite filtrar os dados agregados pela GROUP BY
cláusula para que o usuário obtenha um conjunto limitado de registros para visualizar.
Esta é a sintaxe de HAVING
:
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING COUNT(*) > value;
AVG ()
“Média” é usada para calcular a média de uma coluna numérica do conjunto de linhas retornadas por uma instrução SQL.
Esta é a sintaxe para usar a função:
SELECT groupingField, AVG(num_field) FROM table1 GROUP BY groupingField
Aqui está um exemplo usando a tabela do aluno:
SELECT studentID, FullName, AVG(sat_score) FROM student GROUP BY studentID, FullName;
COMO
AS
permite renomear uma coluna ou tabela usando um alias.
SELECT user_only_num1 AS AgeOfServer, (user_only_num1 - warranty_period) AS NonWarrantyPeriod FROM server_table
Isso resulta na saída conforme abaixo.
+-------------+------------------------+ | AgeOfServer | NonWarrantyPeriod | +-------------+------------------------+ | 36 | 24 | | 24 | 12 | | 61 | 49 | | 12 | 0 | | 6 | -6 | | 0 | -12 | | 36 | 24 | | 36 | 24 | | 24 | 12 | +-------------+------------------------+
Você também pode usar AS para atribuir um nome a uma tabela para facilitar a referência nas junções.
SELECT ord.product, ord.ord_number, ord.price, cust.cust_name, cust.cust_number FROM customer_table AS cust JOIN order_table AS ord ON cust.cust_number = ord.cust_number
Isso resulta na saída conforme abaixo.
+-------------+------------+-----------+-----------------+--------------+ | product | ord_number | price | cust_name | cust_number | +-------------+------------+-----------+-----------------+--------------+ | RAM | 12345 | 124 | John Smith | 20 | | CPU | 12346 | 212 | Mia X | 22 | | USB | 12347 | 49 | Elise Beth | 21 | | Cable | 12348 | 0 | Paul Fort | 19 | | Mouse | 12349 | 66 | Nats Back | 15 | | Laptop | 12350 | 612 | Mel S | 36 | | Keyboard| 12351 | 24 | George Z | 95 | | Keyboard| 12352 | 24 | Ally B | 55 | | Air | 12353 | 12 | Maria Trust | 11 | +-------------+------------+-----------+-----------------+--------------+
ORDENAR POR
ORDER BY
gives us a way to sort the result set by one or more of the items in the SELECT
section. Here is an SQL sorting the students by FullName in descending order. The default sort order is ascending (ASC
) but to sort in the opposite order (descending) you use DESC
.
SELECT studentID, FullName, sat_score FROM student ORDER BY FullName DESC;
COUNT
COUNT
will count the number of rows and return that count as a column in the result set.
Here are examples of what you would use COUNT for:
- Counting all rows in a table (no group by required)
- Counting the totals of subsets of data (requires a Group By section of the statement)
This SQL statement provides a count of all rows. Note that you can give the resulting COUNT column a name using “AS”.
SELECT count(*) AS studentCount FROM student;
DELETE
DELETE
is used to delete a record in a table.
Be careful. You can delete all records of the table or just a few. Use the WHERE
condition to specify which records you want to delete. The syntax is:
DELETE FROM table_name WHERE condition;
Here is an example deleting from the table Person the record with Id 3:
DELETE FROM Person WHERE Id = 3;
INNER JOIN
JOIN
, also called Inner Join, selects records that have matching values in two tables.
SELECT * FROM A x JOIN B y ON y.aId = x.Id
LEFT JOIN
A LEFT JOIN
returns all rows from the left table, and the matched rows from the right table. Rows in the left table will be returned even if there was no match in the right table. The rows from the left table with no match in the right table will have null
for right table values.
SELECT * FROM A x LEFT JOIN B y ON y.aId = x.Id
RIGHT JOIN
A RIGHT JOIN
returns all rows from the right table, and the matched rows from the left table. Opposite of a left join, this will return all rows from the right table even where there is no match in the left table. Rows in the right table that have no match in the left table will have null
values for left table columns.
SELECT * FROM A x RIGHT JOIN B y ON y.aId = x.Id
FULL OUTER JOIN
A FULL OUTER JOIN
returns all rows for which there is a match in either of the tables. So if there are rows in the left table that do not have matches in the right table, those will be included. Also, if there are rows in the right table that do not have matches in the left table, those will be included.
SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName
INSERT
INSERT
is a way to insert data into a table.
INSERT INTO table_name (column_1, column_2, column_3) VALUES (value_1, 'value_2', value_3);
LIKE
LIKE
é usado em a WHERE
ou HAVING
(como parte de GROUP BY
) para limitar as linhas selecionadas aos itens quando uma coluna contém um certo padrão de caracteres.
Este SQL selecionará alunos que FullName
começam com “Monique” ou terminam com “Greene”.
SELECT studentID, FullName, sat_score, rcd_updated FROM student WHERE FullName LIKE 'Monique%' OR FullName LIKE '%Greene';
+-----------+---------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+---------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | +-----------+---------------+-----------+---------------------+ 2 rows in set (0.00 sec)
Você pode colocar NOT
antes LIKE
para excluir as linhas com o padrão de string em vez de selecioná-las. Este SQL exclui registros que contêm “cer Pau” e “Ted” na coluna FullName.
SELECT studentID, FullName, sat_score, rcd_updated FROM student WHERE FullName NOT LIKE '%cer Pau%' AND FullName NOT LIKE '%"Ted"%';
+-----------+----------------------+-----------+---------------------+ | studentID | FullName | sat_score | rcd_updated | +-----------+----------------------+-----------+---------------------+ | 1 | Monique Davis | 400 | 2017-08-16 15:34:50 | | 2 | Teri Gutierrez | 800 | 2017-08-16 15:34:50 | | 4 | Louis Ramsey | 1200 | 2017-08-16 15:34:50 | | 5 | Alvin Greene | 1200 | 2017-08-16 15:34:50 | | 6 | Sophie Freeman | 1200 | 2017-08-16 15:34:50 | | 8 | Donald D. Chamberlin | 2400 | 2017-08-16 15:35:33 | | 9 | Raymond F. Boyce | 2400 | 2017-08-16 15:35:33 | +-----------+----------------------+-----------+---------------------+ 7 rows in set (0.00 sec)