Skip to content

Instantly share code, notes, and snippets.

@jean-cap
Last active July 5, 2018 18:15
Show Gist options
  • Save jean-cap/615947d7850e466d6ea9304b4789843a to your computer and use it in GitHub Desktop.
Save jean-cap/615947d7850e466d6ea9304b4789843a to your computer and use it in GitHub Desktop.
Anotações de alguns comandos SQL

Comandos SQL

Logar no MySQL

Comando

mysql -u <usuario> -p

Logout no MySQL

Comando

exit

Criar um banco de dados:

Comando

create database <nome_do_banco>

Saída

Query OK, 1 row affected (0,00 sec)

Excluir um banco de dados:

Comando

drop database <nome_do_banco>

Listar bancos de dados

Comando

show databases

Saída

+--------------------+
| Database           |
+--------------------+
| information_schema |
| controle_compras   |
| loja               |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
6 rows in set (0,00 sec)

Selecionar um banco de dados

Comando

use <nome_do_banco>

Saída

Database changed

Saber qual banco está selecionado

Comando

select database()

Criar uma tabela

Comando

create table usuario (
    id integer auto_increment primary key,
    nome varchar(255) not null,
    email varchar(255) not null
);

Saída

Query OK, 0 rows affected (0,32 sec)

Alterar uma tabela

Comando

alter table COMPRAS modify observacoes varchar(255) not null;

Saída

Query OK, 0 rows affected (0,64 sec)
Records: 0  Duplicates: 0  Warnings: 0

Visualizar as tabelas do banco de dados

Comando

show tables;

Saída

+----------------------------+
| Tables_in_controle_compras |
+----------------------------+
| compras                    |
| usuario                    |
+----------------------------+
2 rows in set (0,00 sec)

Exibir informações sobre uma determinada tabela

Comando

desc usuario;

Saída

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| nome  | varchar(255) | NO   |     | NULL    |                |
| email | varchar(255) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
3 rows in set (0,00 sec)

Inserir registro em uma tabela

Comando

insert into usuarios (nome, email) values ('Jean Carlos', 'jeancarlos@gmail.com');

Saída

Query OK, 1 row affected (0,04 sec)

Atualizar registro em uma tabela

Comando

update usuario set email = 'jeancarlos@outlook.com' where id = 1;

Saída

Rows matched: 1  Changed: 1  Warnings: 0

Consultando registros de uma tabela

Comando

select * from usuario;

Saída

+----+-------------+----------------------+
| id | nome        | email                |
+----+-------------+----------------------+
|  1 | Jean Carlos | jeancarlos@gmail.com |
+----+-------------+----------------------+
1 row in set (0,00 sec)

Filtrando resultado da consulta de registros de uma tabela

Comando

select * from usuario where email = 'jeancarlos@gmail.com';

Saída

+----+-------------+----------------------+
| id | nome        | email                |
+----+-------------+----------------------+
|  1 | Jean Carlos | jeancarlos@gmail.com |
+----+-------------+----------------------+
1 row in set (0,01 sec)

Filtrando resultado da consulta de registros de uma tabela onde o valor de determinada coluna é igual a NULL

Comando

select * from usuario where email is null;

Saída

Empty set (0,00 sec)

Filtrando resultado da consulta de registros de uma tabela com o operador between

Comando

select * from COMPRAS where valor between 1000 and 3000;

Saída

+----+--------+------------+----------+------------------------+
| id | valor  | data       | recebido | observacoes            |
+----+--------+------------+----------+------------------------+
|  3 | 1576.4 | 2008-04-30 |        1 | MATERIAL DE CONSTRUCAO |
|  7 |   1203 | 2009-03-18 |        1 | QUARTOS                |
| 14 |   2498 | 2009-01-12 |        1 | COMPRAS DE JANEIRO     |
| 22 |   1501 | 2010-06-22 |        0 | PRESENTE DA SOGRA      |
| 23 |   1709 | 2010-08-25 |        0 | PARCELA DA CASA        |
| 37 | 1245.2 | 2011-10-17 |        0 | ROUPAS                 |
+----+--------+------------+----------+------------------------+
6 rows in set (0,00 sec)

O operador between inclui o valor dado na consulta, neste caso ele trará todos os registros cujos valores sejam maior ou igual a 1000 e menor ou igual a 3000.

Obtendo a soma de uma coluna utilizando a função SOMA

Comando

select sum(valor) as Total from COMPRAS;

Saída

+-------------------+
| Total             |
+-------------------+
| 83971.17999999993 |
+-------------------+
1 row in set (0,00 sec)

Obtendo a total de registros de uma tabela utilizando a função COUNT

Comando

select sum(valor) as Total, count(valor) as Quantidade from COMPRAS;

Saída

+-------------------+------------+
| Total             | Quantidade |
+-------------------+------------+
| 83971.17999999993 |         83 |
+-------------------+------------+
1 row in set (0,00 sec)

Agrupando e ordenando

Comando

SELECT MONTH(DATA) AS MES, YEAR(DATA) AS ANO, SUM(VALOR) AS 'TOTAL NO PERIODO' FROM COMPRAS GROUP BY MONTH(DATA), YEAR(DATA) ORDER BY YEAR(DATA), MONTH(DATA);

Saída

+------+------+--------------------+
| MES  | ANO  | TOTAL NO PERIODO   |
+------+------+--------------------+
|    2 | 2008 |                420 |
|    4 | 2008 |             3172.8 |
|    5 | 2008 |               7020 |
|   12 | 2008 |              346.9 |
|    1 | 2009 |           16198.58 |
|    3 | 2009 |             1630.1 |
|    4 | 2009 | 129.95999999999998 |
|    5 | 2009 |              44.68 |
|    7 | 2009 |             196.24 |
|   11 | 2009 |             6424.8 |
|   12 | 2009 |             603.48 |
|    1 | 2010 |               1655 |
|    2 | 2010 |            1842.22 |
|    4 | 2010 | 24278.600000000002 |
|    5 | 2010 |            1356.86 |
|    6 | 2010 |             3233.8 |
|    8 | 2010 |               3418 |
|    9 | 2010 |            1134.18 |
|   10 | 2010 |            1459.06 |
|   12 | 2010 | 1681.6999999999998 |
|    2 | 2011 |            1085.06 |
|    5 | 2011 |             174.86 |
|    7 | 2011 |  88.86000000000001 |
|    9 | 2011 |            1579.24 |
|   10 | 2011 |             2490.4 |
|   11 | 2011 |            1908.24 |
|   12 | 2011 |              47.56 |
|   12 | 2017 |                350 |
+------+------+--------------------+
28 rows in set (0,03 sec)

Excluindo um registro

Comando

delete from usuario where id = 1;

Saída

Query OK, 1 row affected (0,06 sec)

Excluindo uma tabela

Comando

drop table usuario;

Saída

Query OK, 0 rows affected (0,18 sec)

Dar privilegios de acesso ao banco

Comando

grant all privileges on <nome_do_bando> to <nome_usuario>@<dominio>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment