Basic SQL syntax: Creating and Modifying tables and databases

written by: George Ionescu; article published: year 2007, month 12;


In: Categories » Computers and technology » Databases » Basic SQL syntax: Creating and Modifying tables and databases

This tutorial shows basic syntax and commands and of the SQL language.

Creating and Dropping Databases

First, let's see what databases already exist in the MySQL server. We can view this information by using the SHOW command. Enter the following (except the mysql> part) into the MySQL console client, followed by a return:

mysql> SHOW DATABASES;

there are two databases already created in the MySQL server. The mysql database contains administration information for the MySQL server and should not be modified. The other database, test, is exactly what it sounds like: a test for the MySQL server. The test database does not contain anything, and it can be removed safely if required.

Creating a Database

So how do we add our own database in the MySQL server? To do this, we use the CREATE command. Let's say we wish to create a database called mydata; we would use the following syntax.

Note The following table lists the length and character restrictions that are imposed on the names of databases, tables, columns, and aliases.
Identifier Max Length Valid Characters
Database 64 All valid directory name characters except "." and "/".
Table 64 All valid directory name characters except "." and "/".
Column 64 All are valid.
Alias 15 All are valid.
mysql> CREATE DATABASE mydata;

Notice that the semicolon is added after every command in the SQL language. When we press Return after entering this command, the console informs us that the query was okay.

Now that we have created the database, we can ensure it is on the server by again using the SHOW command, as follows:

mysql> SHOW DATABASES;

When we press Return with this command, we can see our database has been added to the list (note that the list is in alphabetical order, not the order in which the databases were created).

Dropping a Database

Now we will remove the database from the server. Note that when we do this, all data (if any) will be lost. To remove a database, we "drop" it from the server by using the DROP command. So to drop our new mydata database, we would use the following command:

mysql> DROP DATABASE mydata;

When we execute this command by pressing Return, the query will be reported as okay.

Now, if we again list the databases using the SHOW command:

mysql> SHOW DATABASES;

...we can see that our mydata database is no longer visible on the list.

Column (Field) Types in MySQL

Before we discuss the creation of tables within databases, now is a good time to mention the different column types that we can have in tables.

Each column in a table must be assigned a type, which represents the type of information that field is going to hold. Here is a complete list of available types you can use:

Type Description
TINYINT A very small integer. Signed range is –128 to 127. Unsigned range is 0 to 255.
SMALLINT A small integer. Signed range is –32768 to 32767. Unsigned range is 0 to 65535.
MEDIUMINT A medium sized integer. Signed range is –8388608 to 8388607. Unsigned range is 0 to 16777215.
INT A normal sized integer. Signed range is –2147483648 to 2147483647. Unsigned range is 0 to 4294967295.
BIGINT A large sized integer. Signed range is –9223372036854775808 to 9223372036854775807. Unsigned range is 0 to 18446744073709551615.
FLOAT A small, single-precision floating-point number that cannot be unsigned. Signed range is –3.402823466E+38 to –1.755494351E–38, 0, and 1.755494351E–38 to 3.402823466E+38.
DOUBLE A double-precision floating-point number that cannot be unsigned. Signed range is –1.7976931348632157E+308 to –2.2250738585072014E–308, 0, and 2.2250738585072014E–308 to 1.7976931348632157E+308.
DECIMAL An unpacked floating-point number that cannot be unsigned. Works like a "char" column in that the number is stored as a string (i.e., each number uses one character in the string).
DATE A date. Range is 1000-01-01 to 9999-12-31 and is in the format YYYY-MM-DD.
TIME A time. Range is –838:59:59 to 838:59:59 and is in the format HH:MM:SS.
DATETIME A combination of date and time. Range is 1000-01-01 00:00:00 to 9999-12-31 21:59:59 and is in the format YYYY-MM-DD HH:MM:SS.
YEAR[(2|4)] A year in 2- or 4-digit format (default is 4). Range is 1901 to 2155 and also 0000.
TIMESTAMP A timestamp. Range is 1970-01-01 00:00:00 to sometime in the year 2037 in the format YYYYMMDDHHMMSS.
CHAR(length) A fixed-length string that is always right-padded with spaces to the specified length when stored. The range is 1 to 255 characters depending on the "length" specified.
VARCHAR A variable-length string.
TINYBLOB/ TINYTEXT A tiny binary object. Maximum length of 255 characters. *See NOTE below table.
BLOB/TEXT A binary object. Maximum length of 65535 characters. *See NOTE below table.
MEDIUMBLOB/ MEDIUMTEXT A medium binary object. Maximum length of 16777215 characters. *See NOTE below table.
LONGBLOB/ LONGTEXT A large binary object. Maximum length of 4294967295 characters. *See NOTE below table.
ENUM('val1', 'val2'...) An enumeration. A list of string values of which only one can be selected. Maximum of 65535 distinct values.
SET('val1', 'val2'...) A set. A string object that can have zero or more values, each of which must be chosen from the list (i.e., 'val1', 'val2', etc.). Maximum of 64 characters.
Note The only difference between the BLOB and TEXT types is that for sorting and comparisons, a BLOB is case-sensitive, whereas the TEXT type is not case-sensitive.

