0% found this document useful (0 votes)
17 views25 pages

Chapter 7 The SQL Language

Chapter 7 covers the Structured Query Language (SQL), detailing its purpose in querying and modifying database structures. It introduces key components such as Data Definition Language (DDL), Data Manipulation Language (DML), and various data types and operators used in SQL. The chapter also explains how to create, modify, and manage database objects, including constraints and commands for altering database structures.

Uploaded by

sead4239.se
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views25 pages

Chapter 7 The SQL Language

Chapter 7 covers the Structured Query Language (SQL), detailing its purpose in querying and modifying database structures. It introduces key components such as Data Definition Language (DDL), Data Manipulation Language (DML), and various data types and operators used in SQL. The chapter also explains how to create, modify, and manage database objects, including constraints and commands for altering database structures.

Uploaded by

sead4239.se
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 7 The SQL Language

Objectives

After going through this UNIT, you will be in a position to:

✓ Demonstrate on Structured Query Language


✓ Create and Modify Database Objects
✓ Populate Objects with Data
✓ Manipulate Data
✓ Relate and Share Data
✓ Explore the methods of Querying

Structure

The SQL Language

Introduction

Datatypes and Operators

Data Definition Language

Constraints Specifications

Data Manipulation Language

SELECT – SQL in detail

Joins

Complex Queries

Views
Introduction

The Structured Query Language (SQL) is a database query language introduced by IBM in
the earlier 1970’s and standardized by ANSI later. The purpose of the language is to create
a platform to query and modify database structures. SQL is a version of Relational
Calculus, a high level, declarative query language.

There are four categories of Query Language, namely


1. Data Definition Language (DDL)
2. Data Manipulation Language (DML)
3. Data Control Language (DCL)
4. Transaction Control Language (TCL)

The Data Definition Language (DDL) statements are used to create or modify database
structure or schema. The Data Manipulation Language (DML) is used to manage data
within the schema objects. The Data Control Language (DCL) is used to GRANT or
REVOKE privileges to users in order to access data in different security levels. The
Transaction Control Language (TCL) is used to control the transactions made by the Data
Manipulation Statements, by creating save points and committing or rolling back
transactions as required. We will discuss about the first two categories here.

In RDBMS, data is represented as tables or relation. A table constitutes of rows and


columns, where rows represent records or tuples and columns represent attributes of the
table.

A table is uniquely identified by its name, which can be a combination of alphanumeric


characters. Space is not allowed in a name and the special character “_” (under score) alone
is used to indicate the space. Every attribute is represented by a name and datatype. A table
can have a maximum of 254 columns to represent data. The usage of datatypes is described
below.
Section 1: Datatypes and Operators

Section Objectives

At the end of this section, you will be able to:

✓ Explore on different types of datatypes and their usage


✓ Understand arithmetic, relational, logical and other operators
7.1.1 Datatypes
Inspite of the wide range of datatypes available, we shall discuss some of the basic
datatypes here and are categorized below. The maximum extent of the datatypes is
specified according to the latest version (say Oracle 11g).
- Character Datatypes
- Numeric Datatypes
- Date Datatypes
- Large Object Datatypes

[Link] Character Datatypes:

Data Type Extent Explanation


Syntax (if applicable)
char(size) Maximum size of Where size is the number of characters
2000 bytes. to store. Fixed-length strings. Space
padded.
nchar(size) Maximum size of Where size is the number of characters
2000 bytes. to store. Fixed-length NLS string
Space padded.
nvarchar2(size) Maximum size of Where size is the number of characters
4000 bytes. to store. Variable-length NLS string.
Saves memory by using the unused
allocated memory.
varchar2(size) Maximum size of Where size is the number of characters
4000 bytes. to store. Variable-length string.
Saves memory by using the unused
allocated memory.
long Maximum size of Variable-length strings. (backward
2GB. compatible)
raw Maximum size of Variable-length binary strings
2000 bytes.
long raw Maximum size of Variable-length binary strings.
2GB. (backward compatible)

7.1.1.2Numeric Datatypes:

Data Type Extent Explanation


Syntax (if applicable)
number(p,s) Precision can range from 1 to 38. Where p is the precision and s
is the scale.

