Home

The Structure of a Database Table

 

A Review of Tables

 

Introduction

Tables are the foundation of organizing lists of items. This concept is valid regardless of the type of list. As a database application is primarily a list of things, the SQL also uses the same approach to organize information.

Before creating a table, you must specify what database it would belong to. You can use one of either the Northwind or the pubs databases that ship with Microsoft SQL Server or you can use one of your own.

Practical Learning Practical Learning: Introducing Tables

  1. Start Microsoft Access and create a Blank Database named Countries1 in your Microsoft Access Database Development folder
  2. Start Microsoft Visual Basic .NET or Visual Studio .NET and create a new Windows Application named Countries1
  3. Right click the form and click View Code
  4. In the top section of the file, under the other using namespace lines, type:
     
    Imports System.Data.OleDb
    
    Public Class Form1
        Inherits System.Windows.Forms.Form

Table Creation

The statement used to create a new table uses the following formula:

CREATE TABLE TableName

The CREATE and TABLE keywords must be used to let SQL know that you want to create a table. The TableName factor specifies the name of the new table. Because of the flexibility of SQL, it can be difficult to maintain names in a database. Based on this, there are conventions we will use for our objects. In fact, we will adopt the rules used in C/C++, C#, Pascal, Java, and Visual Basic, etc. In our databases:

  • A name will start with either a letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z) or an underscore
  • After the first character, we can use any combination of letters, digits, or underscores
  • A name will not start with two underscores
  • A name will not include one or more empty spaces. That is, a name will be made in one word
  • If the name is a combination of words, at least the second word will start in uppercase. Examples are dateHired, _RealSport, FullName, or DriversLicenseNumber

After specifying the name of the table, you must list the columns of the table. The list of columns starts with an opening parenthesis "(". The list ends with a closing parenthesis ")". Each column must be separated from the next with a comma, except for the last column. You can include all columns on the same line if possible as follows:

CREATE TABLE Country(Column1, Column2, Column3)

Alternatively, to make your statement easier to read, you should create each column on its own line as follows:

CREATE TABLE Country(
Column1,
Column2,
Column3);

There are two primary pieces of information you must specify for each column: its name and its type. Therefore, the syntax of creating a column is:

ColumnName DataType Options

To programmatically create a table, you can follow the same formula rules of creating a table using SQL code. Once the statement is ready, you can pass it to a OleDbCommand object. To execute the statement, you can call the OleDbCommand.ExecuteNonQuery() method.

The Columns of a Table

 

The Name of a Column

Although a table is used to hold information, its data is divided in columns and you must create each column following specific rules. The primary characteristic you must provide for a column is its name. If you are using the Design View of a table, you can type the name of each column under the Field Name section. If you are creating a SQL statement, you can type the name of the first column after the opening parenthesis.

The name of a column should follow the same rules and suggestions we reviewed for the database objects.

 

The Types of Data a Column Can Carry

After specifying the name of a column, the interpreter would need to know the kind of information the column will hold. You must specify the data type that is necessary for a particular column.

If you are using the Design View of a table, you can click the box under Data Type that corresponds to the column. This would convert the text box into a combo box. You can then select from the list of available types.

If you are creating a SQL statement, after typing the name of the column, you must type the appropriate name of the desired data type. Remember that SQL is not case-sensitive but while you can write the data type in any case, you should not overlook the case you use for the names of columns.

To support the data types used in a database, the .NET Framework provides the System.Data.SqlTypes namespace that provides a class for each SQL data type. The names of SQL data types are:

bit: The bit is the smallest data type. It is used for a field that would validate a piece of information as being true or false, On or Off, Yes or No, 1 or 0. This is also the data type you should select if a check box would be used to validate the value of this column. This means that it can be used where the C++' bool or the .NET Framework's System.Boolean data types would be applied. The .NET Framework database equivalent to this data type is the SqlBoolean class.

int: This is the same data type as the C++' int. It is a natural number that would be used if a column would hold numbers in the range of -2,147,483,648 to 2,147,483,647. This is also the same as the System.Int32 we reviewed for the DataTable objects when we studies DataSet tables. The .NET Framework database equivalent to this data type is the SqlInt32 class.

