Curso MySQL #04 - Melhorando a Estrutura do Banco de Dados

Curso MySQL #04 - Melhorando a Estrutura do Banco de Dados

Introduction to the Database Course

In this section, Gustavo Guanabara introduces himself as the teacher of the database course and explains that the focus of this class is to improve the structure of the previously created database.

Improving the Structure of the Database

  • The goal is to redo the structure in a better way by using commands like Alter Table to change the structure of an existing table.
  • The previous database will be deleted and recreated to solve issues with duplicate entries.
  • Primary Keys will be used to solve problems with multiple entries for a single person.

Introduction to Godfrey's Family Example

  • Recap of Godfrey's characteristics (name, age, sex, weight, height, nationality) from the previous lesson.
  • All family members share these characteristics.
  • The need for a container (database) to store their information.

Evolving in Database Study

  • Recap of previous lessons on creating databases and tables using basic commands.
  • Plan to create a more complex database with multiple tables and relationships.

Improving CREATE DATABASE Command

  • Introducing data formats by specifying them during database creation.
  • Comparison with HTML course where data formats were specified in HTML tags.
  • UTF-8 format for handling special characters and accents in different languages.

Deleting and Recreating the Database

In this section, Gustavo demonstrates how to delete and recreate a database using MySQL Workbench. He also introduces new parameters for CONSTRAINTS during database creation.

Deleting Previous Database

  • Open MySQL Workbench and WampServer environment.
  • Click on "Create a new SQL File" button.

DROP DATABASE register;

  • Execute DROP command to delete the "Register" database.

Recreating Database with Constraints

  • Modify the CREATE DATABASE command to include CONSTRAINTS.

CREATE DATABASE register

DEFAULT CHARACTER SET utf8

DEFAULT COLLATE utf8_general_ci;

  • Use DEFAULT CHARACTER SET to specify data format (UTF-8).
  • Use DEFAULT COLLATE to define character collection.

Conclusion

In this section, Gustavo concludes the lesson by summarizing the changes made to the CREATE DATABASE command and emphasizing the importance of following all steps in setting up the environment.

Recap of Changes Made

  • Modified CREATE DATABASE command with CONSTRAINTS for data format and character collection.
  • Lowercase letters for parameters and names.

Importance of Following Steps

  • Reminder to follow all steps in setting up the environment.
  • Highlighting the simplicity of creating and deleting databases using MySQL commands.

Timestamps are approximate and may not match exactly with the provided transcript.

Setting Default Collation

In this section, the speaker explains how to set the default collation for a database.

Setting Default Collation

  • The default collation for a database can be set using the command default collate utf8_general_ci.
  • This command ensures that all characters in the database are encoded in UTF8.
  • To execute the command, press Ctrl + Enter or click on the button for command execution.

Creating and Updating Databases

This section covers creating and updating databases.

Creating a Database

  • To create a database, use the command create database MYDATABASE.GDB;.
  • Press Ctrl + Enter to execute the command.
  • The last line of output indicates if the database was created successfully.

Updating Schema

  • After creating a database, it is important to update its schema.
  • Click on "Information" to view registration details of the created database.

Database Information

  • The registration information shows that the default collation is UTF8.
  • The character set for the environment may differ from the default setting.

Deleting a Database

  • To delete a database, use the command drop datebase MYDATABASE.GDB;.
  • Press Ctrl + Enter to execute the command.

Optimizing Table Structure

This section focuses on optimizing table structure by using appropriate data types and constraints.

Primitive Types and Optimization

  • It is important to optimize table structures by choosing appropriate data types.
  • Instead of using int, consider using tinyint to save disk space.
  • For example, an int occupies 11 bytes while a tinyint occupies only 3 bytes per record.

Improving Field Types

  • Consider improving field types such as changing float to decimal for real numbers.
  • Decimal type allows for more customization.
  • Instead of storing age, store the birth date to calculate age dynamically.
  • This avoids the need to constantly update age as time passes.

Working with Enumerations

  • Use enum data type for fields like sex to restrict values to a predefined set.
  • For example, use enum('M', 'F') to only accept 'M' or 'F' as valid values.

Registering Birth Date and Sex

This section explains the decision to register birth dates instead of ages and working with sex as an enumeration.

Birth Date Registration

  • Instead of registering age, it is better to register the day of birth.
  • By calculating age based on the birth date, it eliminates the need for constant updates.