Example: number(7,2) is a
number that has 5 digits before
the decimal and 2 digits after
the decimal.
integer Ranges between -32767 and 32768 Occupies a maximum of 2
bytes.
[Link] Date Datatypes:

Data Type Extent Explanation


Syntax (if applicable)
Date A date between Jan 1, Occupies a maximum of 9
4712 BC and Dec 31, bytes.
9999 AD.
timestamp (fsp) fsp stands for fractional Includes year, month, day,
seconds precision, which hour, minute, and seconds.
must be a number between
0 and 9. (default is 6) Example: timestamp(6)

interval year year precision is the Time period stored in years


(year precision) number of digits in the and months.
to month year. (default is 2)
Example:
interval year(4) to month

[Link] Large Object Datatypes:

Data Extent Explanation


Type (if applicable)
Syntax
Bfile Maximum file size of 264-1 bytes. File locators that point to a
binary file on the server file
system (outside the database).
blob Store up to (4 gigabytes -1) * (the Stores unstructured binary
value of the CHUNK parameter large objects.
of LOB storage).
clob Store up to (4 gigabytes -1) * (the Stores single-byte and multi-
value of the CHUNK parameter byte character data.
of LOB storage) of character
data.
nclob Store up to (4 gigabytes -1) * (the Stores unicode data.
value of the CHUNK parameter
of LOB storage) of character text
data.
7.1.2Operators
[Link] Relational Operators
Some of the relational operators used in SQL are listed below:

Operator Description Example


= Equal to Regno = 101
> Greater than Total_Marks > 100
< Less than Salary < 10000
>= Greater than or equal to Mark1 >= 50
<= Less than or equal to Mark2 <=50
!= , <>, ^= Not equal to Mark1 <> 0
IS NULL To check whether the value is null Regno is null
IN To represent a value in a collection Regno in (100, 101, 102)
City in (‘Addis’, ‘Jimma’)
BETWEEN To represent a range of values Avg_marks between 100
and 200
Bill_date between ’01-Sep-
2010’ and ’11-Sep-2010’
LIKE To specify a similar character string City like (‘A%’)
City like (‘%a’)
Name like (‘Jo_ _’)

The logical operators say AND, OR and NOT are used respectively in SQL statements.
The wild card character ‘%’ denotes unlimited number of characters where as ‘_’ denotes
the specific number of characters.
Section 2: Data Definition Language

Section Objectives
At the end of this section, you will be able to:

✓ Create database objects


✓ Modify the attribute datatypes
✓ Include or remove attributes
✓ Rename attributes and database objects
✓ Delete database objects
✓ Reallocate memory for database objects
✓ Make comments

7.2 Data Definition Language


The Data Definition Language is used to create, modify or destroy database structures.
Following are the commands of DDL.
 CREATE – To create objects in the database
 ALTER – alters structure of the database
 DROP – deletes objects of the database
 TRUNCATE - remove all records from a table, including all spaces
allocated for the records are removed
 COMMENT – add comments to the data dictionary
 RENAME – renames an object

Here are some conditions that are to be notified before executing SQL Commands in the
editor and for understanding the text given the following sections.
- Every statement should end with a semicolon
- There should not be spaces in between names
- String and Date values are enclosed within single quotes
- Keywords are indicated in uppercase for understanding purposes
- Square brackets [], indicate optional provisions
- There is no difference between lower case and upper case in specifying table
or column names.
- All commands are executable at the SQL prompt

7.2.1 CREATE Command


A table definition is made through a CREATE command. We will see the syntax,
example and possible requirements for a creating a table.
Syntax:
CREATE TABLE <tablename> (
<column 1> <data type>,
.........
<column n> <data type>
);
Example:
Q1> create table Employee ( Emp_id number(4),
Emp_Name varchar2(30),
Department varchar2(20),
Designation varchar2(20));
It is necessary to identify the requirements of the table before we create them. The
following can be a checklist while creating tables.
✓ What are the attributes of the tuples to be stored?
✓ What are the data types of the attributes?
✓ Should varchar2 be used instead of char?
✓ Which columns build the primary key?
✓ Which columns do (not) allow null values?
✓ Which columns do (not) allow duplicates?
✓ What are constraints to be imposed on the table?
7.2.2 ALTER Command