tinyint: This data type can be used for a column that would hold (very) small numbers that range from 0 to 255. It is equivalent to the .NET Framework's System.Byte database. Because C++ doesn't have a byte data type, the tinyint type can be used where a short or rather an unsigned short would be used. You should use this data type only when you know for sure that the values used on this column will be small. When in doubt, you should use int. The .NET Framework database equivalent to this data type is the SqlByte class.

smallint: The smallint data type follows the same rules and principles as the int data type except that it is used to store smaller numbers that would range between -32,768 and 32,767. This means it is equivalent to the C++' short integer or the .NET Framework's System.Int16 type. The .NET Framework database equivalent to this data type is the SqlInt16 class.

bigint: The bigint data type follows the same rules and principles as the int data type except that its field can hold numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. It is somehow equivalent to the C++' long integer but more accurately equivalent to the .NET Framework's System.Int64 data type. As such, you can apply this data type for a column that would hold (very) large numbers. The .NET Framework database equivalent to this data type is the SqlInt64 class.

binary: This data type is used for a column that would hold hexadecimal numbers. Examples of hexadecimal numbers are 0x7238, 0xFA36, or 0xAA48D. Use the binary data type if all entries under the column would have the exact same length (or quantity). If you anticipate that some entries would be different than others, then use the alternative varbinary data type. The varbinary also is used for hexadecimal numbers but allows dissimilar entries, as long as all entries are hexadecimals. The .NET Framework database equivalent to this data type is the SqlBinary class.

numeric and decimal: This data type is used on a column that will hold (either whole or) real numbers, numbers that include a decimal separator (the character used as the decimal separator as set in the Control Panel) between the digits. An example would be 12.125 or 44.80. If you anticipate such a number for a field, specify its data type as numeric or decimal (either decimal or numeric would produce the same effect in SQL Server). This data type is mostly equivalent to the C++' double or the .NET Framework's System.Double data type. The .NET Framework database equivalent to this data type is the SqlDecimal class.

float and real: A floating-point number is a fractional number, like the decimal and numeric types. Floating-point numbers can be used if you would allow the database engine to apply an approximation to the actual number that a field is supposed to carry. This is mostly equivalent to the C++' float or the .NET Framework's System.Single data type. As you may be aware when using float, this data type doesn't offer good precision. The .NET Framework database equivalent to this data type is the SqlDouble class.

money: As its name announces it, the money data type can be used on a column whose data would consist of currency values. A field with a money data type can hold positive or negative values from -922,337,203,685,477.5808 to +922,337,203,685,477.5807

The .NET Framework database equivalent to this data type is the SqlMoney class.

smallmoney: While the money data type can be used for a field that would hold large quantities of currency values, the smallmoney data type can be applied for a column whose value cannot be lower than -214,748.3648 nor higher than 214,748.3647

The .NET Framework database equivalent to this data type is the SqlMoney class.

char: A field of characters can consist of any kinds of alphabetical symbols in any combination, readable or not. If you want a column to hold a fixed number of characters, such as the book shelf numbers of a library, apply the char data type for such a column. This is equivalent to the C++' char and __wchar_t types of the .NET Framework's System.Char data type except that the SQL's char type is suitable if all fields of a column would have the same length. The .NET Framework database equivalent to this data type is the SqlString class.

varchar: Like the string is in C++ and most other languages, the varchar data type is the most common data type of SQL. It represents a string. This means that it can be used on any column whose values you cannot predict. In fact, it is the default data type of any column created in the New Table window of SQL Server Enterprise Manager or the dbo.Table1 window of Visual Studio .NET. Use this data type wherever you would use a String value. The maximum length of text that a field of varchar type can hold is equivalent to 8 kilobytes.  The .NET Framework database equivalent to this data type is the SqlString class.

text: The text data type can be applied to a field whose data would consist of ASCII characters. As opposed to a varchar type of field, a text type of field can hold text that is longer than 8 kilobytes. The .NET Framework database equivalent to this data type is the SqlString class.

nchar, nvarchar, and ntext: These three types follow the same rules as the char, varchar, and text respectively, except that they can be applied to columns that would hold international characters, that is, characters of languages other than US English. This is done following the rules of Unicode formats. The .NET Framework database equivalent to these data types is the SqlString class.