Working with Sex Enumeration

  • Instead of using a single character field for sex, use an enumeration type.
  • An enum field can be defined as enum('M', 'F') to only accept 'M' or 'F' as valid values.

Relação entre tabelas e criação de banco de dados

Nesta seção, o instrutor fala sobre a relação entre tabelas e a criação de um banco de dados. Ele destaca a importância da paciência ao trabalhar com bancos de dados e explica como usar o comando CREATE DATABASE para criar um novo banco.

Relação entre tabelas

  • A relação entre tabelas é discutida, com três elementos antes da vírgula e dois após.
  • É enfatizada a necessidade de paciência ao lidar com bancos de dados.

Criação do banco de dados

  • O comando CREATE DATABASE é introduzido como uma forma de criar um novo banco.
  • Explica-se que um banco de dados contém palavras, nomes e números.
  • O formato UTF-8 é mencionado como sendo adequado para caracteres especiais, incluindo acentuações em português.
  • Instruções são dadas sobre como abrir o ambiente necessário (WampServer e MySQL Workbench) para executar os comandos.
  • É ressaltada a importância de configurar corretamente o conjunto de caracteres (UTF-8) e COLLATION (utf8_general_ci).
  • Exemplos práticos são fornecidos para demonstrar como criar e apagar bancos de dados usando os comandos DROP DATABASE e CREATE DATABASE.

HTML, PHP e empregabilidade

Nesta seção, o instrutor menciona a importância do estudo do HTML em conjunto com algoritmos em PHP. Ele também destaca que muitas pessoas têm conseguido empregos graças aos conhecimentos adquiridos nesses cursos.

Estudo do HTML e PHP

  • É mencionado que é possível fazer um curso de HTML e aprender a combinar algoritmos com PHP.
  • Destaca-se que muitas pessoas têm se beneficiado desses conhecimentos e estão conseguindo empregos.

Formatação de caracteres acentuados

Nesta seção, o instrutor aborda a formatação de caracteres acentuados em bancos de dados. Ele explica que o formato UTF-8 é adequado para caracteres especiais, incluindo acentuações em português.

Formatação de caracteres

  • É explicado que os bancos de dados devem ser configurados para lidar corretamente com caracteres acentuados.
  • O formato UTF-8 é mencionado como sendo capaz de lidar com caracteres especiais, incluindo acentuações em português.

Preparação do ambiente e criação do banco de dados

Nesta seção, o instrutor fala sobre a preparação do ambiente necessário para trabalhar com bancos de dados. Ele demonstra como abrir o WampServer e o MySQL Workbench, além de mostrar como criar um novo banco usando o comando CREATE DATABASE.

Preparação do ambiente

  • Instruções são dadas sobre como abrir o WampServer e o MySQL Workbench.
  • É enfatizado que é importante ter esses ambientes configurados corretamente antes de prosseguir.

Criação do banco de dados

  • O comando CREATE DATABASE é utilizado para criar um novo banco.
  • É ressaltada a importância do ponto-e-vírgula (;) ao finalizar os comandos no MySQL.
  • Exemplos práticos são fornecidos para demonstrar como criar e apagar bancos de dados.

Configuração do banco de dados

Nesta seção, o instrutor aborda a configuração do banco de dados. Ele explica que o comando CREATE DATABASE deve ser seguido por parâmetros e destaca a importância do ponto-e-vírgula (;) para finalizar os comandos.

Configuração do banco de dados

  • É explicado que o comando CREATE DATABASE pode ser seguido por parâmetros.
  • A importância do ponto-e-vírgula (;) é destacada como indicador de finalização dos comandos no MySQL.

Diferença entre Collation em bancos de dados

Nesta seção, o instrutor fala sobre a diferença entre Collation em bancos de dados. Ele demonstra como diferentes configurações podem afetar a codificação de caracteres.

Diferença entre Collation

  • É mostrado um exemplo prático comparando dois bancos de dados com diferentes configurações de Collation.
  • A importância da correta configuração do Collation é ressaltada para garantir a codificação adequada dos caracteres.

Criação inteligente da estrutura da tabela

Nesta seção, o instrutor fala sobre a criação inteligente da estrutura da tabela. Ele menciona a importância de utilizar tipos primitivos bem dimensionados ao projetar tabelas em um banco de dados.

Criação inteligente da estrutura da tabela

  • É enfatizada a importância de utilizar tipos primitivos bem dimensionados ao projetar tabelas em um banco.
  • Exemplos práticos são fornecidos para demonstrar como criar uma estrutura de tabela mais eficiente.