The Alter command is used to modify the structure of the table. The command helps to
 To include new columns
 To modify column width
 To modify column datatype (extension of width and conversion of datatype from
numeric to alphanumeric and not viceversa)
 To rename column names
 To drop columns
 To introduce constraints

Syntax for Inclusion:


ALTER TABLE < Table_Name > ADD
(Column1 datatype, ……, Column n datatype);

Syntax for Modification:


ALTER TABLE < Table_Name > MODIFY
(Column1 datatype, ……, Column n datatype);

Syntax for Renaming Columns:


ALTER TABLE < Table_Name > RENAME COLUMN
<old_name> TO <new_name>;

Syntax for Dropping:


ALTER TABLE < Table_Name > DROP COLUMN <column names>;

Examples:
Q2> Alter table Employee Add
(Date_of_join Date, Salary number(8,2), Increment number(3,2));
Q3> Alter table Employee Modify (Salary number (10, 2));
Q4> Alter table Employee Rename Column Emp_Id To Employee_ID
Q5> Alter table Employee Drop Column Increment
7.2.3 DROP Command

The Drop Command helps to delete the table structures. When a drop command is
executed, the table structure and the table contents are together deleted. If the tables are
connected with referential integrity (i.e. if foreign key exists – discussed in the next
section), then the CASCADE CONSTRAINTS option helps to remove the relationship and
delete tables.

Syntax:
DROP TABLE <Table_Name> [CASCADE CONSTRAINTS];
Example:
Q6> Drop Table Employee;

7.2.4 TRUNCATE Command


Sometimes we may want to get rid of the data, but not the data itself. For the purpose of
deleting all records, but not the table structure, we would prefer to use the TRUNCATE
Command.

Syntax:
TRUNCATE TABLE <table_name>;
Example:
Q7> Truncate table Employee;
7.2.5 Comment
Comments are made in between statements in order to give short descriptions and the
characters within the comment are ignored by the database server. Single line comments
are made by giving double hyphens (--) and the multiple line comments are enclosed
between /* and */.

Example:
SQL> create table dummy(
2 -- to demonstrate
3 id number(3),
4 /* example
5 for commenting */
6 name varchar2(20));
7.2.6 RENAME Command
The Rename Command is used to rename tables. Once if the table is renamed, the older
name no longer exists.
Syntax:
RENAME <old_table_name> TO <new_table_name>;
Example:
Q8> Rename Employee To Employee_details;
Section 3: Constraints Specification

Section Objectives

At the end of this section, you will be able to:

✓ Explore the method of specifying constraints for database columns


✓ Relate and share data between tables using constraints
✓ Specify value-specific constraints for attributes
✓ Ensure integrity of data using constraints

7.3 Constraints Specification

Some of the constraints used are listed below:

Constraint Description Specification


Not Null if an attribute value should be non- Column level Specification
empty
Null if an attribute value should be empty Column level Specification
Unique if an attribute must have non- Column level Specification
duplicate values
Primary Key - if the attribute must be both Both Column level and table
non-empty and unique; level Specifications
- there can be only one
primary key for a given
table;
- a primary key can be
constituted of one or more
number of columns of the
same table
Foreign Key To create relationship between master Both Column level and table
and child tables using a common level Specifications
attribute of same datatype
Check To specify value limits for attributes Both Column level and table
level Specifications

The Constraints can be specified in two ways namely, Column level Specification and
Table level Specification. In Column level specification, the respective constraint is
specified along with the attribute declaration. In the table level specification, constraints
are declared at the end, after all the attribute listings get over. The constraints either be
given constraints name or can be specified without names. We find that Not Null and
Unique constraints can be specified only in the column level.
Constraints specification is made either when the table is created or can be included to the
table later with the help of ALTER … ADD or ALTER … MODIFY commands.
Syntax using CREATE Command:

CREATE TABLE <table> (


<column 1> <data type> [NOT NULL] [UNIQUE] [PRIMARY KEY]
[column level constraint specification],
.........
<column n> <data type> [NOT NULL] [UNIQUE]
[<column level constraint specification>],

[<table level constraint(s) specification>]


);

