29
 Contents:-

Chapter7 SQL

Embed Size (px)

Citation preview

Page 1: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 1/29

 

Contents:-

Page 2: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 2/29

1. Data Definition in SQL

2. Queries in SQL

3. Insert, Delete and update

statements in SQL

4. Views in SQL

5. Specifying general constraints

as assertions

6. Specifying indexes

7. Embedded SQL

Page 3: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 3/29

SQL:

 The name SQL is derived from Structured Query Language. It

was first names SQUEL and was designed and implemented at

IBM as the interface for an experimental relational database

system. ANSI and ISO joined together to bring the standard

version of SQL called SQL-86 or SQL 1. Later SQL2 or SQL-92

was developed. SQL is considered as the standard for relational

databases. The reason is converting from one relational DBMS

to another is neither expensive nor time consuming becauseboth system follow same language standards. It is a

comprehensive database language. It has statements for data

definition, query and update. Hence it is both DDL and DML.

Data Definition in SQL:-

 The SQL2 commands for data definition are CREATE, ALTER and

DROP.

CREATE COMMAND:-

 The create command is used to specify a new relation by giving

it a name and specifying its attributes and constraints.

 The attributes are specified first and each attribute is given a

name, data type to specify its domain and any attribute

constraints. Each row represents one piece of data, and eachcolumn can be thought of as representing a component of that

piece of data. So, for example, if we have a table for recording

customer information, then the columns may include

information such as First Name, Last Name, Address, City,

Country, Birth Date, and so on. As a result, when we specify a

table, we include the column headers and the data types for

that particular column.

 The SQL syntax for CREATE TABLE is

Page 4: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 4/29

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 varchar(50),City char(50),Country char(25),Birth_Date date); 

Sometimes, we want to provide a default value for eachcolumn. A default value is used when you do not specify acolumn's value when inserting data into the table. To specify adefault value, add "Default [value]" after the data typedeclaration. 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 varchar(50) default 'Unknown',City char(50) default 'Mumbai',Country char(25),Birth_Date date) ;

 You can place constraints to limit the type of data that can go

into a table. Such constraints can be specified when the table isfirst created via the CREATE TABLE statement, or after thetable is already created via the ALTER TABLE statement.

Common types of constraints include the following:

NOT NULL Constraint: Ensures that a column cannot haveNULL value.

By default, a column can hold NULL. If you do not want to allow

NULL value in a column, you will want to place a constraint onthis column specifying that NULL is now not an allowable value.

Page 5: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 5/29

For example, in the following statement,