Creating, Modifying, and Dropping Tables

Creating Tables

Now that we know the possible types for the columns in our tables, let's look at how we actually go about creating a table.

Let's say that we wish to create a table to hold some user details within a database.

We want to store the user's title, first name, surname, age, e-mail address, and the date the user was added to the database. So we will require the following columns in our table:

Title  Firstname  Surname  Age  EmailAddress  DateAdded

Before we get into how to actually add it, let's first think how we are going to store the information—or more to the point, what types we require for each of the columns.

For the title, first name, and surname, we can use the TEXT type, as it contains plenty of characters to allow for all possibilities.

Note VARCHAR can work faster and is maybe a better choice if the string length can be restricted to less than 255 characters.

For age, an unsigned TINYINT would be an obvious choice, as ages are numerical and no one has ever been known to live past 255. For e-mail address, we can again use a TEXT type, as it will give us substantial storage space for the address. Finally, for the date that the user was added to the table, we can use a TIMESTAMP.

Note With Java, it is possible to use an INT data type and store System.currentTimeMillis() / 1000 as the value. This value can later be fetched from the database. Then multiply it by 1000 and convert it to the DATE type (i.e., date = new Date(value);). This is useful when doing localization and/or conversion between different databases

The TIMESTAMP also has a great property in that the time and date can be retrieved automatically into the database.

Now that we know which types we want for our columns, we need to create a database to add the table into. Let's create a database called myinfo with the following command:

mysql> CREATE DATABASE myinfo;

When we execute this command, the console should report that the query was okay. We can now check that our database has been created with the following command:

mysql> SHOW DATABASES;

Now we need to tell MySQL that we wish to perform actions on the myinfo database. This is accomplished by using the USE command:

mysql> USE myinfo;  
Note Without USE, all tables in the myinfo database should be referred to as myinfo.mytable, which is of course quite inconvenient.

After executing this command, any DDL (Data Definition Language) and DML (Data Manipulation Language) statements that are executed will affect the database in use, which in this case is our myinfo database.

Now that we have our database set up and ready to accept commands, we can create our table (which we will name userinfo) with the following statement:

mysql> CREATE TABLE userinfo (      
-> id INT auto_increment,      
-> title TEXT,      
-> firstname TEXT,      
-> surname TEXT,      
-> age TINYINT,      
-> email TEXT,      
-> dateadded TIMESTAMP,      
-> PRIMARY KEY(id));
Note auto_increment is not a standard SQL option. MSSQL (Microsoft SQL) has a similar option and so does Postgre, but Oracle does not have a way to do this as a create table option. It must be done with sequences and triggers.

Let's break this up a little so we can see what is happening. First we declare that we wish to create a table by entering CREATE TABLE. Next we specify the name that we wish to call the table; in this case, the name is userinfo. Then we use parentheses to contain all of the columns that we require in our table and simply list all of the column names and types that we require. Note how we have added an extra field named id. Finally, note the addition of the primary key as the last parameter. This is used to determine how the table is optimized within the database.

We can now check that our table was created successfully by executing the following command:

mysql> SHOW TABLES;

Note you can also view the columns in a table by using the following command:

mysql> DESCRIBE userinfo;

When you execute this command, the console will display all the details for each of the columns in the userinfo table.

This information can be useful for both ensuring the table was created as you envisioned and to recap the columns a table contains at a later date.

Modifying Tables

So now that we know how to create a table, let's look at how we go about modifying it. Modifying a table can range from simply changing the type of one of the columns to adding a completely new column (or removing an existing column).

Let's first look at how we change the name of an existing column. In our userinfo table, we have a column called firstname, but let's now change this to read forename, a synonym for a person's first name.

To make this change, we need to use the following syntax:

mysql> ALTER TABLE userinfo CHANGE firstname forename TEXT;
Tip It is always highly recommended to design the database before creating it because there may be problems modifying/altering database tables or structure after there is data inserted in the tables.

Note we also must supply the data type for the column as well as its old and new names.

If we describe the userinfo table with the following command:

mysql> DESCRIBE userinfo;

...we can see that the column firstname has been renamed to forename.

We can also change the data types of columns in tables. Let's say that we want to change the age column from a TINYINT to an INT. We would use the following command:

mysql> ALTER TABLE userinfo MODIFY age INT;

After executing this command, if we describe the table, we can see the type has changed to INT.