Syntax using ALTER Command:

ALTER TABLE <table_name> ADD


(Column1 datatype [<column level constraint specification>],
……….
Column n datatype [<column level constraint specification>]
);
ALTER TABLE <table_name> ADD CONSTRAINT <constraint_name>
<constraint_specification>;
7.3.1 Specifying Not Null, Unique and Primary Key Constraints
Let us see how we can impose the not null, unique and primary key constraints with some
examples.

Column level Specification:


Q9> Create table Employee ( Emp_id number(4) primary key,
Emp_Name varchar2(30) not null,
Department varchar2(20),
Designation varchar2(20),
Date_of_join Date,
Salary number(8,2));

The same table with constraints can be defined as follows, with a constraint name. The
advantage of specifying a constraint name is that we can delete the constraint, when we
donot need it.

Q10> create table Employee ( Emp_id number(4) CONSTRAINT cons_pk primary key,
Emp_Name varchar2(30) not null,
Department varchar2(20),
Designation varchar2(20),
Date_of_join Date,
Salary number(8,2));

Following command helps us to delete the constraint created.


Q11> Alter table Employee Drop Constraint cons_pk;
It follows the syntax given below.
ALTER TABLE <table_name> DROP CONSTRAINT <constraint_name>;
Table Level Specification:
We can even create tables with constraints with table level specification as in the following
example.
Q12> Create table Department ( Dept_id char(4),
Dept_Name varchar2(20),
Dept_Head varchar2(30),
Primary Key (Dept_id));
Suppose if the table is created as follows without any constraints, the constraints can be
included using ALTER command as described below.
Q13> Create table Stock (prod_id number(3),
prod_name varchar2(10),
quantity number(3),
rate_unit number(6,2));
Q14> Alter table Stock Modify (prod_name varchar2(10) not null,
quantity number(3) not null);
Q15> Alter table Stock Add Constraint Cons_pk_Stock
Primary Key (prod_id);

7.3.2 Specifying a Foreign Key Constraint


A foreign key constraint helps establishing relationship between Master and Child tables.
If a table (master) contains the major information and other tables (Children) containing
other relevant information, then reference to the master table is made by the Foreign Key.
This relationship is otherwise called Referential Integrity
For this purpose, a common column is identified, which can connect both the tables. It is
mandatory that the common column must be a primary key of the master table and foreign
key of the child table. For referential integrity to hold, any column in the child table that is
declared as a foreign key can contain only values from a master table's primary key. For
instance, deleting a record from master table that contains a value referred to by a foreign
key in a child table, would break referential integrity.
Let us consider an example where Employee_details and Employee_Salary are the master
and child tables respectively. The attribute Emp_Code is the key for relating tables. We can
define the respective tables with referential integrity as follows.
Master Table Definition:
Q16> Create table Employee_details
( Emp_Code number(4) CONSTRAINT cons_pk primary key,
Emp_Name varchar2(30) not null,
Department varchar2(20),
Designation varchar2(20));

Child Table Definition: (Column Level Specification)


Q17> Create table Employee_Salary
( Emp_Code number(4) references Employee_details(Emp_Code),
Basic_Salary number(8,2) not null,
HRA number(4,2),
TA number(4,2),
DA number(4,2),
Tax number(5,2),
Net_Pay number(10,2));

The same table can be specified in the table level, with a constraint name as follows.
Q18> Create table Employee_Salary
( Emp_Code number(4),
Basic_Salary number(8,2) not null,
HRA number(4,2),
TA number(4,2),
DA number(4,2),
Tax number(5,2),
Net_Pay number(10,2),
Constraint cons_fk Foreign Key(Emp_Code) references
Employee_details(Emp_Code)
);

7.3.3 Specifying Check Constraints

The Check constraint helps to impose special conditions on column values before
insertion. It prohibits accepting data that violates the condition specified. Let us consider
some examples.
Check constraints are used with the following restrictions.
 The condition must be specified on a column
 The condition must be a Boolean expression
 The condition can relate two columns of the same table
 While comparing two columns of the same row, a table level constraint specification