CREATE TABLE Customer(CID integer NOT NULL,

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

Columns "CID" and "First_Name" cannot include NULL, while"Last_Name" can include NULL. If we attempt to execute thefollowing SQL statement,

INSERT INTO Customer (Last_Name, First_Name) values(‘Chan’,’Jackie’);

It will result in an error because this will lead to column "CID"being NULL, which violates the NOT NULL constraint on thatcolumn.

DEFAULT Constraint: Provides a default value for a columnwhen none is specified. The DEFAULT constraint provides adefault value to a column when the INSERT INTO statementdoes not provide a specific value. For example, if we create atable as below:

CREATE TABLE Student(Student_ID integer Unique,Last_Name varchar (30),First_Name varchar (30),Score 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 inthe INSERT INTO statement, it does get assigned the default

Page 6: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 6/29

value of 80 since we had already set 80 as the default value forthis column. 

UNIQUE Constraint: Ensures that all values in a column are

different. The UNIQUE constraint ensures that all values in acolumn are distinct.

For example, in the following CREATE TABLE statement,

CREATE TABLE Customer(CID integer Unique,Last_Name varchar (30),First_Name varchar(30));

column "CID" has a unique constraint, and hence cannot includeduplicate values. Such constraint does not hold for columns"Last_Name" and "First_Name". So, if the table already containsthe following rows:

SID

Last_Name

First_Name

1 Johnson Stella

2 James Gina3 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 SIDcolumn, thus trying to insert another row with that valueviolates the UNIQUE constraint.

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

CHECK Constraint: Makes sure that all values in a columnsatisfy certain criteria. The CHECK constraint ensures that allvalues in a column satisfy certain conditions. Once defined, the

database will only insert a new row or update an existing row if 

Page 7: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 7/29

the new value satisfies the CHECK constraint. The CHECK constraint is used to ensure data quality.

For example, in the following CREATE TABLE statement,

CREATE TABLE Customer(CID integer CHECK (CID > 0),Last_Name varchar (30),First_Name varchar(30)); 

Column "CID" has a constraint -- its value must only includeintegers greater than 0. So, attempting to execute the followingstatement,

INSERT INTO Customer values ('-3','Gonzales','Lynn'); 

 This will result in an error because the values for CID must begreater than 0.

Primary Key Constraint: Used to uniquely identify a row inthe table. A primary key is used to uniquely identify each row in

a table. A primary key can consist of one or more fields on atable. When multiple fields are used as a primary key, they arecalled a composite key.

Primary keys can be specified either when the table is created(using CREATE TABLE) or by changing the existing tablestructure (using ALTER TABLE).

Below are examples for specifying a primary key when creatinga table:

MySQL:CREATE TABLE Customer(CID integer,Last_Name varchar(30),First_Name varchar(30),PRIMARY KEY (CID)); 

Oracle:

CREATE TABLE Customer(CID integer PRIMARY KEY,

Page 8: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 8/29

Last_Name varchar(30),First_Name varchar(30)); 

SQL Server:

CREATE TABLE Customer(CID integer PRIMARY KEY,Last_Name varchar(30),First_Name varchar(30)); 

Below are examples for specifying a primary key by altering atable:

MySQL:ALTER TABLE Customer ADD PRIMARY KEY (CID); 

Oracle:ALTER TABLE Customer ADD PRIMARY KEY (CID); 

SQL Server:ALTER TABLE Customer ADD PRIMARY KEY (CID); 

Note: Before using the ALTER TABLE command to add a primarykey, you'll need to make sure that the field is defined as 'NOT

NULL' -- in other words, NULL cannot be an accepted value forthat field.

Foreign Key Constraint: Used to ensure referential integrityof the data. A foreign key is a field (or fields) that points to theprimary key of another table. The purpose of the foreign key isto ensure referential integrity of the data. In other words, onlyvalues that are supposed to appear in the database arepermitted.

For example, say we have two tables, a CUSTOMER table thatincludes all customer data, and an ORDERS table that includesall customer orders. The constraint here is that all orders mustbe associated with a customer that is already in the CUSTOMERtable. In this case, we will place a foreign key on the ORDERStable and have it relate to the primary key of the CUSTOMERtable. This way, we can ensure that all orders in the ORDERStable are related to a customer in the CUSTOMER table. In otherwords, the ORDERS table cannot contain information on a

customer that is not in the CUSTOMER table.

Page 9: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 9/29

 The structure of these two tables will be as follows:

 Table CUSTOMER 

columnname characteristic

SIDPrimaryKey

Last_Name

First_Name

 Table ORDERS 

columnname

characteristic

Order_IDPrimaryKey

Order_Date

Customer_SID

Foreign Key

Amount

In the above example, the Customer_SID column in the ORDERStable is a foreign key pointing to the SID column in theCUSTOMER table.

Below we show examples of how to specify the foreign keywhen creating the ORDERS table:

MySQL:

CREATE TABLE ORDERS(Order_ID integer,Order_Date date,Customer_SID integer,Amount double,Primary Key (Order_ID),Foreign Key (Customer_SID) referencesCUSTOMER(SID)); 

Oracle:CREATE TABLE ORDERS

Page 10: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 10/29

(Order_ID integer primary key,Order_Date date,Customer_SID integer references CUSTOMER(SID),Amount double); 

SQL Server:

CREATE TABLE ORDERS(Order_ID integer primary key,Order_Date datetime,Customer_SID integer references CUSTOMER(SID),Amount double); 

Below are examples for specifying a foreign key by altering a

table. This assumes that the ORDERS table has been created,and the foreign key has not yet been put in:

MySQL:ALTER TABLE ORDERSADD FOREIGN KEY (customer_sid) REFERENCESCUSTOMER(SID); 

Oracle:

ALTER TABLE ORDERSADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID); 

SQL Server:ALTER TABLE ORDERSADD FOREIGN KEY (customer_sid) REFERENCESCUSTOMER(SID); 

ALTER Command:-

Once a table is created in the database, there are manyoccasions where one may wish to change the structure of thetable. 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. Common changes are

Page 11: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 11/29

ALTER TABLE Add Column

 The 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 created in the CREATE TABLE section:

 Table customer 

ColumnName

Data Type

First_Name char(50)

Last_Name char(50)

Addressvarchar(50)

City char(50)

Country char(25)

Birth_Date date

Our goal is to add a column called "Gender". To do this, we keyin:

MySQL: Oracle SQL ServerALTER TABLE customer ADD Gender char(1); 

Resulting table structure: Table customer 

ColumnName Data Type

First_Name char(50)

Last_Name char(50)

Addressvarchar(50)

City char(50)

Country char(25)

Birth_Date date

Page 12: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 12/29

Gender char(1)

Note that the new column Gender becomes the last column inthe customer table.

It is also possible to add multiple columns. For example, if wewant to add a column called "Email" and another column called"Telephone", we will type the following:

MySQL: Oracle SQL ServerALTER TABLE customer ADD (Email varchar(30),Telephone integer(20));

  The table now becomes: Tablecustomer 

ColumnName

Data Type

First_Name char(50)

Last_Name char(50)

Addressvarchar(50)

City char(50)

Country char(25)

Birth_Date date

Gender char(1)

Emailvarchar(30)

 Telephoneinteger(20)

ALTER TABLE Modify ColumnSometimes we need to change the data type of a column. To dothis, we use the ALTER TABLE Modify Column command. ForOracle and MySQL, the SQL syntax for ALTER TABLE ModifyColumn is,

ALTER TABLE "table_name"MODIFY "column 1" "New Data Type" 

Page 13: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 13/29

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 created in the CREATE TABLE section:

 Table customer 

ColumnName

Data Type

First_Name char(50)

Last_Name char(50)

Addressvarchar(50)

City char(50)

Country char(25)

Birth_Date date

Our goal is to alter the data type of the "Address" column to

varchar(100). To do this, we key in:

MySQL: Oracle ALTER TABLE customer MODIFY Address varchar(100); 

SQL Server:ALTER TABLE customer ALTER COLUMN Addressvarchar(100); 

Resulting table structure:

 Table customer 

ColumnName

Data Type

First_Name char(50)

Page 14: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 14/29

Last_Name char(50)

Addressvarchar(100)

City char(50)

Country char(25)

ALTER TABLE Rename Column

In MySQL, the SQL syntax for ALTER TABLE Rename Columnis

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 

ColumnName

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

Page 15: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 15/29

SQL Server:It is not possible to rename a column using the ALTER TABLEstatement in SQL Server. Use sp_rename instead.

Resulting table structure:

 Table customer 

ColumnName

Data Type

First_Name char(50)

Last_Name char(50)

Addr char(50)

City char(50)

Country char(25)

Birth_Date date

ALTER TABLE Drop Column

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 TABLEDrop Column is

ALTER TABLE "table_name"DROP COLUMN "column 1"

Let's look at the example. Assuming our starting point is the

"customer" table created in the CREATE TABLE section:

 Table customer 

ColumnName

Data Type

First_Name char(50)

Last_Name char(50)

Address char(50)

Page 16: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 16/29

City char(50)

Country char(25)

Birth_Date date

Our goal is to drop the "Birth_Date" column. To do this, we keyin:

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 

ColumnName

Data Type

First_Name char(50)

Last_Name char(50)

Address char(50)

City char(50)

Country char(25)

DROP Command

Sometimes we may decide that we need to get rid of a table inthe database for some reason. In fact, it would be problematic if we cannot do so because this could create a maintenancenightmare for the DBA's. Fortunately, SQL allows us to do it, aswe can use the DROP TABLE command. The syntax for DROPTABLE is

DROP TABLE "table_name"

So, if we wanted to drop the table called customer that wecreated in the CREATE TABLE section, we simply type

DROP TABLE customer.

Page 17: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 17/29

Views in SQL

A view is a virtual table. A view consists of rows and columns just like a table. The difference between a view and a table is

that views are definitions built on top of other tables (or views),and do not hold data themselves. If data is changing in theunderlying table, the same change is reflected in the view. Aview can be built on top of a single table or multiple tables. Itcan also be built on top of another view.

Views offer the following advantages:

1. Ease of use: A view hides the complexity of the database

tables from end users. Essentially we can think of views as alayer of abstraction on top of the database tables.

2. Space savings: Views takes very little space to store, sincethey do not store actual data.

3. Additional data security: Views can include only certaincolumns in the table so that only the non-sensitive columns areincluded and exposed to the end user. In addition, somedatabases allow views to have different security settings, thushiding sensitive data from prying eyes.

 The syntax for creating a view is as follows:

CREATE VIEW "VIEW_NAME" AS "SQL Statement"

"SQL Statement" can be any of the SQL statements

Say we have the following table:

TABLE Customer (First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date date)

Page 18: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 18/29

and we want to create a view called V_Customer that containsonly the First_Name, Last_Name, and Country columns from thistable, we would type in,

CREATE VIEW V_CustomerAS SELECT First_Name, Last_Name, CountryFROM Customer

Now we have a view called V_Customer with the followingstructure:

View V_Customer (First_Name char(50),Last_Name char(50),

Country char(25))

We can also use a view to apply joins to two tables. In this case,users only see one view rather than two tables, and the SQLstatement users need to issue becomes much simpler. Let's saywe have the following two tables:

 Table Store_Information

store_name

Sales Date

LosAngeles

$1500 Jan-05-1999

San Diego $250 Jan-07-1999

LosAngeles

$300 Jan-08-1999

Boston $700 Jan-08-1999

 Table Geography  

region_name

store_name

East Boston

East New York

West Los

Page 19: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 19/29

Angeles

West San Diego

and we want to build a view that has sales by region

information. We would issue the following SQL statement:

CREATE VIEW V_REGION_SALESAS SELECT A1.region_name REGION, SUM(A2.Sales)SALESFROM Geography A1, Store_Information A2WHERE A1.store_name = A2.store_nameGROUP BY A1.region_name

 This gives us a view, V_REGION_SALES, that has been definedto store sales by region records. If we want to find out thecontent of this view, we type in,

SELECT * FROM V_REGION_SALES

Result:

REGION

SALES

East$700

West$2050

Queries in SQL

 The most basic SQL query structure is SELECT.

Syntax:- SELECT "column_name" FROM "table_name"

 To illustrate the above example, assume that we have thefollowing table:

 Table Store_Information

store_name

Sales Date

Los $150 Jan-05-

Page 20: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 20/29

Angeles 0 1999

San Diego$250 Jan-07-1999

LosAngeles $300

 Jan-08-1999

Boston $700 Jan-08-1999

 To select all the stores in this table, we key in,

SELECT store_name FROM Store_Information

Result:store_name

LosAngeles

SanDiego

LosAngeles

Boston

Multiple column names can be selected, as well as multipletable names.

 The SELECT keyword allows us to grab all information from acolumn (or columns) on a table. This, of course, necessarilymeans that there will be redundancies. What if we only want toselect each DISTINCT element? This is easy to accomplish inSQL. All we need to do is to add DISTINCT after SELECT. Thesyntax is as follows:

SELECT DISTINCT "column_name" FROM "table_name"

For example, to select all distinct stores in TableStore_Information,

 Table Store_Information

store_name

Sales Date

Page 21: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 21/29

LosAngeles

$1500 Jan-05-1999

San Diego $250 Jan-07-1999

LosAngeles

$300 Jan-08-1999

Boston $700 Jan-08-1999

We key in, SELECT DISTINCT store_name FROMStore_Information

Result:store_name

LosAngeles

SanDiego

Boston

Next, we might want to conditionally select the data from atable. For example, we may want to only retrieve stores withsales 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_Information,

 Table Store_Information

store_na

me

Sales Date

Los $150Jan-05-

Page 22: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 22/29

Angeles 01999

San Diego $250 Jan-07-1999

LosAngeles $300

 Jan-08-1999

Boston $700 Jan-08-1999

We key in, SELECT store_nameFROM Store_InformationWHERE Sales > 1000

Result:

store_name

LosAngeles

Insert, Delete and update

statements in SQL

In SQL, there are essentially basically two ways to INSERT datainto a table: One is to insert it one row at a time, the other is toinsert multiple rows at a time.

INSERT INTO VALUES

 The syntax for inserting data into a table one row at a time is asfollows:

INSERT INTO "table_name" ("column1", "column2", ...)VALUES ("value1", "value2", ...)

Assuming that we have a table that has the following structure,

 Table Store_Information

ColumnName

Data Type

store_name char(50)

Page 23: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 23/29

Sales float

Date datetime

If we wish 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. We will henceuse 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 multiplerows into a table. Unlike the previous example, where we inserta single row by specifying its values for all columns, we now usea SELECT statement to specify the data that we want to insertinto the table. This means that we are using information fromanother table. 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 caneasily contain WHERE, GROUP BY , and HAVING clauses, aswell 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 youalready know that the source data resides in the

Sales_Information table, we'll type in:

INSERT INTO Store_Information (store_name, Sales,Date)SELECT store_name, Sales, DateFROM Sales_InformationWHERE Year(Date) = 1998

UPDATE COMMAND:-

Page 24: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 24/29

Once there's data in the table, we might find that there is aneed to modify the data. To do so, we can use the UPDATEcommand. 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

LosAngeles

$1500 Jan-05-1999

San Diego $250 Jan-07-1999

LosAngeles

$300 Jan-08-1999

Boston $700 Jan-08-1999

and we notice that the sales for Los Angeles on 01/08/1999 isactually $500 instead of $300, and that particular entry needsto be updated. To do so, we use the following SQL query:

UPDATE Store_InformationSET 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

LosAngeles $1500 Jan-05-1999

Page 25: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 25/29

San Diego $250 Jan-07-1999

LosAngeles

$500 Jan-08-1999

Boston $700 Jan-08-1999

In this case, there is only one row that satisfies the condition inthe WHERE clause. If there are multiple rows that satisfy thecondition, all of them will be modified. If no WHERE clause isspecified, all rows will be modified.

It is also possible to UPDATE multiple columns at the same

time. The syntax in this case would look like the following:

UPDATE "table_name"SET column_1 = [value1], column_2 = [value2]WHERE {condition} 

DELETE Command:

Sometimes we may wish to use a query to remove records from

a table. To do so, we 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 asbelow:

 Table Store_Information

store_name

Sales Date

LosAngeles

$1500 Jan-05-1999

San Diego $250 Jan-07-1999

Los

Angeles $300

 Jan-08-

1999

Page 26: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 26/29

Boston $700 Jan-08-1999

and we decide not to keep any information on Los Angeles in

this table. To accomplish this, we type the following SQL:

DELETE FROM Store_InformationWHERE store_name = "Los Angeles"

Now the content of table would look like,

 Table Store_Information

store_name Sales Date

San Diego$25

0 Jan-07-1999

Boston$70

0 Jan-08-1999

Specifying general constraints as

assertionsIn SQL2, users can specify more general constraints—those that

do not fall into any of the categories through declarative

assertions, using the CREATE ASSERTION statement of the

DDL. Each assertion is given a constraint name and is specified

via a condition similar to the WHERE clause of an SQL query.

For example, to specify the constraint that "the salary of an

employee must not be greater than the salary of the manager of 

the department that the employee works for" in SQL2, we can

write the following assertion:

CREATE ASSERTION SALARY_CONSTRAINT

CHECK  ( NOT EXISTS ( SELECT * FROM EMPLOYEE E,

Page 27: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 27/29

EMPLOYEE M,

DEPARTMENT D

WHERE E.SALARY > M.SALARY AND E.DNO=D.DNUMBER

AND D.MGRSSN=M.SSN));

 The constraint name SALARY_CONSTRAINT is followed by the

keyword CHECK, which is followed by a condition in

parentheses that must hold true on every database state for the

assertion to be satisfied. The constraint name can be used laterto refer to the constraint or to modify or drop it. The DBMS is

responsible for ensuring that the condition is not violated. Any

WHERE-clause condition can be used, but many constraints can

be specified using the EXISTS and NOT EXISTS style of 

conditions. Whenever some tuples in the database cause the

condition of an ASSERTION statement to evaluate to FALSE, theconstraint is violated.  The constraint is satisfied by a

database state if  no combination of tuples in that database

state violates the constraint.

Embedded SQL

SQL provides a powerful declarative query language. However,

access to a database from a general-purpose programminglanguage is required because,

o SQL is not as powerful as a general-purposeprogramming language. There are queries thatcannot be expressed in SQL, but can be programmedin C, Fortran, Pascal, Cobol, etc.

o Nondeclarative actions -- such as printing a report,interacting with a user, or sending the result to a GUI

-- cannot be done from within SQL.

Page 28: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 28/29

 The SQL standard defines embedding of SQL as embedded SQLand the language in which SQL queries are embedded isreferred as host language. Embedded SQL is a method of combining the computing power of a programming language 

and the database manipulation capabilities of SQL. The result of the query is made available to the program one tuple (record)at a time.

 To identify embedded SQL requests to the preprocessor, we useEXEC SQL statement:

EXEC SQL embedded SQL statement END-EXEC

Note: A semi-colon is used instead of END-EXEC when SQL is

embedded in C or Pascal. Embedded SQL can execute any validupdate, insert, or delete statements.

Page 29: Chapter7 SQL

8/6/2019 Chapter7 SQL

http://slidepdf.com/reader/full/chapter7-sql 29/29

Specifying indexes

ALTER TABLE Add IndexALTER TABLE Drop IndexALTER TABLE Add Constraint

ALTER TABLE Drop Constraint