Vous êtes sur la page 1sur 11

Tables are the basic structure where data is stored in the database.

Given that
in most cases, there is no way for the database vendor to know ahead of time wha
t your data storage needs are, chances are that you will need to create tables i
n the database yourself. Many database tools allow you to create tables without
writing SQL, but given that tables are the container of all the data, it is impo
rtant to include the CREATE TABLE syntax in this tutorial.
Before we dive into the SQL syntax for CREATE TABLE, it is a good idea to unders
tand what goes into a table. Tables are divided into rows and columns. Each row
represents one piece of data, and each column can be thought of as representing
a component of that piece of data. So, for example, if we have a table for recor
ding customer information, then the columns may include information such as Firs
t Name, Last Name, Address, City, Country, Birth Date, and so on. As a result, w
hen we specify a table, we include the column headers and the data types for tha
t particular column.
So what are data types? Typically, data comes in a variety of forms. It could be
an integer (such as 1), a real number (such as 0.55), a string (such as 'sql'),
a date/time expression (such as '2000-JAN-25 03:22:22'), or even in binary form
at. When we specify a table, we need to specify the data type associated with ea
ch column (i.e., we will specify that 'First Name' is of type char(50) - meaning
it is a string with 50 characters). One thing to note is that different relatio
nal databases allow for different data types, so it is wise to consult with a da
tabase-specific reference first.
The SQL syntax for CREATE TABLE is
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )
So, if we are to create the customer table specified as above, we would type in
CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date)
Sometimes, we want to provide a default value for each column. A default value i
s used when you do not specify a column's value when inserting data into the tab
le. To specify a default value, add "Default [value]" after the data type declar
ation. In the above example, if we want to default column "Address" to "Unknown"
and City to "Mumbai", we would type in
CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50) default 'Unknown',
City char(50) default 'Mumbai',
Country char(25),
Birth_Date date)

table:
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
We shall use this table as an example throughout the tutorial (this table will a
ppear in all sections). To select all the stores in this table, we key in,
SELECT store_name FROM Store_Information
Result:
store_name
Los Angeles
San Diego
Los Angeles
Boston

next, we might want to conditionally select the data from a table. For example,
we may want to only retrieve stores with sales above $1,000. To do this, we use
the WHERE keyword. The syntax is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "condition"
For example, to select all stores with sales above $1,000 in Table Store_Informa
tion,
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
we key in,
SELECT store_name
FROM Store_Information
WHERE Sales > 1000
Result:
store_name
Los Angeles

In the previous section, we have seen that the WHERE keyword can be used to cond
itionally select data from a table. This condition can be a simple condition (li
ke the one presented in the previous section), or it can be a compound condition
. Compound conditions are made up of multiple simple conditions connected by AND
or OR. There is no limit to the number of simple conditions that can be present
in a single SQL statement.
The syntax for a compound condition is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+
The {}+ means that the expression inside the bracket will occur one or more time
s. Note that AND and OR can be used interchangeably. In addition, we may use the
parenthesis sign () to indicate the order of the condition.
For example, we may wish to select all stores with sales greater than $1,000 or
all stores with sales less than $500 but greater than $275 in Table Store_Inform
ation,
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999
we key in,
SELECT store_name
FROM Store_Information
WHERE Sales > 1000
OR (Sales < 500 AND Sales > 275)
Result:
store_name
Los Angeles
San Francisco

Once a table is created in the database, there are many occasions where one may
wish to change the structure of the table. In general, the SQL syntax for ALTER
TABLE is
ALTER TABLE "table_name"
[alter specification]
[alter specification] is dependent on the type of alteration we wish to perform.
We list a number of common changes below:
â ¢ ALTER TABLE Add Column
â ¢ ALTER TABLE Modify Column
â ¢ ALTER TABLE Rename Column
â ¢ ALTER TABLE Drop Column
â ¢ ALTER TABLE Add Index
â ¢ ALTER TABLE Drop Index
â ¢ ALTER TABLE Add Constraint
â ¢ ALTER TABLE Drop Constraint
For all cases, examples are provided for MySQL, Oracle, and SQL Serv

he SQL syntax for ALTER TABLE Add Column is


ALTER TABLE "table_name"
ADD "column 1" "Data Type"
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Our goal is to add a column called "Gender". To do this, we key in:
MySQL:
ALTER TABLE customer ADD Gender char(1);
Oracle:
ALTER TABLE customer ADD Gender char(1);
SQL Server:
ALTER TABLE customer ADD Gender char(1);
Resulting table structure:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Gender char(1)
Note that the new column Gender becomes the last column in the customer table.
It is also possible to add multiple columns. For example, if we want to add a co
lumn called "Email" and another column called "Telephone", we will type the foll
owing:
MySQL:
ALTER TABLE customer ADD (Email char(30), Telephone char(20));
Oracle:
ALTER TABLE customer ADD (Email char(30), Telephone char(20));
SQL Server:
ALTER TABLE customer ADD (Email char(30), Telephone char(20));
The table now becomes:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Gender char(1)
Email char(30)
Telephone char(20)
Sometimes we need to change the data type of a column. To do this, we use the AL
TER TABLE Modify Column command. For Oracle and MySQL, the SQL syntax for ALTER
TABLE Modify Column is,
ALTER TABLE "table_name"
MODIFY "column 1" "New Data Type"
For SQL Server, the syntax is,
ALTER TABLE "table_name"
ALTER COLUMN "column 1" "New Data Type"
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Our goal is to alter the data type of the "Address" column to char(100). To do t
his, we key in:
MySQL:
ALTER TABLE customer MODIFY Address char(100);
Oracle:
ALTER TABLE customer MODIFY Address char(100);
SQL Server:
ALTER TABLE customer ALTER COLUMN Address char(100);
Resulting table structure:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(100)
City char(50)
Country char(25)