must be followed
 Two columns of different tables cannot be compared
 Two rows cannot be compared
 The condition cannot contain subqueries or other keywords like SYSDATE, UID etc.

The following Create Query ensures that no employee gets salary more than 50,000 Birr,
during insertion of records.

Q19> Create table Employee ( Emp_id number(4) primary key,


Emp_Name varchar2(30) not null,
Department varchar2(20),
Designation varchar2(20),
Date_of_join Date,
Salary number(8,2)
Check (Salary < 50000));

Q20> Create table Marks_details


( regno number(3) primary key,
Name varchar2(20) not null,
Course1_mark number(3),
Course2_mark number(3),
Check ( Course1_mark between 0 and 100),
Check ( Course2_mark between 0 and 100));

Here the table ensures the course marks to be between 0 and 100. We shall see how we
can compare different columns of the same table in the following example.
Q21> Create table Product_details
( Product_id char(3) primary key,
Product_name varchar2(20) not null,
Units_stock number(3),
Sales_rate number(10,2),
Purchased_rate number(10,2),
Check ( Purchased_rate < Sales_rate));

In the above-said example, we check that the purchased rate of the product does not
exceed the rate for sale, which may result in loss otherwise.
Section 4: Data Manipulation Language

Section Objectives
At the end of this section, you will be able to:
✓ Insert new records to database objects
✓ Modify the attribute values
✓ Delete one or more records with filter conditions
✓ Retrieve data using filters

7.4 Data Manipulation Language


Data Manipulation Language comprises the 'SQL-data change' statements, which modify
stored data but not the schema or database objects. In other words, DML statements are
used to manipulate the data in the database. This is done either by retrieving information
from existing rows, entering new rows, changing existing rows or removing unwanted rows
from tables in the database.
Therefore the DML commands are

✓ INSERT
✓ UPDATE
✓ DELETE
✓ SELECT
7.4.1 INSERT Command
The INSERT Command helps to insert a new record onto the database. We can insert one
or more records using parameters to the existing table structures.
Syntax 1
INSERT INTO
<table_name> (Column_name1, Column_name2, …., Column_name n)
VALUES (Column_value1, Column_value2, …., Column_value n);
Syntax 2
INSERT INTO <table_name>
VALUES (Column_value1, Column_value2, …., Column_value n);
Syntax 3
INSERT INTO
<table_name> (<column_name_listings>)
VALUES (&value1, &value2, …., &value n);
Syntax 4
INSERT INTO <table_name>
VALUES (&value1, &value2, …., &value n);
The Syntax 1 helps in inserting values to the selective columns of the table structure. We
can specify the column names to which we prefer to insert and their respective values after
the VALUES keyword, as in the same order of the column listings.
If we want to insert values to all columns of the table, we can use the syntax 2.
If we would to like to insert more number of records, we can make use of statement with
parameter, which can be repeatedly executed for further insertions. Syntax 3 and Syntax 4
are respectively used to insert selective columns with parameter and all columns with
parameter.
We shall see some examples for the insert statement.
Examples:
Q22> Insert into employee (emp_id, emp_name) Values (101, ‘Yusuf’);
Q23> Insert into employee values (102, ‘Mohammed’, ‘CS’, ‘Lecturer’);
Q24> Insert into employee (emp_id, emp_name, department)
Values (&id, ‘&name’, ‘&dept’);
Q25> Insert into employee values ( &eid, ‘&ename’, ‘&dept’, ‘&desig’);
The above-said insert queries are assumed to insert values onto table with columns emp_id,
emp_name, department and designation (as defined in Q1). Q22 and Q24 insert values for
the columns emp_id and emp_name alone, leaving the department and designation
columns null (which means the query sets a null value for the unspecified columns).
Note: If we require filling these null columns, we need to use an UPDATE command to
reset or modify the null values.
Parameters are none but the user-defined variable names with a special character
ampersand ‘&’ preceding them. We note that the String or Date value parameters are
enclosed within single quotes.
In order to re-execute the statements with parameters, we shall specify a back slash ‘/’, in
the SQL prompt, which repeats the execution of the previous statement. (This command is
SQL-Plus Editor-Specific).
The following can be a check list while performing an INSERT statement.
 When inserting a row of data in a table, there must be a value for every