datetime: As its name suggests, a datetime data type is used for a column whose data would consist of date and/or time values. The entries must be valid date or time values but SQL Server allows a lot of flexibility, even to display a date in a non-traditional format. The date value of a datetime field can be comprised between January 1st, 1753 and December 31, 9999. This data type is equivalent to the .NET Framework's DateTime data type. The .NET Framework database equivalent to this data type is the SqlDateTime class.

smalldatetime: The smalldatetime is an alternative to the datetime data type. It follows the same rules and principles as the datetime data type except that a date value must be comprised between January 1st, 1900 and June 6, 2079. This data type is equivalent to the .NET Framework's DateTime data type except that this one's date ranges are smaller. Whenever in doubt, use the datetime type (or the varchar). The .NET Framework database equivalent to this data type is the SqlDateTime class.

 

The Length of Data

One way you can tune your database is to control the amount of text entered in a column's field. As various columns can hold different types of data, so can the same data type control its own mechanism of internal data entry. The length of data means different things to different fields. Columns that carry the same data type can have different lengths.

Most columns use a default length. The only type you should think of changing the length of data is if the column is character (char) or string-based (varchar): You should not touch the others.

To specify the length of a column, if you are using the Design View of a table, you can enter the desired number in the Length box that corresponds to the column.

If you are creating a SQL statement, after typing the name of the type, type the opening parenthesis, followed by the desired number, followed by the closing parenthesis.

The rules of Length columns are:

Bit Fields: We saw already that a bit column type is meant for one of two answers. The user is supposed to simply let the database know that the answer is yes or no, true or false, on or off, 1 or 0. Therefore, the only length of this field is 1.

Integers: The length of an integer is the number of bytes its field can hold. For an int type, that would be 4 bytes.

Decimal and Floating-Point Numbers: The Length specifies how many bytes the field can store.

Strings: The Length of a character or string column specifies the maximum number of characters that the field can hold.

In some circumstances, you will need to change or specify the length as it applies to a particular field. For example, since you should use the varchar data type for a string field whose content will change from one record to another, not all varchar columns need to have the same length. Although a First Name and a Book Title columns should use the varchar type, both columns would not have the same length of entries. As it happens, people hardly have a first name that is beyond 20 characters and many book titles go beyond 32 characters. In this case, both fields would use the same data type but different lengths. On the other hand, for columns of datetime and money data types, you should accept the default length suggested by the database. 

Practical Learning Practical Learning: Creating a Table

  1. Change the design of the form as follows:
     
    Control Name Text
    Button btnCreateContinents Create Continents
    Button btnCreateCountries Create Countries
  2. Double-click the Create Continents button and implement its code as follows:
     
    Private Sub btnCreateContinents_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateContinents.Click
            Dim strCreate As String = "CREATE TABLE Continents(" & _
                                                     "ContinentName varchar(100)," & _
        			 "Area Long," & _
    			 "Population Long);"
    
            Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
               "Data Source=C:\\Microsoft Access Database Development\\Countries1.mdb;")
    	dim cmdDatabase  as  OleDbCommand   = new OleDbCommand(strCreate, conDatabase)
    
            conDatabase.Open()
    
            cmdDatabase.ExecuteNonQuery()
            conDatabase.Close()
    End Sub    
  3. Return to the form and double-click the Create Countries button
  4. Implement its event as follows:
     
    Private Sub btnCreateCountries_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateCountries.Click
            dim strCreate as String  = "CREATE TABLE Countries (" & _
            "CountryName varchar(120)," & _
            "Continent Integer," & _
            "Area Long," & _
            "Population Long," & _
            "Capital varchar(80)," & _
    		"Code char(2));"
    
            Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
              "Data Source=C:\Microsoft Access Database Development\Countries1.mdb;")
            Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)
    
            conDatabase.Open()
    
            cmdDatabase.ExecuteNonQuery()
            conDatabase.Close()
    End Sub
  5. Return to the form and double-click the Close button
  6. Implement its event as follows:
     
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
            End
    End Sub
  7. Execute the application
  8. Click the different buttons to create the tables
  9. Close the form
 