MySQL, the SQL syntax for ALTER TABLE Rename Column is


ALTER TABLE "table_name"
Change "column 1" "column 2" ["Data Type"]
In Oracle, the syntax is,
ALTER TABLE "table_name"
RENAME COLUMN "column 1" TO "column 2"
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
To rename "Address" to "Addr", we key in,
MySQL:
ALTER table customer CHANGE Address Addr char(50);
Oracle:
ALTER table customer RENAME COLUMN Address TO Addr;
SQL Server:
It is not possible to rename a column using the ALTER TABLE statement in SQL Ser
ver. Use sp_rename instead.
Resulting table structure:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Addr char(50)
City char(50)
Country char(25)
Birth_Date date

In MySQL, the SQL syntax for ALTER TABLE Drop Column is


ALTER TABLE "table_name"
DROP "column 1"
In Oracle and SQL Server, the SQL syntax for ALTER TABLE Drop Column is
ALTER TABLE "table_name"
DROP COLUMN "column 1"
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Our goal is to drop the "Birth_Date" column. To do this, we key in:
MySQL:
ALTER table customer drop Birth_Date;
SQL Server:
ALTER table customer drop column Birth_Date;
Oracle:
ALTER table customer drop column Birth_Date;
Resulting table structure:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)

The SQL syntax for ALTER TABLE Add Index is


ALTER TABLE "table_name"
ADD INDEX " INDEX_NAME " (COLUMN_NAME)
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Assume we want to add an index on the "Country" column. To do this, we type in t
he following:
ALTER table customer ADD INDEX IDX_COUNTRY (Country);
Please note that using ALTER TABLE to add an index is not supported in Oracle or
SQL Server

The SQL syntax for ALTER TABLE Dop Index is


ALTER TABLE "table_name"
DROP INDEX " INDEX_NAME "
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Assume we want to drop the index created in the ALTER TABLE ADD INDEX section. T
o do this, we type in the following:
ALTER table customer DOP INDEX IDX_COUNTRY;
The SQL syntax for ALTER TABLE Add Constraint is
ALTER TABLE "table_name"
ADD [CONSTRAINT_NAME] [CONSTRAINT_TYPE] [CONSTRAINT_CONDITION]
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Assume we want to add a UNIQUE constraint to the "Address" column. To do this, w
e type in the following:
MySQL:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name);
Oracle:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name);
SQL Server:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name);
where con_first is the name of the constraint.
The SQL syntax for ALTER TABLE Add Constraint is
ALTER TABLE "table_name"
ADD [CONSTRAINT_NAME] [CONSTRAINT_TYPE] [CONSTRAINT_CONDITION]
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Assume we want to add a UNIQUE constraint to the "Address" column. To do this, w
e type in the following:
MySQL:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name);
Oracle:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name);
SQL Server:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name);
where con_first is the name of the constraint.

The SQL syntax for ALTER TABLE Drop Constraint is


ALTER TABLE "table_name"
DROP [CONSTRAINT|INDEX] "CONSTRAINT_NAME"
Let's look at the example. Assuming our starting point is the "customer" table c
reated in the CREATE TABLE section:
Table customer
Column Name Data Type
First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
Birth_Date date
Assume we want to drop the UNIQUE constraint on the "Address" column. To do this
, we type in the following:
MySQL:
ALTER TABLE customer DROP INDEX con_first;
Note that MySQL uses DROP INDEX for index-type constraints such as UNIQUE. con_f
irst is the name of the constraint.
Oracle:
ALTER TABLE customer DROP CONSTRAINT con_first;
SQL Server:
ALTER TABLE customer DROP CONSTRAINT con_first;
ometimes we wish to get rid of all the data in a table. One way of doing this is
with DROP TABLE, which we saw in the last section. But what if we wish to simpl
y get rid of the data but not the table itself? For this, we can use the TRUNCAT
E TABLE command. The syntax for TRUNCATE TABLE is
TRUNCATE TABLE "table_name"
So, if we wanted to truncate the table called customer that we created in SQL CR
EATE TABLE, we simply type,
TRUNCATE TABLE customer