Understanding Field Definitions

In this section, the instructor explains how to define fields in a database table.

Defining Gender Field

  • The gender field should be defined as either "M" or "F", in uppercase and within single quotes.
  • It is not recommended to accept lowercase values for gender.

Defining Weight and Height Fields

  • The weight field should be defined as decimal(5,2), allowing for a decimal number with 5 digits in total and 2 decimal places.
  • The height field should be defined as decimal(3,2), allowing for a decimal number with 3 digits in total and 2 decimal places.

Defining Nationality Field

  • The nationality field can be defined as varchar(20) with a default value of 'Brasil'.
  • It is important to maintain accurate information by specifying the default value.

Using Backticks for Field Names

  • Field names should be enclosed in backticks (`) to allow for special characters or spaces.
  • This allows for fields with accents or spaces, although it is not recommended.

Executing Commands and Selecting Database

This section covers executing commands and selecting the appropriate database before execution.

Selecting Database

  • Use the USE command followed by the database name or double-click on the desired database from the list.
  • Ensure that the correct database is selected before executing commands.

Adding Additional Commands

  • Before pressing CTRL+ENTER to execute a command, ensure that all necessary parts of the command have been added.
  • Add any additional constraints or modifications before executing the command.

Understanding Primary Keys and Unique Identifiers

This section explains primary keys and their importance in database tables.

Importance of Primary Keys

  • In a table, it is important to define at least one field as a primary key.
  • A primary key ensures that each record has a unique identifier and prevents duplicates.

Choosing a Primary Key Field

  • Fields like name, nationality, gender, age, etc., cannot be used as primary keys since they can have duplicate values.
  • Create a new field called ID as an integer with the constraint NOT NULL to serve as the primary key.

Using Auto Increment for Primary Key

  • Use the AUTO_INCREMENT constraint for the ID field to automatically assign incremental values.
  • The first record will have an ID of 1, the second record will have an ID of 2, and so on.

Executing Commands and Checking Table Schema

This section covers executing commands and checking if the table schema was created successfully.

Executing Commands

  • To execute a command, ensure that the desired database is open and place the cursor anywhere within the command.
  • Press CTRL+ENTER to execute the command.

Checking Table Schema

  • After executing commands, check if the table schema was created successfully by refreshing or updating the view.
  • Verify that all columns are correctly defined and organized.

Curso em Video

This section discusses the eternal nature of the video course.

Eternal Nature of the Video Course

  • The video course is designed to be everlasting and accessible at any time.
  • It provides a timeless learning experience that can be accessed repeatedly.
  • The course content remains relevant and valuable over an extended period.
  • Students can revisit the course materials whenever they need to refresh their knowledge or learn new concepts.

Timestamp provided is 0:22:19 (1339 seconds).

Video description

Veja como otimizar a estrutura da sua tabela usando comandos CREATE DATABASE e CREATE TABLE com suporte à acentuação de caracteres no MySQL. Nessa aula, vamos melhorar ainda mais os comandos que vimos na aula anterior. Nós do CursoemVideo sempre recomendamos assistir a aula completa, mas se quiser aprender diretamente uma parte específica, clique nos marcadores de tempo a seguir: 0:28 - O que veremos nessa aula? 3:39 - Apagando um banco com DROP DATABASE 5:14 - Melhorando seu CREATE DATABASE para aceitar acentos no MySQL 8:23 - Melhorando seu CREATE TABLE 17:25 - Explicando Chave Primária (PRIMARY KEY) 21:44 - Pronunciamento importante 23:22 - Criando um Banco MySQL em um servidor online profissional 25:48 - Ajuda a gente, vai? Aula do Curso de Banco de Dados com MySQL criado pelo professor Gustavo Guanabara para o portal CursoemVideo.com. Curso em Vídeo Site: http://www.cursoemvideo.com YouTube: http://www.youtube.com/cursoemvideo Facebook: http://www.facebook.com/cursosemvideo Twitter: http://twitter.com/cursosemvideo Google+: http://plus.google.com/112666558837414979080 Patrocínio HOSTNET: http://www.hostnet.com.br Trilha sonora da abertura: African Drums (Sting) de Twin Musicom está licenciada sob uma licença Creative Commons Attribution (https://creativecommons.org/licenses/by/4.0/) Artista: http://www.twinmusicom.org/