Esses foram os primeiros projetos do módulo de backend do curso de Desenvolvedor Web Full Stack da Trybe usando banco de dados relacionais - MySQL.
Esse repositório é a junção adaptada de dois projetos com fins educacionais entregues no curso.
- Basics: O primeiro projeto são de queries básicas abrangendo pequenas manipulações e filtragens, pequenas inserções, atualizações e deleções de entradas no banco de dados.
- Joins: O segundo projeto trata de uma normalização na 3ª forma de um banco, criação e população de tabelas através de comandos e a prática de queries contendo joins.
O objetivo primário desse projeto foi a introdução desse conteúdo através da prática de queries.
- MySQL Server;
- MySQL WorkBench.
Cada desafio foi elaborado em um arquivo com o nome "desafioX.sql", onde X é o número do desafio.
No MySQL WorkBench ou algum outro client SQL execute o arquivo "northwind.sql" para criar o banco de dados dos desafios do Basics.
A criação do bando de dados do Joins se inicia pelo desafio1.sql que é a normalização na 3ª forma e elaboração da query de criação e população do banco de dados. Caso o usuário queira testar os outros desafios sem realizar a normalização e elaborar query de criação de população do banco, é possível se executar a query presente no "desafio1.sql" que fará a criação de maneira correta do banco.
- Exibir nomes dos produtos da tabela
products. - Exibir dados da tabela
products. - Exibir primary keys da tabela
products. - Contar registros da coluna
product_namena tabelaproducts. - Exibir dados da tabela
productsdo quarto registro ao décimo (sem usarWHEREeORDER BY). - Exibir
product_nameeidda tabelaproductsem ordem alfabética dos nomes. - Exibir 5 maiores ids da tabela
products. - Montar query que retorne 3 colunas: "A", "Trybe", "eh" e com os valores de referência: '5+6', 'de, '2+8'.
- Exibir valores não nulos da coluna
notesda tabelapurchase_orders. - Exibir dados da tabela
purchase_ordersem ordem decrescente, ordenados porcreated_bye em que o valor é maior ou igual a 3 (useidcrescente como critério de desempate). - Exibir dados da coluna
notesda tabelapurchase_ordersem que o valor dePurchase generated based on Orderseja maior ou igual a 30 e menor ou igual a 39. - Exibir
submitted_dateda tabelapurchase_ordersonde asubmitted_dateseja 26 de abril de 2006. - Exibir
supplier_idiguais a 1 ou 3 da tabelapurchase_orders. - Exibir
supplier_idmaiores ou iguais a 1 e menores ou iguais a 3 da tabelapurchase_orders. - Exibir apenas a hora (sem minutos e segundos) da coluna
submitted_datedos registrospurchase_orders, chamando essa coluna desubmitted_hour. - Exibir
submitted_dateentre2006-01-26 00:00:00e2006-03-31 23:59:59da tabelapurchase_orders. - Exibir
idesupplier_idda tabelapurchase_ordersem que osupplier_idseja: 1, 3, 5 ou 7. - Exibir registros de
purchase_ordersem que osupplier_idseja igual a 3 e ostatus_idseja igual a 2. - Exibir quantidade de pedidos da tabela
ordersfeitos peloemployee_id5 ou 6 e que foram enviados peloshipper_id2. (Nomeie a coluna de resultado comoorders_count). - Adicionar um registro:
order_id: 69,product_id: 80,quantity: 15.0000,unit_price: 15.0000,discount: 0,status_id: 2,date_allocated: NULL,purchase_order_id: NULL einventory_id: 129, na tabelaorder_details(iddeve ser incrementado automaticamente). - Em uma única query faça duas inserções iguais com os dados da query anterior.
- Atualizar dados de
discountdoorder_detailspara 15. - Atualizar dados de
discountdoorder_details para 30, ondeunit_price` seja menor que 100000. - Atualizar os dados da coluna
discountda tabelaorder_detailspara 45, onde o valor deunit_priceseja maior que 100000 e oidseja entre 30 e 40. - Deletar todas as entradas em que
unit_pricedeorder_detailsseja menor que 100000. - Deletar todas as entradas em que
unit_pricedeorder_detailsseja maior que 100000. - Deletar todos os dados de
order_details.
- Normalizar a tabela da planilha SpotifyClone-Non-NormalizedTable.ods com a 3ª forma de normalização e criar uma query para criar a tabela e popula-la.
- Elaborar uma query que exiba 3 colunas:
- A primeira coluna deve ter o nome
cancoese exibir a quantidade de total de canções; - A segunda coluna deve ter o nome
artistase exibir a quantidade total de artistas; - A terceira coluna deve ter o nome
albunse exibir a quantidade total de álbuns.
- A primeira coluna deve ter o nome
- Elaborar uma query que exiba 3 colunas agrupando por nome de usuário em ordem alfabética apresentando as seguintes colunas:
- A primeira coluna deve ter o nome
usuarioe possuir o nome do usuário; - A segunda coluna deve ter o nome
qtde_musicas_ouvidase exibir a quantidade de músicas ouvidas pelo usuário com base no histórico de reprodução; - A terceira coluna deve ter o nome
total_minutose exibir a soma dos minutos ouvidos pelo usuário com base no histórico de reprodução.
- A primeira coluna deve ter o nome
- Elaborar uma query que exiba 2 colunas referentes aos usuários (em ordem alfabética) relacionando os usuários com a sua atividade/inatividade no ano de 2021 baseado na data mais recente do histórico de reproduções:
- A primeira coluna deve ter o nome
usuarioe exibir o nome do usuário; - A Segunda coluna deve ter o nome
condicao_usuarioe deve exibir se o usuário está ativo ou não;
- A primeira coluna deve ter o nome
- Elaborar uma query com 2 colunas das duas músicas mais tocadas em ordem descrescente de mais tocadas e usando ordem alfabética como critério de desempate:
- A primeira coluna deve ter o nome
cancaoe exibir o nome da canção; - A segunda coluna deve ter o nome
reproducoese exibir quantidade de pessoas que reproduziram aquela música.
- A primeira coluna deve ter o nome
- Elaborar uma query com 4 colunas mostrando dados referentes ao faturamento da empresa (usar duas casas decimais):
- A primeira coluna deve ter o nome
faturamento_minimoe deve mostrar o plano com o menor valor para um usuário; - A segunda coluna deve ter o nome
faturamento_maximoe deve mostrar o plano com o maior valor para um usuário; - A terceira coluna deve ter o nome
faturamento_medioe deve mostrar o valor médio dos planos para um uauário; - A quarta coluna deve ter o nome
faturamento_totale deve exibir o valor total obtidos com a venda dos planos para todos os usuários.
- A primeira coluna deve ter o nome
- Elaborar uma query com 3 colunas que relacione os álbuns produzidos por cada artista, com a quantidade de seguidores que ele possui e deve ser ordenado em ordem decrescente de seguidores (como critério de desempate usar o nome do artista em ordem alfabética e, caso haja novo empate, usar ordem alfabética do álbum):
- A primeira coluna deve ter o nome
artistae deve exibir o nome do artista; - A segunda coluna deve ter o nome
albume deve exibir o nome do album; - A terceira coluna deve ter o nome
seguidorese deve exibir a quantidade de usuários seguidores do artista.
- A primeira coluna deve ter o nome
- Elaborar uma query com duas colunas exibindo os álbuns(em ordem alfabética) que o artista "Walter Phoenix" produziu:
- A primeira coluna deve ter o nome
artistae exibir o nome do artista; - a segunda coluna deve ter o nome
albume deve exibir o nome do album;
- A primeira coluna deve ter o nome
- Elaborar uma query que exiba a quantidade de músicas presentes no histórico de reprodução do usuário
Bille que tenha como nome da colunaquantidade_musicas_no_historico. - Elaborar uma query com duas colunas que exiba o nome(em ordem alfabética) e a quantidade de vezes que cada canção foi tocada por usuários que possuem o plano gratuito ou pessoal:
* A primeira coluna deve ter o nome
nomee exibir o nome da música; * A segunda coluna deve ter o nomereproducoese exibir a quantidade de pessoas que já escutaram aquela música segundo o histórico de reproduções. - Elaborar uma query que altere o nome de algumas músicas e as ordene em ordem alfabética se baseando nos seguintes critérios:
* O nome da música em seu estado normal com o alias
nome_musica* O nome da música atualizado com o aliasnovo_nome
Critérios
- Trocar a palavra "Streets" no final do nome de uma música por "Code Review"
- Trocar a palavra "Her Own" no final do nome de uma música por "Trybe"
- Trocar a palavra "Inner Fire" no final do nome de uma música por "Project"
- Trocar a palavra "Silly" no final do nome de uma música por "Nice"
- Trocar a palavra "Circus" no final do nome de uma música por "Pull Request"
- MySQL Server
- MySQL WorkBench (recomendado)
No terminal:
git clone git@github.com:IgorMarinhoArgollo/MySQL-Basics.git
Execute as queries de criação do banco e depois executar as queries que solucionam os desafios através do MySQL WorkBench ou outro cliente MySQL.
- Faça um fork do projeto;
- Crie uma nova branch com as suas alterações:
git checkout -b my-feature; - Salve as alterações e crie uma mensagem de commit contando o que você fez:
git commit -m "feature: My new feature"; - Envie as suas alterações:
git push origin my-feature; - Abra o seu pull-request na página do GitHub.
Igor Marinho Argollo
These were the first projects of the backend module of the Full Stack Web Developer course at Trybe using relational databases - MySQL.
This repository is a combination of two educational projects delivered in the course.
- Basics: The first project is for basic queries covering small manipulations and filtering, small insertions, updates and deletions of entries in the database.
- Joins: The second project deals with a normalization in the 3rd form of a database, creation and population of tables through queries and the practice of queries containing joins.
The primary objective of this project was the introduction of this content through the practice of queries.
- MySQL Server;
- MySQL WorkBench (recommended).
Each challenge was created in a file named "challengeX.sql", where X is the challenge number.
In MySQL WorkBench or some other SQL client run the file "northwind.sql" to create the Basics challenges database.
The creation of the Joins database starts with the challenge1.sql which is the normalization in the 3rd form and elaboration of the database creation and population query. If the user wants to test the other challenges without performing the normalization and creating a query to create the database population, it is possible to execute the query present in "challenge1.sql" which will correctly create the database.
- Display product names from the
productstable. - Display data from the
productstable. - Display primary keys from the
productstable. - Count records from column
product_namein tableproducts. - Display data from the
productstable from the 4th record to the 10th (without usingWHEREandORDER BY). - Display
product_nameandidfrom theproductstable in alphabetical order of names. - Display top 5 ids from
productstable. - Build a query that returns 3 columns: "A", "Trybe", "eh" and with reference values: '5+6', 'de, '2+8'.
- Display not null values from the
notescolumn of thepurchase_orderstable. - Display data from table
purchase_ordersin descending order, sorted bycreated_byand where the value is greater than or equal to 3 (useridincreasing as tiebreaker). - Display data from the
notescolumn of thepurchase_orderstable where the value ofPurchase generated based on Orderis greater than or equal to 30 and less than or equal to 39. - Display
submitted_datefrompurchase_orderstable wheresubmitted_dateis April 26, 2006. - Display
supplier_idequal to 1 or 3 frompurchase_orderstable. - Display
supplier_idgreater than or equal to 1 and less than or equal to 3 from thepurchase_orderstable. - Display only the hour (without minutes and seconds) of the
submitted_datecolumn of thepurchase_ordersrecords, naming the column assubmitted_hour. - Display
submitted_datebetween2006-01-26 00:00:00and2006-03-31 23:59:59from thepurchase_orderstable. - Display
idandsupplier_idfrompurchase_orderstable wheresupplier_idis: 1, 3, 5 or 7. - Display
purchase_ordersrecords wheresupplier_idequals 3 andstatus_idequals 2. - Display the number of orders from the
orderstable placed byemployee_idnumber 5 or 6 and that were shipped byshipper_idnumber 2. (Name the result column asorders_count). - Add a record:
order_id: 69,product_id: 80,quantity: 15,0000,unit_price: 15,0000,discount: 0,status_id: 2,date_allocated: NULL,purchase_order_id: NULL andinventory_id: 129, in theorder_detailstable (idshould be auto-incremented). - In a single query make two equal insertions with the data from the previous query.
- Update
discountdata fromorder_detailsto 15. - Update
discountdata fromorder_details to 30, whereunit_price` is less than 100000. - Update the data in the
discountcolumn of theorder_detailstable to 45, where theunit_pricevalue is greater than 100000 and theidis between 30 and 40. - Delete all entries where
unit_priceoforder_detailsis less than 100000. - Delete all entries where
unit_priceoforder_detailsis greater than 100000. - Delete all data from
order_details.
- Normalize the SpotifyClone-Non-NormalizedTable.ods spreadsheet table with the 3rd normal form and create a query to create the table and populate it.
- Create a query that displays 3 columns:
- The first column should be named as
cancoesand display the total amount of songs; - The second column should be named as
artistasand display the total number of artists; - The third column should be named as
albunsand display the total number of albums.
- The first column should be named as
- Create a query that displays 3 columns grouped by user name in alphabetical order with the following columns:
- The first column must have the name
usuarioand have the username; - The second column should have the name
qtde_musicas_ouvidaand display the number of songs listened to by the user based on the playback history; - The third column should be named as
total_minutosand display the sum of minutes heard by the user based on the playback history.
- The first column must have the name
- Create a query that displays 2 columns referring to users (in alphabetical order) relating users to their activity/inactivity in the year 2021 based on the most recent date in the reproduction history:
- The first column should be named as
usuarioand display the username; - The second column must have the name
consicao_usuarioand must display if the user is active or not;
- The first column should be named as
- Develop a query with 2 columns of the two most played songs in descending order of most played and using alphabetical order as a tiebreaker:
- The first column should be named as
cancaoand display the name of the song; - The second column should have the name
reproducoesand display the number of people who played that song.
- The first column should be named as
- Create a query with 4 columns showing data regarding the company's revenue (use two decimal places):
- The first column should be named as
faturamento_minimoand should show the plan with the lowest value for a user; - The second column should be named as
faturamento_maximoand should show the plan with the highest value for a user; - The third column must have the name
faturamento_medioand must show the average value of the plans for a user; - The fourth column must have the name
faturamento_totaland must display the total amount obtained from the sale of plans for all users.
- The first column should be named as
- Create a query with 3 columns that lists the albums produced by each artist, with the amount of followers he has and must be ordered in descending order of followers (as a tie-breaking criterion, use the artist's name in alphabetical order and, if there is a new one tie, use alphabetical album order):
- The first column should be named as
artistaand should display the artist's name; - The second column should be named as
albumand should display the name of the album; - The third column should be named as
seguidoresand should display the number of users following the artist.
- The first column should be named as
- Create a query with two columns showing the albums (in alphabetical order) that the artist "Walter Phoenix" produced:
- The first column must be named as
artistaand display the artist's name; - the second column should be named as
albumand should display the name of the album;
- The first column must be named as
- Create a query that displays the number of songs present in the playback history of the user
Billand that has the column namequantidade_musicas_no_historico. - Create a two-column query that displays the name (in alphabetical order) and the number of times each song has been played by users who have the 'gratis' or 'plano pessoal':
* The first column should be named as
nameand display the name of the song; * The second column should have the namereproducoesand display the number of people who have already listened to that song according to the playback history. - Create a query that changes the name of some songs and sorts them in alphabetical order based on the following criteria:
* The name of the song in its normal state with the alias
nome_musica* The song name updated with the aliasnovo_nome
Criteria
- Change the word "Streets" at the end of a song name to "Code Review"
- Change the word "Her Own" at the end of a song name to "Trybe"
- Change the word "Inner Fire" at the end of a song name to "Project"
- Change the word "Silly" at the end of a song name to "Nice"
- Change the word "Circus" at the end of a song name to "Pull Request"
- MySQL Server
- MySQL WorkBench (recomendado)
On terminal:
git clone git@github.com:IgorMarinhoArgollo/MySQL-Basics.git
Run the queries to create the database and then run the queries that solve the challenges through MySQL WorkBench or another MySQL client.
- Make a fork of the project;
- Create a new branch with your changes:
git checkout -b my-feature; - Save your changes and create a commit message explaining what you have done:
git commit -m "feature: My new feature"; - Send your changes:
git push origin my-feature; - Open your pull-request on GitHub.
Igor Marinho Argollo