Chapter 7 The SQL Language
Chapter 7 The SQL Language
Objectives
Structure
Introduction
Constraints Specifications
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.
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.
Section Objectives
7.1.1.2Numeric Datatypes:
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:
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:
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
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
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;
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
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:
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));
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)
);
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.
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
✓ 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:
Example:
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.
Examples:
Q31> Select * from Employee;
Q32> Select emp_name, Department from Employee;
Q33> Select * from Employee where Salary >10000;
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 . . .