SQL
SQL
Introduction to SQL
• The name SQL is presently expanded as Structured
Query Language.
• Originally, SQL was called SEQUEL (Structured English
QUEry Language) and was designed and implemented at
IBM Research as the interface for an experimental
relational database system called SYSTEM R.
• SQL is now the standard language for commercial
relational DBMSs.
Introduction to SQL
• SQL is based on set and relational operations
with certain modifications and enhancements
• A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P
• Ai represent attributes
• ri represent relations
• P is a predicate
• The result of an SQL query is a relation.
Advantages of SQL
• Allows users to access data in the relational database
management systems.
• Allows users to describe the data.
• Allows users to define the data in a database and
manipulate that data.
• Allows to embed within other languages using SQL
modules, libraries & pre-compilers.
• Allows users to create and drop databases and tables.
• Allows users to create view, stored procedure, functions in
a database.
• Allows users to set permissions on tables, procedures and
views.
Data types in SQL
• The basic data types available for attributes include
numeric, character string, bit string, Boolean, date, and
time.
• Numeric data types include integer numbers of various
sizes (INTEGER or INT, and SMALLINT) and floating-
point (real) numbers of various precision (FLOAT or
REAL, and DOUBLE PRECISION).
• Character-string data types are either fixed length—
CHAR(n) or CHARACTER(n), where n is the number of
characters—or varying length— VARCHAR(n) or CHAR
VARYING(n) or CHARACTER VARYING(n), where n is
the maximum number of characters
Data types in SQL
• Bit-string data types are either of fixed length n—
BIT(n)—or varying length—BIT VARYING(n), where n
is the maximum number of bits. The default for n, the
length of a character string or bit string, is 1.
• A Boolean data type has the traditional values of
TRUE or FALSE.
• The DATE data type has ten positions, and its
components are YEAR, MONTH, and DAY in the form
YYYY-MM-DD. The TIME data type has at least eight
positions, with the components HOUR, MINUTE, and
SECOND in the form HH:MM:SS.
SQL Commands
• The standard SQL commands to interact with
relational databases are CREATE, SELECT,
INSERT, UPDATE, DELETE and DROP. These
commands can be classified into the following
groups based on their nature:
• DDL - Data Definition Language
• DML - Data Manipulation Language
• DCL - Data Control Language
DDL Commands
CREATE
1 Creates a new table, a view of a table, or other object in the
database.
ALTER
2 Modifies an existing database object, such as a table.
DROP
3 Deletes an entire table, a view of a table or other objects in the
database.
DML Commands
SELECT
1 Retrieves certain records from one or more tables.
INSERT
2
Creates a record.
UPDATE
3
Modifies records.
DELETE
4
Deletes records.
DCL Commands
GRANT
1 Gives a privilege to user.
REVOKE
2 Takes back privileges granted from user.
CREATE command
• Create database student;
• Create table article;
• Create view for_students;
DROP command
• Drop database student;
• Drop table article;
• Drop view for_students;
ALTER command
• alter table article add subject varchar;
• alter table article add article_no int;
• alter table article drop column subject;
• alter table article alter column id float;
INSERT command
• Syntax:
• INSERT INTO table_name ([column1, column2,
column3 ... ]) VALUES ([value1 , value2,
value3 ... ])
• Example:
• INSERT INTO article(Author, Subject) VALUES
("anonymous", "computers");
Or
• INSERT INTO article VALUES(“anonymous”,
“computers”);
UPDATE command
• Syntax:
• UPDATE table_name SET column_name =
value [, column_name = value ...] [WHERE
condition]
• Example:
UPDATE article SET Author="webmaster"
WHERE Author="anonymous";
DELETE command
• Syntax:
DELETE FROM table_name [WHERE condition];
• Example:
DELETE FROM article WHERE
Author="unknown";
The select clause
• The select clause list the attributes desired in the result
of a query
• E.g. find the names of all branches in the loan relation
• select branch-name
• from loan
• NOTE: SQL does not permit the ‘-’ character in names,
▫ Use, e.g., branch_name instead of branch-name in a real
implementation.
• We use ‘-’ since it looks nicer!
• NOTE: SQL names are case insensitive, i.e. you can use
capital or small letters.
The select clause
• SQL allows duplicates in relations as well as in
query results.
• To force the elimination of duplicates, insert the
keyword distinct after select.
• Find the names of all branches in the loan
relations, and remove duplicates
▫ select distinct branch-name from loan
The select clause
• An asterisk in the select clause denotes “all attributes”
▫ select * from loan
• The select clause can contain arithmetic expressions
involving the operation, +, –, ∗, and /, and operating
on constants or attributes of tuples.
• The query:
▫ select loan-number, branch-name, amount ∗ 100 from
loan
would return a relation which is the same as the loan
relations, except that the attribute amount is multiplied
by 100.
The where clause
• The where clause specifies conditions that the result must
satisfy.
• To find all loan number for loans made at the Perryridge
branch with loan amounts greater than $1200.
▫ select loan-number from loan where branch-name =
‘Perryridge’ and amount > 1200
• Comparison results can be combined using the logical
connectives and, or, and not.
• SQL includes a between comparison operator
▫ E.g. Find the loan number of those loans with loan amounts
between $90,000 and $100,000 (that is, ≥$90,000 and
≤$100,000)
▫ select loan-number from loan where amount between
90000 and 100000
String operations
• SQL includes a string-matching operator for
comparisons on character strings. Patterns are
described using two special characters:
▫ percent (%). The % character matches any substring.
▫ underscore (_). The _ character matches any
character.
• Find the names of all customers whose street
includes the substring “Main”.
▫ select customer-name from customer where
customer-street like ‘%Main%’
Basic SQL Queries
• Create database named Employee.
• Use database Employee and create a table
Employee with attributes ename, ecity, salary,
eno, eaddress, deptname.
• Create table Company with attributes cname,
ccity, noofemp, empno in database Employee.
• Create table Student with attributes sid, sname,
scity.
• Destroy the Student database.
Solutions
• Create database Employee;
• Use database Employee;
• Create table Employee(ename varchar(30), ecity
varchar(30), salary int, eno int NOT NULL,
eaddress varchar(50), deptname varchar(20));
• Drop database Student;
Basic SQL Queries -2
• Find names of all employees who live in Delhi.
• Increase salary of all employees by Rs5000.
• Find company name where no. of
employees>10,000.
• Change company city to Gurgaon where
company name is TCS.
Solutions
• Select ename from Employee where
ecity=‘Delhi’;
• Update Employee set salary=salary+5000
• Select cname from Company where
noofemp>10000
• Update Company set ccity=‘Gurgaon’ where
cname=‘TCS’
Basic SQL Queries- 3
• Add an attribute named ‘Designation’ to the
table Employee.
• Modify the table Employee and change datatype
of salary attribute to float.
• Drop attribute ‘deptname’ from table Employee.
• Delete entries from table ‘Company’ where no. of
employees are less than 500.
Solutions
• Alter table Employee add Designation
varchar(20)
• Alter table Employee alter column salary float
• Alter table Employee drop column deptname
• Delete from Company where noofemp<500
Aggregate functions
These functions operate on the multiset of values of a
column of a relation, and return a value
• avg: average value
• min: minimum value
• max: maximum value
• sum: sum of values
• count: number of values
Aggregate functions
Find the average account balance at the Perryridge branch.
• select avg (balance) from account where branch-
name = ‘Perryridge’
Find the number of tuples in the customer relation.
• select count (*) from customer
Find the number of depositors in the bank.
• select count (distinct customer-name) from
depositor
Queries
• Find the sum and average of salaries of all
employees in Testing department.
• Find the number of all employees who live in
‘Chandigarh’
• Find the maximum and minimum salary in
‘Testing’ department.
Solutions
• Select sum(salary) “Sum”, avg(salary) “Average”
from Employee where deptname=‘Testing’;
• Select count(*) from Employee where
ecity=‘Chandigarh’
• Select max(salary) “Max salary”, min(salary)
“Min salary” from Employee where
deptname=‘Testing’
The Rename operation
• The SQL allows renaming relations and
attributes using the as clause:
• old-name as new-name
• Find the name, loan number and loan amount of
all customers; rename the column name loan-
number as loan-id.
▫ select customer-name, borrower.loan-number
as loan-id, amount from borrower, loan where
borrower.loan-number = loan.loan-number
Order by clause
• List in alphabetic order the names of all
customers having a loan in Perryridge branch
▫ select distinct customer-name from borrower,
loan where borrower loan-number - loan.loan-
number and branch-name = ‘Perryridge’ order
by customer-name
• We may specify desc for descending order or
asc for ascending order, for each attribute;
ascending order is the default.
▫ E.g. order by customer-name desc
Group by clause
• List the average of salaries of all the employees
of each company.
▫ select avg(salary), company_name from works
group by company_name;
( SELECT Pno
FROM WORKS_ON, EMPLOYEE
WHERE Essn = Ssn AND Lname = ‘Smith’ );
Example Queries
Make a list of all project numbers for projects that
involve an employee whose last name is ‘Smith’, as
a manager of the department that controls the
project.