The USE keyword is used to select a database in MySQL. The syntax is as follows:
USE "Database Name"
For example, if you want to connect to a database called "Scores", you can type
in the following:
USE Scores;
In MySQL, you can access tables in multiple databases by specifying [Database Na
me].[Table Name]. If the table you want to access is currently in the database y
ou use, there is no need to specify the database name.
For example, if you want to access table "Course_110" from database "Scores" and
table "Students" from database "Personnel", you can type in the following:
USE Scores;
SELECT ...
FROM Course_110, Personnel.Students
WHERE ...
;

In the previous sections, we have seen how to query information from tables. But
how do these rows of data get into these tables in the first place? This is wha
t this section, covering the INSERT INTO statement, and next section, covering t
be UPDATE statement, are about.
In SQL, there are essentially basically two ways to INSERT data into a table: On
e is to insert it one row at a time, the other is to insert multiple rows at a t
ime. Let's take a look at each of them individually:
INSERT INTO VALUES
The syntax for inserting data into a table one row at a time is as follows:
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...)
Assuming that we have a table that has the following structure,
Table Store_Information
Column Name Data Type
store_name char(50)
Sales float
Date datetime
and now we wish to insert one additional row into the table representing the sal
es data for Los Angeles on January 10, 1999. On that day, this store had $900 in
sales. We will hence use the following SQL script:
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')
INSERT INTO SELECT
The second type of INSERT INTO allows us to insert multiple rows into a table. U
nlike the previous example, where we insert a single row by specifying its value
s for all columns, we now use a SELECT statement to specify the data that we wan
t to insert into the table. If you are thinking whether this means that you are
using information from another table, you are correct. The syntax is as follows:
INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2"
Note that this is the simplest form. The entire statement can easily contain WHE
RE, GROUP BY, and HAVING clauses, as well as table joins and aliases.
So for example, if we wish to have a table, Store_Information, that collects the
sales information for year 1998, and you already know that the source data resi
des in the Sales_Information table, we'll type in:
INSERT INTO Store_Information (store_name, Sales, Date)
SELECT store_name, Sales, Date
FROM Sales_Information
WHERE Year(Date) = 1998
Here I have used the SQL Server syntax to extract the year information out of a
date. Other relational databases will have different syntax. For example, in Ora
cle, you will use to_char(date,'yyyy')=1998.

Once there's data in the table, we might find that there is a need to modify the
data. To do so, we can use the UPDATE command. The syntax for this is
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}
For example, say we currently have a table as below:
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
and we notice that the sales for Los Angeles on 01/08/1999 is actually $500 inst
ead of $300, and that particular entry needs to be updated. To do so, we use the
following SQL query:
UPDATE Store_Information
SET Sales = 500
WHERE store_name = "Los Angeles"
AND Date = "Jan-08-1999"
The resulting table would look like
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $500 Jan-08-1999
Boston $700 Jan-08-1999
In this case, there is only one row that satisfies the condition in the WHERE cl
ause. If there are multiple rows that satisfy the condition, all of them will be
modified. If no WHERE clause is specified, all rows will be modified.
It is also possible to UPDATE multiple columns at the same time. The syntax in t
his case would look like the following:
UPDATE "table_name"
SET column_1 = [value1], column_2 = [value2]
WHERE {condition}
Sometimes we may wish to use a query to remove records from a table. To do so, w
e can use the DELETE FROM command. The syntax for this is
DELETE FROM "table_name"
WHERE {condition}
It is easiest to use an example. Say we currently have a table as below:
Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
and we decide not to keep any information on Los Angeles in this table. To accom
plish this, we type the following SQL:
DELETE FROM Store_Information
WHERE store_name = "Los Angeles"
Now the content of table would look like,
Table Store_Information
store_name Sales Date
San Diego $250 Jan-07-1999
Boston $700 Jan-08-1999

SQL > SQL Syntax


In this page, we list the SQL syntax for each of the SQL commands in this tutori
al, making this an easy reference for someone to learn SQL. For detailed explana
tions of each SQL syntax, please go to the individual section by clicking on the
keyword.
The purpose of this page is to have a quick reference page for SQL syntax, so yo
u can learn SQL more quickly. Bookmark this page now by pressing Control-D so yo
u can have this syntax page handy.
Select Statement
SELECT "column_name" FROM "table_name"
Distinct
SELECT DISTINCT "column_name"
FROM "table_name"
Where
SELECT "column_name"
FROM "table_name"
WHERE "condition"
And/Or
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{[AND|OR] "simple condition"}+
In
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...)
Between
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2'
Like
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN}
Order By
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC]
Count
SELECT COUNT("column_name")
FROM "table_name"
Group By
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
Having
SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"
HAVING (arithematic function condition)
Create Table Statement
CREATE TABLE "table_name"
("column 1" "data_type_for_column_1",
"column 2" "data_type_for_column_2",
... )
Drop Table Statement
DROP TABLE "table_name"
Truncate Table Statement
TRUNCATE TABLE "table_name"
Insert Into Statement
INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...)
Update Statement
UPDATE "table_name"
SET "column_1" = [new value]
WHERE {condition}
Delete From Statement
DELETE FROM "table_name"
WHERE {condition}

Vous aimerez peut-être aussi