Вы находитесь на странице: 1из 28

An inner join in SQL returns rows where there is at least one match on both tables.

Let's assume that we


have the following two tables,

Table Store_Information

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name

East Boston

East New York

West Los Angeles

West San Diego

We want to find out sales by store, and we only want to see stores with sales listed in the report. To do
this, we can use the following SQL statement using INNER JOIN:

SELECT A1.Store_Name STORE, SUM(A2.Sales) SALES

FROM Geography A1

INNER JOIN Store_Information A2

ON A1.Store_Name = A2.Store_Name

GROUP BY A1.Store_Name;

Result:

STORE SALES
Los Angeles 1800
San Diego 250
Boston 700
Syntax

The SQL syntax for ALTER TABLE Add Column is,

ALTER TABLE "table_name"


ADD "column_name" "Data Type";

Examples

Let's look at the example. Assuming our starting point is the Customer table
created 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 datetime

Example 1: Add one column to a table

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);

The resulting table structure is:

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 datetime
Gender char(1)

Note that the new column Gender becomes the last column in
the Customer table.

Example 2: Add multiple columns to a table

It is also possible to add multiple columns. For example, if we want to add a


column called "Email" and another column called "Telephone", we will type the
following:

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 datetime
Gender char(1)
Email char(30)
Telephone char(20)

The INSERT INTO statement is used to add new records into a database
table.

In SQL, there are basically two ways to INSERT data into a table: One is to
insert it one row at a time, the other is to insert multiple rows at a time. In this
section, we'll take a look at the first case.

Syntax

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", ...);

Examples

The examples refer to a table that has the following structure,

Table Store_Information

Column Name Data Type


Store_Name char(50)
Manager_ID integer
Sales float
Txn_Date datetime

Example 1: All column names are specified

We want to insert one additional row into the table representing the sales data
for Los Angeles on January 10, 1999. On that day, this store had $900 in
sales, and the Manager_ID for this store is 10. We will use the following SQL
script:
INSERT INTO Store_Information (Store_Name, Manager_ID, Sales, Txn_Date)
VALUES ('Los Angeles', 10, 900, 'Jan-10-1999');

Now the table will hold the following data:

Table Store_Information

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999

Please note that we can specify the column names in any order -- the order
does not have to be the same as that of the table. For example, the following
SQL statement is equivalent to the SQL statement above:

INSERT INTO Store_Information (Sales, Store_Name, Manager_ID, Txn_Date)


VALUES (900, 'Los Angeles', 10, 'Jan-10-1999');

Example 2: None of the column names are specified

If we leave off the column names in the INSERT INTO statement, we will need
to make sure that data is inserted in the same column order as that in the
table. For example,

INSERT INTO Store_Information


VALUES ('Los Angeles', 10, 900, 'Jan-10-1999');

will give us the desired result, while

INSERT INTO Store_Information


VALUES (900, 'Los Angeles', 10, 'Jan-10-1999');

will result in Store_Name being set to 900, Manager_ID being set to 'Los
Angeles', and Sales being set to 10. Clearly this is not what we intend to
accomplish.

Example 3: Some of the column names are specified

In the first two examples, we insert a value for every column in the table.
Sometimes, we may decide to insert value into some of the columns and
leave the rest of the columns blank. For those cases, we simply specify the
column names that we want to insert values into in our SQL statement. Below
is an example:
INSERT INTO Store_Information (Store_Name, Sales, Txn_Date)
VALUES ('New York', 500, 'Jan-10-1999');

Now the table becomes:

Table Store_Information

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999
New York 500 Jan-10-1999

In this case, the value for the Manager_ID column in the second row
is NULL. NULL means that data does not exist, and we discuss the concept
of NULL later in this tutorial.

EXAMPLE Exercise :

1. Let's assume we start with the Store_Information table shown above. What
does the table look like after the following SQL statement is executed?
INSERT INTO Store_Information VALUES ('San Jose',25,700,'Jan-10-1999');

2. Continuing with Question 1. What does the table look like after the following
SQL statement is executed?
INSERT INTO Store_Information (Manager_ID,Txn_Date,Sales) VALUES
(10,600,'Jan-11-1999');

3. Using the same table as above. What does the table look like after the
following SQL statement is executed?
INSERT INTO Store_Information ('Portland',30,650,'Jan-11-1999');

1. The table becomes,

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999
New York 500 Jan-10-1999
San Jose 25 700 Jan-10-1999
2. The table becomes,

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999
New York 500 Jan-10-1999
San Jose 25 700 Jan-10-1999
10 600 Jan-11-1999

3. The table becomes,

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999
New York 500 Jan-10-1999
San Jose 25 700 Jan-10-1999
10 600 Jan-11-1999

There is no change to the table as the SQL statement is not valid (it is missing
'VALUES').
Syntax

UPDATE can be used to modify one column at a time or multiple columns at a


time. The syntax for updating a single column is as follows:

UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";

The syntax for updating multiple columns is as follows:

UPDATE "table_name"
SET column_1 = [value1], column_2 = [value2], ...
WHERE "condition";

Examples

We use the following table for our examples.

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Example 1: Update a single column

We notice that the sales for Los Angeles on Jan-08-1999 is actually $500
instead 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 Txn_Date = 'Jan-08-1999';

The resulting table would look like

Table Store_Information
Store_Name Sales Txn_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 clause. 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.

Example 2: Update multiple columns

We notice that the 'San Diego' entry has the wrong Sales and TXN_Date
information. To fix it, we run the following SQL statement:

UPDATE Store_Information
SET Sales = 600, Txn_Date = 'Jan-15-1999'
WHERE Store_Name = 'San Diego';

The table now becomes,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 600 Jan-15-1999
Los Angeles 500 Jan-08-1999
Boston 700 Jan-08-1999

IMPORTANT: When using the UPDATE statement, pay special attention to


make sure that some type of filtering criteria is specified. Otherwise, the value
of all rows can be changed.
Exercises

1. Using the same Store_Information table right above, what data is in the
table after the following SQL statement is executed?
UPDATE Store_Information
SET Sales = 800
WHERE Store_Name = 'Boston';

2. Continuing to use the same table. What is the content of the table after the
following SQL statement is executed?
UPDATE Store_Information
SET Sales = 2000
WHERE Store_Name = 'Los Angeles' AND Txn_Date = 'Jan-10-1999';

3. Again using the same table. What is the content of the table after the
following SQL statement is executed?
UPDATE Store_Information
SET Sales = 1000;

Ans :

Data modified by the UPDATE statement is shown in red below.

1. Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 600 Jan-15-1999
Los Angeles 500 Jan-08-1999
Boston 800 Jan-08-1999

2. Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 600 Jan-15-1999
Los Angeles 500 Jan-08-1999
Boston 800 Jan-08-1999
There is no change to the table as no row satisfies the condition in
the WHERE clause.

3. Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1000 Jan-05-1999
San Diego 1000 Jan-15-1999
Los Angeles 1000 Jan-08-1999
Boston 1000 Jan-08-1999

Since there is no WHERE clause, all rows are updated.


he DELETE FROM statement in SQL is used to remove records from a table.

Please note that the DELETE FROM command cannot delete any rows of
data that would violate FOREIGN KEY or other constraints.

Syntax

The syntax for the DELETE FROM statement is as follows:

DELETE FROM "table_name"


WHERE "condition";

The WHERE clause is important here. Without specifying a condition, all


records from the table will be deleted.

"Condition" can be simple (such as "Sales > 500") or complex (such as from
the result of a subquery).

Examples

Two examples of how to use the DELETE FROM statement are shown below.

Example 1: DELETE FROM using a simple condition

We use the following table as the starting point.

Table Store_Information

Store_Name Sales Txn_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 decide not to keep any information on Los Angeles in this table. To


accomplish this, we type the following SQL:

DELETE FROM Store_Information


WHERE Store_Name = 'Los Angeles';

Now the table becomes,


Table Store_Information

Store_Name Sales Txn_Date


San Diego 250 Jan-07-1999
Boston 700 Jan-08-1999

Example 2: DELETE FROM using the results from a subquery

In Example 1, the criteria we use to determine which rows to delete is quite


simple. We can also use a more complex condition. Below is an example
where we use a subquery as the condition. Assume we have the following
two tables:

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Table Geography

Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego

We want to remove data for all stores in the East region


from Store_Information (assuming that a store is either in the East region or
the West region—it cannot be in more than one region). We use the following
SQL statement to accomplish this:

DELETE FROM Store_Information


WHERE Store_Name IN
(SELECT Store_Name FROM Geography
WHERE Region_Name = 'East');

Upon execution, the Store_Information table becomes,


Store_Name Sales Txn_Date
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999

If we leave out the WHERE clause in a DELETE FROM command, we will


delete all rows from the table. Most times, this is not what we intend to do. To
prevent this, it is a best practice in database management to always run the
corresponding SELECT statement first to make sure the rows selected are the
ones we intend to remove from the table. This can be done by
replacing "DELETE" with "SELECT *".

Exercises

For the questions below, we use the following table as the starting point:

Table Clients

Customer_ID Last_Name First_Name City Stat e Join_Date


2 Larry Kerr Seattle WA Oct-15-2001
5 Aaron Wallace Denver CO Oct-18-2001
6 Jayson Fortran Raleigh NC Oct-24- 2001
12 Jill Dobbs Buffalo NY Nov-15-2001
13 Lisa Yamaguchi San Diego CA Nov-15- 2001
20 Ally Smith Seattle WA Nov-25-2001
67 Teyu Lee Cupertino CA Jan-11-2002

1. Which of the following SQL statements is valid? (There may be more than
one answer)
a) DELETE * FROM Clients WHERE State = 'CO';
b) DELETE FROM Clients WHERE State = 'CO';
c) DELETE FROM Clients HAVING State = 'CO';
d) DELETE FROM Clients WHERE Customer_ID < 10;

