You are on page 1of 26

Introduction to SQL

SQL is a standard computer language for accessing and manipulating databases.

What is SQL?
• SQL stands for Structured Query Language
• SQL allows you to access a database
• SQL is an ANSI standard computer language
• SQL can execute queries against a database
• SQL can retrieve data from a database
• SQL can insert new records in a database
• SQL can delete records from a database
• SQL can update records in a database
• SQL is easy to learn

SQL is a Standard - BUT....


SQL is an ANSI (American National Standards Institute) standard computer language for
accessing and manipulating database systems. SQL statements are used to retrieve and update
data in a database. SQL works with database programs like MS Access, DB2, Informix, MS SQL
Server, Oracle, Sybase, etc.

Unfortunately, there are many different versions of the SQL language, but to be in compliance
with the ANSI standard, they must support the same major keywords in a similar manner (such
as SELECT, UPDATE, DELETE, INSERT, WHERE, and others).

Note: Most of the SQL database programs also have their own proprietary extensions in addition
to the SQL standard!

SQL Database Tables


A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data.

Below is an example of a table called "Persons":

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Pettersen Kari Storgt 20 Stavanger

The table above contains three records (one for each person) and four columns (LastName,
FirstName, Address, and City).

SQL Queries
With SQL, we can query a database and have a result set returned.

A query like this:

SELECT LastName FROM Persons

Gives a result set like this:

LastName
Hansen
Svendson
Pettersen

Note: Some database systems require a semicolon at the end of the SQL statement. We don't use
the semicolon in our tutorials.

SQL Data Manipulation Language (DML)


SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also
includes a syntax to update, insert, and delete records.

These query and update commands together form the Data Manipulation Language (DML) part
of SQL:

• SELECT - extracts data from a database table


• UPDATE - updates data in a database table
• DELETE - deletes data from a database table
• INSERT INTO - inserts new data into a database table

SQL Data Definition Language (DDL)


The Data Definition Language (DDL) part of SQL permits database tables to be created or
deleted. We can also define indexes (keys), specify links between tables, and impose constraints
between database tables.

The most important DDL statements in SQL are:

• CREATE TABLE - creates a new database table


• ALTER TABLE - alters (changes) a database table
• DROP TABLE - deletes a database table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index

SQL Basics
P.G. Daly
9/13/2004

Go to page: 1 2

Printer Friendly Version

Knowing how to read and write SQL is a skill that is usually taken for granted. It's assumed SQL is a tool
every IT professional has in his or her toolkit. Within the world of the intranet where the business and IT
realms often blend together, that can be a detrimental assumption to make.

SQL is an important part of the intranet world, yet we hear so little about it. It's hidden under the covers of
Web sites where it tends to go unnoticed, yet it's found just about everywhere because SQL is usually a
component of every dynamic Web site. Regardless of the Web technologies used on the site
(ColdFusion, ASP, Java/JSP, PHP, etc.), the bottom line is that some form of SQL is used for all
database interactions.

Have questions about SQL, databases or dynamic Web applications? Find an answer in the
Intranet Journal Forum.

Background

SQL stands for Structured Query Language and it is an American National Standards Institute (ANSI)
language. It is used to access and manipulate data within relational databases such as MS Access,
Oracle, DB2, and Sybase, to name a few. Almost all vendors have their own flavor of SQL, but in order to
conform to the ANSI standard they must support the same major keywords (SELECT, UPDATE,
DELETE, etc.) in a consistent manner.
Let's use a simple example to illustrate the most common usage of the SQL major keywords in most Web
sites.

The Data

A database consists of one or more tables containing records (rows) of data. Each table has a set of
predefined fields that define what types of information they can contain.

In this example, our table will be named "Customers." It has four pre-defined fields: LastName,
FirstName, City, and State. It consists of four rows of data as shown below:

LastName FirstName City State


Smith John Philadelphia PA
Jones Laura Los Angeles CA
Casey Mike Salt Lake City UT
Doe Jane Bangor PA

The SELECT Statement

The SELECT statement is used more often than any other statement within the SQL language. It is used
to select data read only from a database based on a set of criteria. The syntax for a select statement is:

SELECT [column1, column2, ... columnN] FROM [tablename] WHERE [condition1,


condition2, ... conditionN];

