Este é um post de José Lopes.
Este post serve para explicar um pouco o que é afinal uma base de dados relaccional e alguma
terminologia que lhe está associada. É interessante ter uma ideia deste tipo de base de dados e
do seu sistema de gestão para posteriormente compreender melhor o processo de design (que irei
tratar noutro post).
Posted by José Lopes.
This post goal is to explain in general what is a relational database and some associated
terminology. Its useful to have an idea about this type of database and its management system
to understand better the process of database design (to be treated in another post)
A base de dados relaccional é presentemente a mais utilizada no mundo das bases de dados.
Tal supremacia deve-se, entre outros factores, à:
- forte acção de marketing das empresas comerciais existentes;
- sua relativa fiabilidade (funcionam bem a maior parte do tempo);
- disponibilização de uma boa linguagem de query;
- utilização de um estilo mais declarativo e menos processual, o que permite que nos
concentremos no que queremos e não no como o devemos fazer;
- utilização de optimizadores de pesquisas (queries) que decidem a melhor forma de a levar a
cabo. Isto é interno ao sistema de gestão (RDBMS), não é acessível pelo utilizador e permite uma
maior rapidez nos resultados.
Este tipo de base de dados usa como o nome indica o modelo relaccional. Este modelo é um modelo
matemático, cujo nome significa tabelas e não relacções como poderia dar a entender. Isto é uma
confusão comum.
O relaccional implica uma colecção ordenada de n-coisas (n-tuples).
Exemplificando este tipo de colecções:
- Associando pares de coisas: Europa, Portugal; América do Sul, Brasil
- Se forem triplos de coisas: Europa, Portugal, Euro; América do Sul, Brasil, Real
- E é claro que podemos extender até n-coisas.
Se escrevermos estas n-coisas uma sobre outra obtemos algo que se parece com uma tabela:
| Europa |
Portugal |
Euro |
| América do Sul |
Brasil |
Real |
Esta é a imagem conceptual deste tipo de base de dados. Podemos dizer que num modelo relaccional
a informação é expressada utilizando somente tabelas e todas as operações que possamos fazer
produzem outras tabelas.
Vamos definir alguma terminologia antes de avançarmos mais.
- A tabela representa uma entidade.
- As linhas representam instantes individuais da entidade.
- A tabela tem colunas com nomes que representam as propriedades da entidade, a
que chamamos atributos.
- Os valores numa coluna representam o estado de um instante da
entidade.
- Estes valores são de um determinado tipo que chamamos de domínio, que representa
todos os valores teoricamente possiveis.
Esquematizando:
A utilização de tabelas permite uma elevada uniformidade do modelo, pois como podemos ver no
esquema anterior, os valores nas linhas representam uma única associação, ou por outras palavras,
representam valores individuais ou estado da entidade e nada mais do que dessa entidade (podemos
considerar como um acontecimento da entidade com certos valores), enquanto os valores nas colunas
restringem-se a um determinado domínio (como as Regiões).
O termo 'imagem conceptual' vem da teoria implicita no modelo relaccional que, do seu pedestal
teórico, considera não haver colunas especiais nem mecanismos de ponteiros para associar
informação. Isto não podia estar mais longe da realidade.
Embora o mentor deste modelo, Edgar F. Codd, tenha redigido as que ficaram conhecidas como as
12 Regras de Codd (link em
Inglês) para definir os requesitos necessários para um produto ser considerado como uma base de
dados relaccional, verdade seja dita que nenhum produto existente as preenche na totalidade.
Isto poderá ser devido a alguma subjectividade no texto destas regras mas é de certeza devido
aos criadores dos produtos utilizarem mecanismos de optimização (os tais optimizadores) visando a
performance. Isto vai ao ponto de criarem tabelas de indexação internas ao sistema de gestão e à
utilização de colunas especiais nas tabelas de informação, recorrendo a chaves primárias
e a chaves externas, que não existem na imagem conceptual.
É neste contexto que surgem as chaves primárias (primary keys) e as chaves externas (foreign
keys). Qualquer sistema de gestão de base de dados faz um uso extensivo destes dois conceitos.
Uma chave primária não é mais do que os valores de uma certa coluna da tabela que asseguram que
não haja duas linhas impossíveis de distinguir, ou seja, esses valores têm obrigatoriamente de ser
únicos. A chave primária é aquilo que identifica um registo na tabela garantindo a sua unicidade.
Não se trata de uma questão de repetição do registo na tabela. A função
principal deste tipo de chaves é garantir a consistência da base de dados, por modo a que o
sistema de gestão não fique bloqueado por não conseguir distinguir os registos, daí a unicidade.
Normalmente, por uma questão de lógica visual, a primeira coluna de uma tabela é composta por
chaves primárias. Claro que isto não é obrigatório pois podemos definir qualquer coluna para o
efeito, é mais por uma questão de leitura lógica.
Os sistemas de gestão (DBMS) utilizam internamente uma indexação, para mecanismos internos de
optimização e consolidação, adicionando uma coluna extra no início de cada tabela. Isto contudo não
é uma chave primária, é algo interno que o utilizador não controla nem vê.
Fazendo um pequeno à parte e tomando o exemplo de um sistema Oracle, podemos fazer uso desta
indexação (através de um comando PL/SQL) para obter resultados muito mais rápidos uma vez que
recuperamos os registos de uma forma directa sem o recurso a nenhum método associativo. A Oracle
utiliza um número com um tamanho definido para a indexação.
Na minha opinião não aconselho o uso desta técnica por duas razões principais:
- É muito abstrato e torna difícil a leitura de código e o seu eventual debug.
- Como é propriedade da Oracle, no caso de alteração do tamanho deste números entre
versões, o que já aconteceu no passado, o código vai deixar de funcionar.
Fechando este à parte, não é demais de mencionar a importância de uma escolha correcta da
chave primária para uma boa consistência da base de dados. Irei voltar a escrever sobre as chaves
primárias e como as escolher no post que se seguirá sobre o processo de design de uma base de
dados.
As chaves externas são valores numa coluna da tabela que representam uma relacção desta tabela
com outra. Com um pequeno esquema compreende-se logo:
Na coluna tipo da tabela vinhos temos chaves externas, ou seja, os valores que temos nesta
coluna vêm da tabela tipos. Isto é definido quando se constrói a base de dados, limitando os
valores possíveis para a coluna tipo da tabela vinhos aos existentes na tabela tipos.
Como podemos observar não existe nenhum constrangimento de unicidade, podemos ter a mesma chave
externa várias vezes na tabela vinhos. Atenção que na tabela tipos a coluna existente é constituída
por chaves primárias.
Para concluir, este conceito de chaves e tabelas vai ser importante no que diz respeito à
normalização da base de dados, sendo outro ponto inerente ao design da base de dados.
The relational database is currently the most used in the database world.
This is due, among other thing, to:
- the strong marketing from the existing companies that provide them;
- their relative reliability (they work fine most of the time);
- a good query language;
- the use of a more declarative and less procedural style, allowing us to concentrate in
what we want and not how it must be done;
- the use queries optimizers that decide internally the best way to handle the processes.
This is internal to the management system (RDBMS) and not accessible to the user. It allows an
increase of speed performance.
This type of database use the relational model. This is a mathematical model where the term
relation represent a table and not a relationship. This is a very commom misunderstanding.
The relation is to be regarded as a collection of ordered n-thing (normally referred
as n-tuples).
An example of such collections can be:
- Associating pair of things: Europe, Portugal; South America, Brasil
- Associating triples of things: Europe, Portugal, Euro; South America, Brazil, Real
- And of course we can extend to n-things.
If we write these n-thing on top of each others we will get something resembling a table:
| Europe |
Portugal |
Euro |
| South America |
Brazil |
Real |
This is the conceptual image of databases following the relational model. We can even say that
the information in the relational model is laid out using only tables and all the operation we may
carry out result in other tables.
Lets define some terminology before moving forward.
- The table represents an entity.
- The lines represent individual instances of the entity.
- The table has columns with headers that represent the entity properties, that we
call attributes.
- The values in a column represent the state of an entity instance.
- These values are from a certain type that belong to a domain, domain that
represents all the teorically possible values.
Drawing it to a diagram:
The use of tables allows a high uniformity of the model because, like we can see in the
diagram, the values on the lines represent an unique association, in other words, they represent
the entity individual values or states and nothing other than the entity (we can see it as an
instance of the entity that records specific values), while the values on the columns are
limited to a specific domain (like the Regions).
The 'conceptual image' term comes with the theory implicit on the relational model that,
from its theorical world, states that there should not exist special columns neither pointer
mechanisms to associate information. This could not be more distant to the reality.
Though this model mentor, Edgar F. Codd, had wroten what become known as the
Codd's 12 Rules to define
the necessary requirements that a product ought to match to be considered as a relational
database product, the truth is that none of the existing product meet them in full.
This could be due to some subjectivity on the text rules, but for sure is due to the
products using optimization mechanisms (the optimizers mentioned before) that aim the performance.
This goes to the point that indexation tables are created within the management system and
special coulmns are indead used on the real tables, making use of primary keys and foreign keys,
that do not exist in the conceptual image.
We then have to become aware of the primary keys and the foreign keys. Any database management system uses extensively these two concepts.
A primary key is nothing more than the values of a given column that assure that is always
possible to distinguish the rows, i.e., is mandatory that these values are unique. The primary
key is what identifies a record in the table assuring its unicity.
This is not a question of record repetition on the table. The main function of the primary
key is to assure the database consistency, so that the management system doesn't froze because
its not able to distinguish between two records, that is the reason of the unicity.
Usually, just to keep a visual logic, the first column of a table stores the primary keys.
Of course that this is not mandatory and we can set any other column for that, this is more
to keep a logical reading.
The management systems (DBMS) use internally the indexation, for internal optimization and
consolidation mechanisms, adding an extra column at the begging of each table. This is not a
primary key, is internal to the systen and the user doesn't see it neither controls it.
Allow me to make a small break and take as example an Oracle system. With Oracle we
can use this indexation (through a PL/SQL statment) to retrieve data faster since with it
we retrieve the record directly without any association method. Oracle uses a number with a
defined size for the indexation.
I really don't advice the use of this technique and I invoke two reasons:
- Its very abstract and makes difficult to read the code and debug if necessary.
- Since its owned by Oracle, if they change the numbers size between versions, it already
happedn in the past, the code stops working.
Ending the break, its very important to properly choose the primary key to have a good
database consistency. I will mention again the primary keys and how to choose them in the
post about the database design process.
The foreign keys are values in a column that represent the relationship between that
table and another one. With the following diagram the concept is easy:
In the column type of the wines table we have foreign keys, i.e., the values on the
column come from the table types. This is set when building the database, limiting the possible
values to the type column of the table wines to the ones existing in the table types.
We can observe that there is no uniqueness constraint for this kind of keys, we can have the
same foreign key several times in the wine table. Notice, on the other hand, that the column
on the types table is made of primary keys.
In conclusion, the keys and tables concept will be important when normalizing the databse.
This point will also be treated in the post about the database design process.