2. How many rows are deleted after the following SQL statement is
executed?
DELETE FROM Clients WHERE State = 'CO';

3. What is the effect of the following SQL?


DELETE FROM Clients WHERE 1 = 1;
Ans :

1. b), d)

2. 1 row.

3. All rows are deleted from the table. This is because the condition in
the WHERE clause is true for all rows.
o add a column to a table using SQL, we specify that we want to change the
table structure via the ALTER TABLEcommand, followed by
the ADD command to tell the RDBMS that we want to add a column.

Syntax

The SQL syntax for ALTER TABLE Add Column is,

ALTER TABLE "table_name"


ADD "column_name" "Data Type";

Examples

Let's look at the example. Assuming our starting point is the Customer table
created 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 datetime

Example 1: Add one column to a table

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);


The resulting table structure is:

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 datetime
Gender char(1)

Note that the new column Gender becomes the last column in
the Customer table.

Example 2: Add multiple columns to a table

It is also possible to add multiple columns. For example, if we want to add a


column called "Email" and another column called "Telephone", we will type the
following:

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 datetime
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 ALTER TABLE Modify Column command. For Oracle and MySQL, the
SQL syntax for ALTER TABLE Modify Column is,

ALTER TABLE "table_name"


MODIFY "column_name" "New Data Type";

For SQL Server, the syntax is,

ALTER TABLE "table_name"


ALTER COLUMN "column_name" "New Data Type";

Let's look at the example. Assuming our starting point is the Customer table
created 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 datetime

Our goal is to alter the data type of the "Address" column to char(100). To do
this, 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)
Birth_Date datetime
Sometimes we want to change the name of a column. To do this in SQL, we
specify that we want to change the structure of the table using the ALTER
TABLE command, followed by a command that tells the relational database
that we want to rename the column. The exact syntax for each database is as
follows:

In 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
created 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 datetime

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 Server. Use sp_rename instead.
The resulting table structure is:

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 datetime
Sometimes we will wish to delete a column from an existing table in SQL. To
do this, we specify that we want to change the table structure via the ALTER
TABLE command, followed by a specification indicating that we want to
remove a column. The detailed syntax for each database is as follow:

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

ALTER TABLE "table_name"


DROP "column_name";

In Oracle and SQL Server, the syntax for ALTER TABLE Drop Column is,

ALTER TABLE "table_name"


DROP COLUMN "column_name";

Let's look at the example. Assuming our starting point is the Customer table
created 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 datetime

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;

The resulting table structure is:

Table Customer

Column Name Data Type


First_Name char(50)
Last_Name char(50)
Address char(50)
City char(50)
Country char(25)
NOT NULL Constraint

By default, a column can hold NULL. If you do not want to allow NULL value
in a column, you will want to place the NOT NULL constraint on this column.
The NOT NULL constraint specifies that NULL is not an allowable value.

For example, in the following statement,

CREATE TABLE Customer


(SID integer NOT NULL,
Last_Name varchar (30) NOT NULL,
First_Name varchar(30));

Columns "SID" and "Last_Name" cannot include NULL, while "First_Name"


can include NULL.

An attempt to execute the following SQL statement,

INSERT INTO Customer (Last_Name, First_Name) VALUES ('Smith', 'Ken');

will result in an error because this will lead to column "SID" being NULL,
which violates the NOT NULL constraint on that column.
DEFAULT Constraint

The DEFAULT constraint provides a default value to a column when


the INSERT INTO statement does not provide a specific value. For example, if
we create a table as below:

CREATE TABLE Student


(Student_ID integer Unique,
Last_Name varchar (30),
First_Name varchar (30),
Score Integer DEFAULT 80);

and execute the following SQL statement,

INSERT INTO Student (Student_ID, Last_Name, First_Name) VALUES (10,


'Johnson', 'Rick');

The table will look like the following:

Student_ID Last_Name First_Name Score


10 Johnson Rick 80

Even though we didn't specify a value for the "Score" column in the INSERT
INTO statement, it does get assigned the default value of 80 since we had
already set 80 as the default value for this column.
UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are distinct.

For example, in the following CREATE TABLE statement,

CREATE TABLE Customer


(SID integer UNIQUE,
Last_Name varchar (30),
First_Name varchar(30));

column "SID" has a UNIQUE constraint, and hence cannot include duplicate
values. Such constraint does not hold for columns "Last_Name" and
"First_Name". So, if the table already contains the following rows:

SID Last_Name First_Name


1 Johnson Stella
2 James Gina
3 Aaron Ralph

Executing the following SQL statement,

INSERT INTO Customer VALUES (3, 'Lee', 'Grace');

will result in an error because '3' already exists in the SID column, thus trying
to insert another row with that value violates the UNIQUE constraint.

Please note that a column that is specified as a primary key must also be
unique. At the same time, a column that's unique may or may not be a primary
key. In addition, multiple UNIQUE constraints can be defined on a table.

Вам также может понравиться