At a minimum, you must select one column from one table; the rest is optional. As for the semicolon (;), it
is used to terminate an SQL statement and separate it from other SQL statements included in the same
call to the server. Whether the semicolon is required or is optional depends on the database with which
you are working.

For example, if you wanted to select all of the records from our Customers table, the statement would be:

SELECT * from Customers;

Using a * denotes you you want to select "all." The result would be an exact replica of the Customers
table as it is shown above.

If you wanted to choose only the first and last names of your customers, the statement would change to:

SELECT LastName, FirstName from Customers;

Result:

LastName FirstName
Smith John
Jones Laura
Casey Mike
Doe Jane

If you wanted to choose data based on a specified criteria, you would use the WHERE clause. The syntax
looks as follows:

SELECT column FROM table WHERE column operator value;

The following operators can be used with the WHERE clause:

Operator Description
= Equal
< > (some versions of SQL use !=) Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern

So, for example, if you wanted to choose all information about only the customers that lived in the state of
Pennsylvania, you would write the following:

SELECT * from Customers WHERE State='PA';

Result:

LastName FirstName City State


Smith John Philadelphia PA
Doe Jane Bangor PA

Notice that we used the single quote (') to enclose the value within the WHERE clause. Use single quotes
to enclose textual values (most databases will accept double quotes as well); do not use any quotes for
numeric values.

Use the LIKE operator to search for patterns within a data field. Combined with a wildcard "%", the LIKE
operator is a powerful way to search.

To search for all cities within our Customers that begin with an "An":

SELECT City from Customers WHERE City LIKE 'An%';


Result:

City
Los Angeles

DISTINCT Keyword

With the SELECT statements used thus far, we've selected all values satisfying a particular criteria. If we
wanted to select only the distinct values (no duplicates) from the table, we would have to use the keyword
DISTINCT. For this example, let us use the following Orders Table:

CompanyName OrderNumber
ABC Toys 123456
Wonderful Widgets 456789
ABC Toys 158763
Fabulous Furry Friends 748596

If we simply wrote:

SELECT CompanyName from Orders;

The result would be:

CompanyName
ABC Toys
Wonderful Widgets
ABC Toys
Fabulous Furry Friends

INSERT Statement

The INSERT statement is used to enter new rows into a table within the database. Its syntax is:

INSERT INTO tablename VALUES (value1, value2, ... valuen);

If you are inserting a row that has data for each of the fields within that table, the above syntax works fine.
Keep in mind the order of your values must match the order and data type for each of the fields within the
table.

An alternate syntax is as follows:


INSERT INTO tablename (column1,column2,...,columnN)VALUES (value1,
value2,..., valuen)

In this statement you can specify which columns you have data for and what the values are. The order of
the columns and the corresponding values must match.

Example: Insert a New Row into the Customers table:

INSERT INTO Customers Values (Christian, Sandy, Dallas, TX);

Result:

LastName FirstName City State


Smith John Philadelphia PA
Jones Laura Los Angeles CA
Casey Mike Salt Lake City UT
Doe Jane Bangor PA
Christian Sandy Dallas TX

Example: Insert Specified Data into the Customers Table:

INSERT INTO Customers (LastName, FirstName, State) VALUES (Devers, Thomas,


OR)

LastName FirstName City State


Smith John Philadelphia PA
Jones Laura Los Angeles CA
Casey Mike Salt Lake City UT
Doe Jane Bangor PA
Christian Sandy Dallas TX
Devers Thomas OR

UPDATE Statement

The SQL UPDATE statement is used to update existing data within a table. The syntax for this statement
is:

UPDATE tablename
SET columnname = newvalue
WHERE columnname = somevalue
In the Customers table, if we wanted to change the last name of "Christian" to "Thomas" we would write
the following:

UPDATE Customers
SET LastName = 'Thomas'
WHERE LastName = 'Christian';

The result would be:

LastName FirstName City State


Smith John Philadelphia PA
Jones Laura Los Angeles CA
Casey Mike Salt Lake City UT
Doe Jane Bangor PA
Thomas Sandy Dallas TX
Devers Thomas OR

If we wanted to change the City and State of customer Laura Jones because she relocated, we could
update multiple columns at a time with the following statement:

UPDATE Customers
SET City = 'Seattle',State='WA'
WHERE LastName = 'Jones' AND FirstName = 'Laura';

Result:

LastName FirstName City State


Smith John Philadelphia PA
Jones Laura Seattle WA
Casey Mike Salt Lake City UT
Doe Jane Bangor PA
Thomas Sandy Dallas TX
Devers Thomas OR

Typically databases have a unique record indentifier in each of its tables. The purpose of this primary key
(as it is often called) is to make record identification easier and more foolproof. For instance, in the last
example, if we had two people named "Laura Jones" in our Customers table, we would inadvertently be
updating both customers with a new city and state even though only one of them required a change.
Using the unique identifier in our criteria would prevent these types of problems.

DELETE Statement
This lesson would not be complete without the DELETE statement allowing us to delete rows within a
table and clear out the data we no longer need.

The syntax is as follows:

DELETE FROM tablename


WHERE columnname = somevalue

We will now delete Jane Doe from our list of Customers.

DELETE FROM Customers Where LastName = 'Doe';

Result:

LastName FirstName City State


Smith John Philadelphia PA
Jones Laura Seattle WA
Casey Mike Salt Lake City UT
Thomas Sandy Dallas TX
Devers Thomas OR

You can also delete all data from within a table while leaving the table intact. The syntax for this
command is:

DELETE * FROM Customers;

Needless to say, you want to use the DELETE function cautiously to ensure you are deleting the correct
record(s). This is yet another reason why having a unique identifier in the database is so important.

Wrap-Up

By no means is this article a complete tutorial on SQL. However, it should give you a better idea of the
code that is working behind the scenes of your favorite intranet applications. It will also lay a foundation
that will allow you to better understand and create dynamic Web pages that interface with your existing
databases regardless of the Web platform you use.

Last update: 18/01/2003

This page contains the essential commands to manage databases using SQL (Structured Query
Language). I use it as a refference for myself. I don't pretend to be an SQL-expert. Others may
use this reference freely. If you have any suggestions or comments please e-mail me!

Some commands depend on the type of server used. I experiment with four servers, Microsoft
SQL Server, Borland Interbase Server, MySQL Server en Sybase SQL Anywhere. If a command
is specific to one server I indicate this with an icon.
1. indicates that the command works with MS SQL Server.

2. indicates the command works with Borland InterBase Server.

3. indicates that the command works with MySQL Server.


4. indicates that the command works with Sybase SQL Anywhere.

The commands are written in bold, italicised text (databasenames, fieldnames, values, ...) is up to
you to fill in. Note also that I speak of fields and records instaid off rows and coloms. In MS
SQL Server manuals I see they use rows and coloms, but I prefer to use fields and records,
probably because that was the way in dBase and MS Access, which I used for years.

1. List all the databases on the server:

sp_databases

show databases

2. Select a database to use:

use databasename

3. List tables in the database:

show tables

sp_help

There is another, more complicated, command to retrieve the names of the tables in the database,
but where you get a list of ALL tables, including system tables using sp_help, you can specify to
view only user defined tables

select * from SYSOBJECTS


where TYPE = 'U'
order by NAME

If you want to see the tables of an InterBase database use the menu "Metadata", "Show..."
and select "Tables" in the "View Information on"-dropdown. Click "OK" and you see the tables
of the active database. Using ISQL you can use show tables
To see the tables in Sybase press functionkey F7.

4. List fields in a table:

describe tabelname

sp_help tablename

To see the fields of an InterBase database use the menu "Metadata", "Show..." and select
"Tables" in the "View Information on"-dropdown. Type the name of the database in the "Object
name"-textfield. Click "OK" and you see the fields of the specified table. Using ISQL you can
use show table tablename

To see the fields in a Sybase table press functionkey F7, select the table and click
"Columns".

5. Create a database:

create database databasename


on
(name='databasename_dat',
filename='c:\mssql7\data\databasename_dat.mdf',
size=2mb,
filegrowth=1mb)
log on
(name='databasename_log',
filename='c\mssql7\data\databasename_log.ldf',
size=2mb,
filegrowth=1mb)

6. Create a table in the database en store values in it:

create table tablename


(fieldname1 datatype1, fieldname2 datatype2, ...)
insert into tablename
values(fieldvalue1, fieldvalue2, ...)
7. Constraints:
 Primary key: constraint constraintname primary key (non)clustered
(fieldname1, fieldname2, ...)

 Foreign key: constraint constraintname foreign key (fieldname) references


tablename(fieldname)

 No dulicates: constraint constraintname unique nonclustered (fieldname)

 Check: Add values to the fieldnamelist in the 'create table'-command:


(fieldname1 datatype1 check (fieldname1 in ('value1', 'value2', ...)), fieldname2
datatype2, ...)

 Default value: Add default value to the fieldlist in the 'create table'-command:
(fieldname1 datatype1, fieldname2 datatype2 default 'value', fieldname3
datatype3, ...)

8. Select all records from table:

select * from tablename


order by fieldname

Note that this command could take some time and put a lot of stress on the processor and
memory of the server if you try to view a large database this way. On my server (Pentium MMX
233 Mhz - 64 Mb memory) it took 1:25 minutes to retrieve 25000 records from a database and it
gave warnigs of shortage in virtual memory, so please don't try this on a production database (;-).
Usualy it is better to select fields and conditions to limit the amount of records and the stress on
the server.

9. Select set of records from table:

select fieldname1, fieldname2, ... from tablename


where fieldname = "condition"
order by fieldname

Comparison Operators that can be used in the condition are:

=, !=, <>, <, >, <=, >= and LIKE.


With LIKE you can specify e.g. all the names beginning with S as 'name LIKE "s%"'.

You can also use boolean operators to specify more then one condition (OR, AND, NOT,
BETWEEN, IN). With 'BETWEEN' you give a minimum and maximum value to the condition,
with 'IN' you can give a list of values.
Example:
select Firstname, Lastname, Department from Employees
where Lastname LIKE "Van%" AND
Badge BETWEEN 121990 and 141990 AND
Department IN ("Sales", "Logistics")
order by Lastname

This statement retrieves all the employees where Lastname begins with "Van", whose
badgenumbers are between 121990 and 141990, who work at the Sales- or Logisticsdepartment,
and displays their Lastname, Firstname and Dapartment ordered by Lastname.

Note theat the 'ORDER BY' statemant can have more then one fieldname and can also take 'asc'
or 'desc' as last argument (for ascending or descnding order).

10. Retrieve unique values

select distinct fieldname from table

11. Add records to a table:

insert into tablename (fieldname1, fieldname2, ...)


values ('value1', 'value2', ...)

If you leave out the fieldnames then the values must match the number of fields in the table. If
you only want to add a value to some fields you have to specify them and the values must mach
the number of specified fields. The unspecified fields are filled with NULL or the default
constraint defined in the table. You could concider to specify defaults like "unknown" or "N/A"
to avoid a NULL-value in the field.

12. Updating records in a table;

update tablename
set fieldname1='value1', fieldname2='value2', ...
where fieldname3 = condition

If you ommit the 'where'-statement the update will be performed on ALL the records in the table!
13. Deleting a record from a table

delete from tablename


where fieldname=condition

Be arefull in using this command!! Ommitting the 'where'-statement will erae ALL the records in
the table and leave you with an empty table!!!

14. Adding a field to the records in a table:

alter table tablename


add fieldname datatype

The new field is filled with NULL and can be filled using the update-command after adding the
field.

15. Changing the width of a field

alter table tablename


alter column fieldname newdatatype

alter table tablename


modify fieldname newdatatype

16. Removing field from the records

alter table tablename


drop column fieldname

alter table tablename


drop fieldname

17. Combine two querries:


select fieldname from tablename
union
select fieldname2 from tablename2
order by fieldname
This union will remove all duplicates. To retain duplicates you have to use 'union all'

18. Basic SQL-functions:


 select avg(fieldname) from tablename
Returns the arithmeticaverage of the fields.

 select count(*) from tablename


where fieldname=condition
Returns the number of records that match the condition.

 select max(fieldname) from tablename


Returns the largest value of fieldname.

 select min(fieldname) from tablename


Returns the smallest value of fieldname.

 select sum(fieldname) from tablename


Returns the summation value of fieldname.

 select convert(newdatatype, fieldname) from tablename


converts one datatype into another.

19. String functions


 ASCII returns ASCII code of leftmost character of a characterexpression.

 CHAR converts an ASCII code to a character.

 SOUNDEX returns four-digit code used to compare two strings with


DIFFERENCE.

 DIFFERENCE returns difference between values of two character expressions


returned by SOUNDEX.

 LEFT returns part of character string, starting at number of character from the
left specified in the argument.

 LOWER converts uppercase strings to lowercase.

 UPPER converts lowercase strings to uppercase.

 LTRIM removes leading spaces from a string.

 RTRIM removes trailing spaces from a string.

 CHARINDEX returns starting position of specified character expression in a


string.
 PATINDEX rerurns starting position of first occurence of a substring in a string.

 REPLICATE returns multiple sets of characters specified in the first argument.


The second argument specifies number of sets. (eg. select replicate ('a', 5) returns
'aaaa')

 REVERSE returns reverse order of a string of characters.

 RIGHT returns part of character string, starting at number of character from the
right specified in the argument.

 SPACE returns a string of spaces, length specified in argument.

 STR converts numeric data to character data.

 STUFF inserts a string into another string.

 SUBSTRING returns a part of a string (arguments are startpoint and length).

 + (concatenetion) concatenates two or more strings.

20. Arithmetic functions:


ACOS, ASIN, ATAN, ATAN2, COS, COT, SIN, TAN, DEGREES, RADIANS, CEILING,
FLOOR, EXP, LOG, LOG10, PI(), POWER, ABS, RAND, ROUND, SIGN, SQRT.

21. TEXT and IMAGE functions:


 SET TEXTSIZE specifies number of bytes displayed for data stored as TEXT or
as IMAGE.

 TEXTPTR returns pointer to first database page of stoed text.

 READTEXT extracts substring from data stored as TEXT or as IMAGE.

 TEXTVALID check validity of textpointer.

22. Date functions:


 DATENAME returns specified part of date as characterstring.

 DATEPART returns specified part of date as integer value.

 GETDATE returns current date and time.

 DATEADD returns value of the date with an additional date interval added.

 DATEDIFF returns difference between parts of two specified dates.


23. Views:

Note that a view under SQL is the same as a query you create with Access.

23.1 Create views:


create view viewname as
select fieldname1, fieldname2, ... from tablename1, tablename2, ...
where fieldname = condition

You can't edit a view using SQL. You can use the Enterprise Manager of MS SQL to edit a view
or you can delete a view and recreate it with the same name.

You can use alternative names for the columns in a view:

create view viewname (col1, col2, col3, ...)as


select fieldname1, fieldname2, ... from tablename1, tablename2, ...
where fieldname = condition

23.2 Display definition of a view:


sp_helptext viewname

To prevent the possibility to view the definition of a view you can use encryption:

create view viewname with encryption as


select fieldname1, fieldname2, ... from tablename1, tablename2, ...
where fieldname = condition

23.3 Display associations of a view:


sp_depends viewname

23.4 Delete a view from the database:


drop view viewname1, viewname2, ...

23.5 Insert records through a view:


insert into viewname
values ('value1', 'value2', ...)

You can insert rows through the view that DON'T match the WHERE-statement inthe view
definition, but then you can't retrieve the new row with the view. If you want to prevent this you
can use the check option:
create view viewname as
select fieldname1, fieldname2, ... from tablename1, tablename2, ...
where fieldname = condition with check option

23.6 Delete records through a view:


delete from viewname where fieldname = condition

You can't delete records through a view that don't match the WHERE-statement in the view
definition.

23.7 Updating records through a view:


update viewname set fieldname='value' where fieldname=condition

You can update a record through a view so that it doesn't match the WHERE-statement anymore.
You can't update a view if the updated columns belong to different tables.

24. Indexes:

24.1 Simple index:


create index index_name
on table_name (fieldname)

24.2 Unique index:


create unique index index_name
on table_name (fieldname)

This kind of index enforces integrity of the table by disallowing duplicete values in the indexed
field.

24.3 Clustered index:


create clustered index index_name
on table_name (fieldname)

A clustered index forces SQL Server to phisicaly store the table data in the exact order of of the
index. This improves the performance of the table. You can only have obne clustered index on a
table, the selected fieldname should be choosen carefully and every table should have an
clustered index.

24.4 Display index info:


sp_helpindex tablename
24.5 Deleting an index:
drop index table_name.index_name

24.6 Primary and foreign keys:


You can specify a primary key on a table while creating it (see constraint), or you
can add a primary key to an existing table by altering it. alter table table_name
add constraint constraint_name primary key

24.7 Display primary and foreign keys info:


sp_helpconstraint table_name

24.6 Deleting primary and foreign keys:


alter table table_name drop constraint constraint_name

25. Transaction:
A transaction is a series of SQL-statements performed at once, with the ability to
undo the changes if something goes wrong during the processing of the statements.
A transaction is enclosed in "begin tran" and "commit tran".

Example:

begin tran
update tablename
set fieldname = newvalue
where fieldname = condition

update tablename2
set fieldname = newvalue
where fieldname = condition

if @@error != 0
begin
rollback tran
print 'Error occured, no rows updated'
return
end
commit tran

You can nest one transaction ino another by using named transactions. Be shure however to
include a 'commit tran' for every 'begin tran' to avoid leaving a transaction open.

Example:

begin tran tran1_name


update tablename
set fieldname = newvalue
where fieldname = condition

begin tran tran2_name


update tablename
set fieldnname = newvalue
where fieldname = condition
if @@error != 0
begin
rollback tran tran2_name
print 'Failed to update tablename'
return
end
commit tran tran2_name
commit tran tran1_name

26. Rules:
A rule controls the values that can be entered into a field of a table. To apply a rule
to a field you have to take two steps: create the rule and bind the rule to the field.

26.1 Create a rule:


create rule rule_name
as @fieldname in ('value1','value2','value3')

26.2 Bind a rule:


sp_bindrule 'rule_name', 'table_name.field_name'

26.3 Unbind a rule:


sp_unbindrule table_name.field_name

26.4 Drop a rule:


drop rule rule_name
!!You first have to unbind the rule before you can drop it!!

To display rule bindings you can use 'sp_help tablename', to display the rules you can use
'sp_helptext rule_name' and to rename a rule you can use 'sp_rename rule_name, new_name'.

27. Defaults:
A default is create to provide a value for a field if the user doesn't fill in one. Just like
creating rules you have to make to steps to apply ad efault: create it and bind it to a
field in a table.

27.1 Create a default:


create default default_name as value
27.2 Bind a default:
sp_bindefault default_name, 'tablename.fieldname'

27.3 Unbind a default:


sp_unbindefault 'tablename.fieldname'

27.4 Drop a default:


drop default default_name
!!You first have to unbind the default before you can drop it!!

To display default bindings you can use 'sp_help tablename', to display the default you can use
'sp_helptext default_name' and to rename a default you can use 'sp_rename default_name,
new_name'.

28. Stored procedures:


Stored procedures are routines or series of SQL-commands that run on the server
side. The benefits are performance, because the server typically is the most
powerfull computer on the network, and security, because you can control
add/change/delete/list operations.

28.1 Create a stored procedure:


create procedure procedure_name
as procedure_commands

To execute the procedure you use 'exec procedure_name'. You can use parameters in procedures
to pass values to the procedure:

create procedure procedure_name (@p1 type, @p2 type, ...)


as insert into table_name
values (@p1, @p2, ...)

Now you can execute this procedure by passing values to it:

exec procedure_name (value1, value2, ...)

You can also use variables in a procedure. You first have to declare them (declare @var_name
var_type) and then you can assign a value to it (select @var_name = expression).

28.2 Display a stored procedure:


sp_helptext procedure_name
28.3 Delete a stored procedure:
drop procedure procedure_name

If you want to alter a procedure, you first have to drop it and then recreate it under the same
name.

28.4 Procedure Auto Execution:


You can automaticaly run a procedure every time the server is started by using:

sp_makestartup procedure_name

sp_unmakestartup procedure_name removes the procedure from the startupprocedures

sp_helpstartup displays the procedures currently running at startup

28.5 Flow-control statements:


The following statements can be used in stored procedures to control the flow of the
procedure:

• if ... else ...


• begin ... end
• while ...
• break
• continue
• print
• goto
• return
• raiserror
• waitfor
• case ... when

29. Datatypes:
This is an overview of the different datatypes used by the different servers.

Borland InterBase MS SQL Sybase


MySQL
Server Server SQL

tinyint - tinyint tinyint

smallint smallint smallint smallint

mediumin
- - -
t
int int int int

bigint - - -

- numeric numeric numeric

decimal decimal decimal decimal

- - real real

float float float float

double double precision - double

date date - date

smalldateti
- - -
me

datetime - datetime -

timestam
- timestamp timestamp
p

time - - time

year - - -

char(n) char(n) char(n) char(n)

varchar(n) varchar(n) varchar(n) varchar(n)

long
- - -
varchar

tinytext - - -

text - text -

- - ntext -

mediumte
- - -
xt

longtext - - -

- nchar(n) nchar(n) -
- nchar varying(n) nvarchar(n) -

Databases for Beginners Las Vegas on a


Budget
From Mike Chapple,
Your Guide to Databases. Find a BargainHotel DealsCheap
FREE Newsletter. Sign Up Now! EatsFree
AttractionsEntertainment for Less
A Gentle Introduction to Databases,
What's Hot
SQL, and Microsoft Access
Create an Adobe PDF
Are you new to the world of databases? Wondering
FileCreating Dynamic Web
where to get started? In this series of articles, we
Pages with Microsof...Access
introduce you to the basics of database technology 2007 User InterfaceMySQL 5
and help you get started in this exciting field. OverviewCursor

Introduction to Databases Advertisement


Begin with these articles to learn the fundamental
concepts behind databases:

• What is a Database? introduces databases,


tables, columns and rows
• Database Software Options explains the
differences between desktop databases (such
as Microsoft Access and Filemaker Pro) and
server databases (such as Microsoft SQL Server,
Oracle, and MySQL
• Database Keys helps you select appropriate
primary keys and foreign keys for your
database tables

Working with Microsoft Access


Microsoft Access is one of the most popular database
platforms on the market today.

Sponsored Links

Excel to PDFEasy-to-use server based program. Convert 280+


file formats to PDF!www.activePDF.com
Online Wine DatabaseTrack Your Wine Collection or Cellar
Inventory. Highly
Reviewed.www.CellarTracker.com/Databases

Sql databaseSeven Free Database Tools for Your


Enterprisewww.Baselinemag.com

This series of articles helps you get started with


Access. You can learn how to:

• Purchase Access independently or as part of the


Microsoft Office suite
• Install Access 2007
• Learn about Access file formats
• Access 2007 User Interface Tour
• Convert older Access databases to Access 2007
• Convert Excel spreadsheets into Access
databases
• Build a database from a template
• Use Expression Builder
• Encrypt your Access database

SQL Databases
If you’re working with the Structured Query Language
(SQL), you’ll want to read these articles:

• SQL Basics introduces the Structured Query


Language and explains the basics of the Data
Definition Language (DDL) and the Data
Manipulation Language (DML)
• Once you’ve conquered the basics, our four-part
SQL Fundamentals series teaches you how to
use the Create, Use, Alter, and Drop commands
(part 2); the Insert, Select, Update and Delete
commands (part 3) and the power of the Join
statement (part 4)

Suggested Reading

Microsoft Access FundamentalsIntroduction to


SQLConverting Excel to Access

Related Articles

Past issues of weekly featuresDatabase NewsletterTop 5


Desktop Databases2000 Feature ArticlesEncrypting Access
Databases

Sponsored Links

Port Schema And DataPort Data & Schema from/to Sybase,


SQL Server, PostgreSQL, DB2,
MySQL.www.swissql.com/data-migration.html

Free T-SQL Code and TipsSQL Server coding, T-SQL and


query optimization tips - ALL FREE!www.mssqltips.com

Sql ServerFind Sql Server articles at the UK's leading IT


resource!Techworld.com/Servers

Auto Cad For Beginners25 Courses, 500 Learning Videos, 50


Projects, Access All Online Now!
www.MyIGetIt.com/TrainingCourses

Drowning in Data?Do deep analysis w/Excel-based neural


networks. Free evaluation.www.neuralware.com

You might also like