SQL
SQL
What is SQL?
SQL is a database language designed for the retrieval and management of data in a relational
database.
SQL is the standard language for database management. All the RDBMS systems like MySQL,
MS Access, Oracle, Sybase, Postgres, and SQL Server use SQL as their standard database
language.
SQL programming language uses various commands for different operations. We will learn
about the like DCL, TCL, DQL, DDL and DML commands in SQL with examples.
1970 – Dr. Edgar F. “Ted” Codd described a relational model for databases.
1974 – Structured Query Language appeared.
1978 – IBM released a product called System/R.
1986 – IBM developed the prototype of a relational database, which is standardized by
ANSI.
1989- First ever version launched of SQL
1999 – SQL 3 launched with features like triggers, object-orientation, etc.
SQL2003- window functions, XML-related features, etc.
SQL2006- Support for XML Query Language
SQL2011-improved support for temporal databases
Types of SQL
Here are five types of widely used SQL queries.
The Data Definition Language (DDL) is used to create and destroy databases and database
objects. These commands will primarily be used by database administrators during the setup and
removal phases of a database project.
Let's take a look at the structure and usage of four basic DDL commands: CREATE, ALTER,
DROP and RENAME
Practice No. 1
1. Create Table
DATA TYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length. The
size in brackets determines the number of characters the cell can hold. The maximum
number of character is 255 characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating point).
Number of virtually any magnitude may be stored up to 38 digits of precision. Number as
large as 9.99 * 10 124. The precision (p) determines the number of places to the right of the
decimal. If scale is omitted then the default is zero. If precision is omitted, values are stored
with their original precision up to the maximum of 38 digits.
4. DATE: This data type is used to represent date and time. The standard format is DDMM-
YY as in 17-SEP-2009. To enter dates other than the standard format, use the appropriate
functions. Date time stores date in the 24-Hours format. By default the time 9 in a date field
is 12:00:00 am, if no time portion is specified. The default date for a date field is the first
day the current month.
5. LONG: This data type is used to store variable length character strings containing up to
2GB. Long data can be used to store arrays of binary data in ASCII format. LONG values
cannot be indexed, and the normal character functions such as SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image.
Data loaded into columns of these data types are stored without any further conversion.
RAW data type can have a maximum length of 255 bytes. LONG RAW data type can
contain up to 2GB.
CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between the
constraint and the data action, the action is aborted by the constraint. It can be specified when the
table is created (using CREATE TABLE statement) or after the table is created (using ALTER
TABLE statement).
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is
to be accepted for storage in the table.
Syntax:
Example:
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The table in
which the foreign key is defined is called a detail table. The table that defines the primary
key and is referenced by the foreign key is called the master table.
6. DEFAULT: The DEFAULT constraint is used to insert a default value into a column. The
default value will be added to all new records, if no other value is specified.
Mgr_start_date date
);
Fname varchar(50),
Minit varchar(4),
Lname varchar(50),
Bdate date,
Address varchar(50),
Salary float,
Super_Id int,
Dno INT,
);
);
Pname varchar(50),
Plocation varchar(50),
Dnumber INT,
);
EId INT,
Pno INT,
Hours INT,
);
EId INT,
Sex varchar(10),
Bdate Date,
);
DESC EMPLOYEE;
DESC DEPARTMENT;
DESC PROJECT;
DESC DEPENDENT;
DESC WORKS_ON;
DESC DEPT_LOCATIONS;
ALTER TABLE
Example: ALTER TABLE employee ALTER COLUMN fname SET NOT NULL;
Example: ALTER TABLE employee ADD CONSTRAINT c11 PRIMARY KEY (ID);
3. Dropping Tables
4. Create VIEW
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database. You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table. A view is a virtual table,
which consists of a set of columns from one or more tables. It is similar to a table but it does not
store in the database. View is a query stored as an object.
Exercise
1. Write SQL query to create view which will display name and address of
employees?
3. DROPPING A VIEW:
A view can deleted with the DROP VIEW command. Syntax: DROP VIEW ;
LAB PRACTICE 1:
Student_Course(C_code,S_ID)
3. Add a new column; E_email to the existing relation.
4. Change the datatype of S_address from char to varchar2.
5. Change the name of column/field SID to S_no.
6. Modify the column width of the S_address field of student table
Practice No. 2
Title: Implementation of DML commands of SQL with suitable examples
Insert table
Update table
Delete Table
Objective:
To understand the different issues involved in the design and implementation of a
database system
To understand and use data manipulation language to query, update, and manage a
database
Theory : DATA MANIPULATION LANGUAGE (DML): DML is used to retrieve, insert and
modify database information. These commands will be used by all database users during the
routine operation of the database. Let's take a brief look at the basic DML commands: INSERT,
UPDATE and DELETE.
INSERT INTO
EMPLOYEE(Fname,Minit,Lname,Id,Bdate,Address,Sex,Salary,Super_Id,Dno)VALUES('Toma
s','TB','Belete’, 6060,'8/9/7','ARADA','Male',147891,7070,4444);
2. UPDATE-SET-WHERE
Example:
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.
Example
TRUNCATE: This command will remove the data permanently. But structure will not be
removed.
Using truncate command data will be removed permanently & will not get back where
as by using delete command data will be removed temporally & get back by using
roll back command.
Using delete command data will be removed based on the condition whereas by using
truncate command there is no condition.
Truncate is a DDL command & delete is a DML command.
TRUNCATE TRUNCATE TABLE <Table name> This is used remove the data
permanently but it will
retain the structure of that
relation
LAB EXERCISE 2:
1. Insert data in to the tables that you have created for lab exercise 1?
2. Delete some records from student table?
3. Delete some records from course table based on a condition?
4. Change the name of DEPARTMENT relation to DEPT and back to DEPARTMENT.
5. Rename the SID attribute of the student relation to SNO ?
6. Delete all records of student?
Practice No. 3
Example
Practice No: 4
Title: Implementation of different types of operators in SQL.
Arithmetic Operator
Logical Operator
Comparison Operator
Special Operator
Set Operator
Exercise
IN: The IN operator is used to compare a value to a list of literal values that have been
specified.
EXIST: The EXISTS operator is used to search for the presence of a row in a specified table
that meets certain criteria.
1. Write SQL query to retrieve department number for human resource department?
SQL Retional Algebra statement
SELECT Dnumber Π Dnumber (δ Dname=’Human Resource’ (Department))
FROM Department
Where Dname=’Human
Resource’;
7. Write SQL query to retrieve first name, last name and ID of supervisee of Henok?
SQL Retional Algebra statement
SELECT Fname,Lname,ID R Π ID( δ Fname=’Henok’ (Employee))
FROM Employee
Where SuperID=(SELECT ID Π Fname,Lname,ID (R)
FROM employee WHERE
Fname=’Henok’);
8. Write SQL statement to retrieve the birth date and address of the employee(s) whose
name is ‘John ws. Smith’?
Retional Algebra statement
SQL
SELECT Bdate, Address Rδ Fname = ‘Shrafel’ AND Minit = ‘SH’ AND Lname = ‘Habib’ (Employee)
FROM EMPLOYEE
WHERE Fname = ‘Shrafel’ Π Bdate, Address (R)
AND Minit = ‘SH’ AND
Lname = ‘Habib’;
10. Retrieve the name and address of all employees who work for the human resource
department.
Rational Algebra statement
SQL
SELECT
Fname,Lname,Minit,
Address
FROM Employee
Where
DNO=(SELECT Dno
FROM Department
WHERE
Dname=’human
resource’);
Practice No: 5
Title: Implementation of different types of Joins
Inner Join
Outer Join
Natural Join..etc
Objective: To implement different types of joins
Theory: The SQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values common
to each.The join is actually performed by the ‘where’ clause which combines specified rows
of tables. Types of Joins: Simple Join, Self Join and Outer Join
Simple Join: It is the most common type of join. It retrieves the rows from 2 tables having a
common column and is further classified into
Equi-join: A join, which is based on equalities, is called equi-join.
Example: Select * from Department, Employee where
Department.Dnumber=Employee.Dno; In the above statement,
Department.Dnumber=Employee.Dno performs the join statement. It retrieves rows from
both the tables provided they both have the same id as specified by the where clause. Since
the where clause uses the comparison operator (=) to perform a join, it is said to be equijoin.
It combines the matched rows of tables. It can be used as follows:
To insert records in the target table.
To create tables and insert records in this table.
To update records in the target table.
To create views.
Non Equi-join: It specifies the relationship between columns belonging to different tables by
making use of relational operators other than’=’.
Table Aliases Table aliases are used to make multiple table queries shorted and more
readable. We give an alias name to the table in the ‘from’ clause and use it instead of the
name throughout the query.
Self-join: Joining of a table to itself is known as self-join. It joins one row in a table to
another. It can compare each row of the table to itself and also with other rows of the same
table. Example: select * from employee x , employee y where x.salary >= (select avg(salary)
from x where x. dno =y.dnumber);
Outer Join: It extends the result of a simple join. An outer join returns all the rows returned
by simple join as well as those rows from one table that do not match any row from the table.
The symbols (+) represents outer join.
1. Write SQL statement to retrieve employees who works on Code Writing project?
Rational Algebra statement
SQL
SELECT ρE(Employee)
Fname,Minit,Lname,Id,Bdate,Address,Sex,Sa
lary,Super_Id,Dno Address ρW(WORKS_ON)
FROM Employee E, WORKS_ON W, ρP(Project)
Project p
Where E.ID=W.EID and W.Pid=W.Pnumber R EXWXP
and P.Pname=’Code Writing’; Sδ E.ID=W.EID AND W.Pid=W.Pnumber AND
P.Pname=’Code Writing’ (R)
Π
Fname,Minit,Lname,Id,Bdate,Address,Sex,Salar
y,Super_Id,Dno(S)
2. Retrieve the name and address of all employees who work for the human resource
department.
Practice Exercise
4. For every project located in ‘west wing’, write SQL statement to list the project number,
the controlling department number, and the department manager’s last name, address, and
birth date.
5. For each employee, retrieve the employee’s first and last name and the first and last name
of his or her immediate supervisor.
6. Make a list of all project numbers for projects that involve an employee whose last name
is ‘habib’, either as a worker or as manager of the department that controls the project.
Practice No: 5
Aggregative operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now consider
a powerful class of constructs for computing aggregate values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in that column. If
DISTINCT keyword is used then it will return only the count of unique tuple in the
column. Otherwise, it will return count of all the tuples (including duplicates)
Example:
2. SUM: SUM followed by a column name returns the sum of all the values in that column.
3. AVG: AVG followed by a column name returns the average value of that column values.
Example
4. MAX: MAX followed by a column name returns the maximum value of that column.
Example
5. MIN: MIN followed by a column name returns the maximum value of that column.
Example
Exercise
1. Write SQL query to retrieve an employee who earns the largest salary?
2. Write SQL query to retrieve an employee who earns the largest salary?
Practice No: 6
Title: Study Implementation of Group by & Having Clause and Order by Clause.
1. GROUP BY: This query is used to group to all the records in a relation together for each
and every value of a specific key(s) and then display them for a selected set of fields the
relation.
Example
1. Write SQL query to retrieve total number of employees in each department?
Rational Algebra statement
SQL
SELECT COUNT (*) ,
Dno FROM Employee
GROUP BY Dno;
Exercise
1. Write SQL query to retrieve maximum, minimum, and average salary of employees in
each department?
2. Write SQL query to retrieve maximum, minimum, and average salary of employee’s
human resource in department?
2. HAVING: The HAVING clause was added to SQL because the WHERE keyword could
not be used with aggregate functions. The HAVING clause must follow the GROUP BY
clause in a query and must also precedes the ORDER BY clause if used.
Exercise
1. Write SQL query to retrieve employees who has more than two dependents?
2. Write SQL query to retrieve employees who works on more than one project ?
3. ORDER BY: This query is used to display a selected set of fields from a relation in an
ordered manner base on some field.
Exercise
1. Write SQL query to retrieve employees name in ascending and descending order?
2. Write SQL query to retrieve employees salary ascending and descending order?
Practice No: 7
Title : Study & Implementation of
Sub queries
Objective: – To perform nested Queries and joining Queries using DML command – To
understand the implementation of views.
Theory: SUBQUERIES: The query within another is known as a sub query. A statement
containing sub query is called parent statement. The rows returned by sub query are used by the
parent statement or in other words A subquery is a SELECT statement that is embedded in a
clause of another SELECT statement You can place the subquery in a number of SQL clauses:
WHERE clause, HAVING clause, FROM clause, OPERATORS( IN.ANY,ALL,,>=,<= etc..)
Types
Sub queries can also return more than one value. Such results should be made use along with the
operators in and any.
2. Multiple queries
Here more than one sub query is used. These multiple sub queries are combined by means of
‘and’ & ‘or’ keywords.
A sub query is evaluated once for the entire parent statement whereas a correlated Sub query is
evaluated once per row processed by the parent statement.
Practice NO.8
SET OPERATORS
The Set operator combines the result of 2 queries into a single result. The following are the operators:
Union
Union all
Intersect
Minus
Union: Returns all distinct rows selected by both the queries Union all: Returns all rows selected by
either query including the duplicates.
Minus: Returns all distinct rows selected by the first query and are not by the second
Example:
1. Make a list of all project numbers for projects that involve an employee whose last name is
‘Habib’, either as a worker or as manager of the department that controls the project.
UNION
Exercise
1. Write SQL query to retrieve employees who participate in game development project
only?
2. Write SQL query to retrieve employees who participate in game development and unit
testing project only?