NOT NULL constrained column.
 All character strings and dates must appear in quotes in the list of values
of the INSERT statement
 The column list may be omitted if all columns in a table will be populated.
The values must however be listed in the columns’ default order.
7.4.2 UPDATE Command
The UPDATE Command is used to modify or reset values of the existing records, which
are already inserted using INSERT Command. It also resets the NULL values with new
values.
Update Command can affect either one record or many records at a time. If the Update
Command has no condition, then the command is applied to all records of the table. If a
condition is specified, the command is applied to only the set of records filtered by the
condition specified. The condition may filter one or many records.
Syntax:

UPDATE <table_name> SET <column1> = <new_value1>


[ , <column2> = <new_value2>
, ….. ,
, <column N> = <new_value N> ]
[ WHERE <condition>] ;

Example:

Q26> Update Employee Set Department = ‘History’, Designation = ‘Instructor’


Where Emp_id = 101;
Q27> Update Employee Set Salary = Salary + (0.20 * Salary);

Here we find that Q26 includes or resets the null values of the employee record, whose
employee id is 101. The condition “Where Emp_id = 101” has filtered the specific single
record and helps in modifying the respective record.

In Q27, the command applies to all records of the table, by replacing the Salary column
values with an increment of 20%.
7.4.3 DELETE Command
The Delete Command helps to delete one, some or all records of the table. If a condition is
specified, the records filtered by the condition are deleted. If no condition is specified, then
all records of the table are completely deleted, leaving the table structure unaffected, which
can be repopulated.
Syntax:
DELETE FROM <table_name> [WHERE <conditon>];
Example:
Q28> Delete From Employee Where department = ‘History’;
Q29> Delete From Employee Where Emp_id = 103;
Q30> Delete From Employee;
Here we find that Q28 deletes all employees who belong to “History” department, where
as Q29 deletes only one employee detail, whose employee id is 103 and Q30 deletes all the
records of the table.

7.4.4 SELECT – SQL in Detail


The Select Command helps in retrieving one or more records by specifying or not
specifying the filtering condition. There are more other options available in the select
command which makes the retrieval effective. We shall see them one by one with
examples.
Syntax:
SELECT *| <column_listings> | <expression> FROM <table_name>
[WHERE <condition>] [ORDER BY <column_name> [ASC| DESC]]
[GROUP BY <Column_name>] [HAVING <condition>
[<set operator> SELECT_SQL];

Examples:
Q31> Select * from Employee;
Q32> Select emp_name, Department from Employee;
Q33> Select * from Employee where Salary >10000;

Q34> Select * from Employee where Department = ‘CS’


and Designation = ‘Lecturer’;
Q35> Select * from Employee where emp_id in (101, 102, 103);
Q36> Select distinct emp_name from Employee;
Q37> Select unit_price * quantity from purchase_bill;
Q38> Select unit_price * quantity “Total_Amount” from purchase_bill;

Here Q31 retrieves all the records of the Employee table. Q32 retrieves all records but (only
the column values) the employee names with their departments alone. Q33 retrieves the
employee details whose salary is greater than 10,000 Birr. Q34 retrieves the employee
details that belong to the department “Computer Science” and with the designation
“Lecturer”. Q35 retrieves the employee details whose employee id is either 101 or 102 or
103.
Q36 retrieves the emploees’ names without duplication. The DISTINCT clause helps to
eliminate the duplicate records, if any. Q37 uses an expression “unit_price * quantity” in
order to find the total_amount of the purchased product. Q38, though computes as that of
Q37, it provides a label “Total_Amount” to the computed output. The label can be given
within double quotes or without quotes.
For the different data types supported in Oracle, several operators and functions are also
provided. We are just mentioning them for the reader’s practice.
 For numbers: abs, cos, sin, exp, log, power, mod, sqrt, +,−, _, /, . .
 For string: chr, concat(string1, string2), lower, upper, replace(string, search
string, replacement string), translate, substr(string, m, n), length, to date, . . .
 For the date data type: add month, month between, next day, to char . . .

You might also like