Finally, it is good to know how to remove fields from a table (for example, if they are no longer required). Let's now say that we no longer require the e-mail field in our userinfo table. What we want to do is "drop" the field from our table. Here is the syntax for removing the e-mail field.

mysql> ALTER TABLE userinfo DROP email;

Once this command is executed, we describe the table with the following command:

mysql> DESCRIBE userinfo;

Dropping (Removing) Tables

Removing tables from a database is very simple, but without careful use it can have disastrous effects. The main thing to note is that when dropping a table, you also lose all the data contained within the table. Therefore, it is always wise to back up a database before executing any DROP commands.

Let's now look at how we drop the userinfo table from our myinfo database. To do this, we need to execute the following command in the MySQL console client.

Note You cannot drop the table if there are actual relations to other tables that could break the integrity of the database. If relations are not "real," tables can be removed without errors, but the integrity is then compromised. If the administrator is not careful, the database can be permanently corrupted.

mysql> DROP TABLE userinfo;

Once this command is executed, we can check that the table has been removed by listing what tables are currently in our myinfo database by executing the following command:

mysql> SHOW TABLES;

The table no longer exists in the database.

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. Managing Monitoring and Troubleshooting SQL Server 2000 Databases
Troubleshooting SQL Databases is an operation that supposes multiple actions. They are described below. Optimizing Database Performance Database performance is an important part of administering a SQL Server 2000 environment. There are many ways that performance can be increased including indexing, locking and recompiling. Indexing Establishing indexes can dramatically increase query performance, but can also adversely affect data modification performance. Any changes to an...

2. Tips for Designing a Better SQL Database
Keeping the following subjects in mind helps ensure that your database design and updates go smoothly. Don’t design a database that copes with the norm. Tempting as it is to design a database that covers most situations, doing so is dangerous. The unexpected happens just when you least expect it, so make sure you design your database to cover all situations that could arise, or at least ensure that it can cope with the unusual situations. Even if a client tells you not to worry about the possibility of two people attem...

3. Why and When to Use a Database
When there are a huge number of alternative ways to store data, why should you trouble yourself creating a database? What advantages does a database hold? The main advantage is fast and efficient data retrieval. A database helps you to organize your data in alogical manner. Database management systems are fine-tuned to rapidly retrieve the data you want in the way you want it. Databases also enable you to break data into specific parts. Retrieving data from a database is called querying. You’ll often see the term SQL query, which brief...

4. Creating SQL Server 2000 Databases
Attaching and Detaching Databases Detaching/attaching is used in moving a database between computers or physical disks. When a database is detached, the links from the server to the data files and transaction logs are removed. When you attach a database, you re-establish those links. When you detach and re-attach, you eliminate the need to restore the database backup manually. When a database is reattached, all files that have changed location must be specified. Filegroups Filegroups ar...

5. Developing Notification Services Applications in SQL server 2005
The process for developing Notification Services applications begins with defining the rules that govern how the application works. Next, you must compile the application. Then you need to construct an interface that allows the user to add subscriptions to the application. Finally, you’ll need to add any custom components that may be needed by the application. Let’s look at each of these steps in more detail. Defining the Application The Notification Services developer uses a combination of XML...

6. SQL Server Service Broker Activation
SQL Server Service Broker activation is another unique feature of the SQL Server Service Broker subsystem. Activation enables you to create a stored procedure that is associated with a given input queue. The purpose of the stored procedure is to automatically process messages from that queue. As each new message comes in, the associated stored procedure is automatically executed to handle the incoming messages. If the stored procedure encounters an error, it can throw an exception and be automatically recycled. ...

7. SQL Server 2005 Administrative Tools
This article gives you an overview of the SQL Server 2005 administrative tools, including: Profiler enhancements Database Tuning Advisor Assisted editors Profiler Enhancements With SQL Server 2005, Profiler gets an overhaul as well. The new Profiler now supports the ability to trace both SSIS and Analysis Services commands. SQL Server 2000 was limited to tracing relational database calls only. By having these capabilities, you can use these ...

8. Notification Services in SQL server 2005
A Notification Services application is a software layer that sits between an information source and the intended recipient of that information. The Notification Services application monitors certain predefined events and can intelligently filter and route the information about those events to a variety of different target devices using a personalized delivery schedule. Notification Services applications consist of three basic components: events, subscriptions, and notifications. Events In a Notificatio...

9. Understanding CLR and SQL Server 2005 Database Engine
The integration of the CLR with SQL Server extends the capability of SQL Server in several important ways. While T-SQL, the existing data access and manipulation language, is well suited for set-oriented data access operations, it also has limitations. Designed more than a decade ago, T-SQL is a procedural language, not an object-oriented language. The integration of the CLR with SQL Server 2005 brings with it the ability to create database objects using modern object-oriented languages like VB.NET and C#. While thes...