Table Maintenance

 

Deleting a Table

If you have a table you don't need in your database, you can remove it. Before performing this operation, you should make sure you are familiar with the role of the table. For example, if you work in a team environment and you find a table that may have been created by someone else, you should enquire before deleting it.

To delete a table, first locate the database it belongs to. If you are working in Microsoft Access, to delete a table, in the Tables section of the Database window, right-click the undesired table and click Delete.

If you are working in a SQL statement, the code used to delete a table uses the following formula:

DROP TABLE TableName

The DROP TABLE expression is required and it is followed by the name of the table as TableName. Here is an example:

DROP TABLE FriendsOfMine
GO

If you are working from C++ code, create a DROP TABLE TableName; expression and pass it to a OleDbCommand object before calling the OleDbCommand.ExecuteNonQuery() method. Here is an example:

Private Sub btnMaintenance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaintenance.Click
        Dim strDeleteTable As String = "DROP TABLE Countries;"

        Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
          "Data Source=C:\Microsoft Access Database Development\Countries1.mdb;")
        Dim cmdDatabase As OleDbCommand = New OleDbCommand(strDeleteTable, conDatabase)

        conDatabase.Open()

        cmdDatabase.ExecuteNonQuery()
        conDatabase.Close()
End Sub

It is extremely important to know that, when working with the DROP TABLE TableName statement, you would not receive any warning. If you are working in a Windows Forms Application, you should create your own warning in a message box to make sure that the user really want to delete the table.

 

Columns Maintenance

 

Adding a Column

After creating a table or when using any existing table, you may find out that a column is missing. You can add a new column to a table if necessary.

If you are working with SQL code, to create a new column, the formula to use is:

ALTER TABLE TableName ADD NewColumnName DataType Options

When using this statement, the ALTER TABLE expression and the ADD keyword are required. You must specify the name of the table that the new column will belong to. This is done using the TableName factor in our formula. Specify the name of the new column in the NewColumnName placeholder of our formula. On the right side of the NewColumnName placeholder, specify the options in the same way we described for columns.

If you are working from a Windows Forms Application code, create an ALTER TABLE expression and pass it to a OleDbCommand object before executing it. Here is an example:

Private Sub btnMaintenance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaintenance.Click
        Dim strDeleteTable As String = "DROP TABLE Countries;"

 dim conDatabase  as OleDbConnection = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
			 "Data Source=C:\Microsoft Access Database Development\Countries1.mdb;")

        Dim cmdDatabase As OleDbCommand
        cmdDatabase = New OleDbCommand("ALTER TABLE Countries ADD TypeOfGovernment varchar(100);", _
          conDatabase)

        conDatabase.Open()

        cmdDatabase.ExecuteNonQuery()
        conDatabase.Close()
End Sub

Deleting a Column

If you have a column you don't need, you can remove that column from the table. The formula to delete a column is:

ALTER TABLE TableName DROP COLUMN ColumnName

In this formula, the ALTER TABLE and the DROP COLUMN expressions are required. The TableName factor is the name of the table that owns the column. The ColumnName factor is the name of the column to be deleted.

To programmatically remove a column, create an ALTER TABLE statement using the above formula, pass the statement as string to a OleDbCommand object before executing it. Here is an example:

Private Sub btnMaintenance_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMaintenance.Click
        Dim strDeleteTable As String = "DROP TABLE Countries;"

        Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
          "Data Source=C:\Microsoft Access Database Development\Countries1.mdb;")

        Dim cmdDatabase As OleDbCommand
        cmdDatabase = New OleDbCommand("ALTER TABLE Countries DROP COLUMN Capital;", _
                                    conDatabase)

        conDatabase.Open()

        cmdDatabase.ExecuteNonQuery()
        conDatabase.Close()
End Sub

There is no warning when deleting a column. In the Design Table window, if you delete a column by mistake, you can close the table and refuse to save it. This is almost the only chance you have at keeping the column. If you are programmatically deleting a column, you can provide your own warning through a message box to make the user decide to continue or keep the column.

 

Previous Copyright © 2005-2012 FunctionX Next