0% found this document useful (0 votes)
14 views

SQL

SQL is a standard language for interacting with relational databases. It allows users to define, manipulate, and query data. Common SQL commands include CREATE, SELECT, INSERT, UPDATE, DELETE. The SELECT statement retrieves data from one or more tables. Aggregate functions like COUNT, SUM, AVG operate on columns and return a single value.

Uploaded by

jovape4609
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

SQL

SQL is a standard language for interacting with relational databases. It allows users to define, manipulate, and query data. Common SQL commands include CREATE, SELECT, INSERT, UPDATE, DELETE. The SELECT statement retrieves data from one or more tables. Aggregate functions like COUNT, SUM, AVG operate on columns and return a single value.

Uploaded by

jovape4609
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

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;

• Attributes in select clause outside of aggregate


functions must appear in group by list
Having clause
• List the average of salaries of employees of each
company where average salary is greater than
16000.
▫ select avg(salary), company_name from works
group by company_name having
avg(salary)>16000;
NULL values
• It is possible for tuples to have a null value, denoted by
null, for some of their attributes
• null signifies an unknown value or that a value does
not exist.
• The predicate is null can be used to check for null
values.
• E.g. Find all loan number which appear in the loan
relation with null values for amount.
select loan-number
from loan
where amount is null
Queries
• Find names of all employees living in ‘Gurgaon’
and whose salary is between Rs.30,000 and
Rs.70,000.
• Find names of all employees whose names begin
with either letter ‘A’ or ‘K’.
• Find the company names where the company
city is ‘New Delhi’ and the number of employees
is not between 5000 and 10,000.
• Find the names of all companies that do not end
with letter ‘A’.
Solutions
• Select ename from Employee where
ecity=‘Gurgaon’ and salary between 30000 and
70000;
• Select ename from Employee where ename like
‘a%’ or ename like ‘k%’;
• Select cname from Company where ccity=‘New
Delhi’ and noofemp not between 5000 and
10000;
• Select cname from Company where cname not
like ‘%a’;
Queries
• List all employee names in descending order.
• Find number of employees in each department
where number of employees is greater than 5.
• List all the department names where average
salary of a department is greater than Rs.10,000.
Solutions
• Select ename from Employee order by ename
DESC
• Select count(*), deptname group by deptname
having count(*)>5
• Select deptname from Employee group by
deptname having avg(salary)>10000
SQL Joins
• JOINS in SQL are commands which are used to
combine rows from two or more tables, based on
a related column between those tables.
• Different types of Joins are:
▫ INNER JOIN
▫ LEFT JOIN
▫ RIGHT JOIN
▫ FULL JOIN
INNER JOIN
• INNER JOIN: The INNER JOIN keyword
selects all rows from both the tables as long as
the condition satisfies. This keyword will
create the result-set by combining all rows
from both the tables where the condition
satisfies i.e. value of the common field will be
same.
• Syntax:
SELECT table1.column1, table1.column2,
table2.column1,.. FROM table1 INNER JOIN
table2 ON table1.matching_column =
table2.matching_column;
Student and StudentCourse tables
List the names of students and the course
enrolled.
• SELECT StudentCourse.COURSE_ID, Student.NAME,
FROM Student INNER JOIN StudentCourse ON
Student.ROLL_NO = StudentCourse.ROLL_NO;
LEFT JOIN
• LEFT JOIN: This join returns all
the rows of the table on the left
side of the join and matching
rows for the table on the right
side of join. The rows for which
there is no matching row on right
side, the result-set will
contain null. LEFT JOIN is also
known as LEFT OUTER JOIN.
LEFT JOIN
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student LEFT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
RIGHT JOIN
• RIGHT JOIN: RIGHT JOIN is
similar to LEFT JOIN. This join
returns all the rows of the table
on the right side of the join and
matching rows for the table on
the left side of join. The rows for
which there is no matching row
on left side, the result-set will
contain null. RIGHT JOIN is also
known as RIGHT OUTER JOIN.
RIGHT JOIN
• SELECT Student.NAME, StudentCourse.COURSE_ID
FROM Student RIGHT JOIN StudentCourse ON
StudentCourse.ROLL_NO = Student.ROLL_NO;
FULL JOIN
• FULL JOIN: FULL JOIN
creates the result-set by
combining result of both
LEFT JOIN and RIGHT
JOIN. The result-set will
contain all the rows from
both the tables. The rows for
which there is no matching,
the result-set will
contain NULL values.
FULL JOIN
• SELECT Student.NAME,
StudentCourse.COURSE_ID
FROM Student FULL JOIN
StudentCourse ON
StudentCourse.ROLL_NO =
Student.ROLL_NO;
Example
Assume a publishing house that publishes original and
translated books. Our database contains four tables:
books, authors, editors and translators.
• Books(id, title, type, author_id, editor_id,
translator_id)
• Authors(id, first_name, last_name)
• editors(id, first_name, last_name)
• translators(id, first_name, last_name)
Queries
1. Show the books and their authors.

SELECT b.id, b.title, a.first_name,


a.last_name
FROM books b
INNER JOIN authors a
ON b.author_id = a.id;
Queries
2. Find out the editors who haven’t yet published
any book.

SELECT b.id, b.title,


e.last_name AS editor
FROM books b
RIGHT JOIN editors e
ON b.editor_id = e.id;
Queries
3. Find out the book details along with their
translators, if exist.

SELECT b.id, b.title, b.type,


t.last_name, t.first_name
FROM books b
LEFT JOIN
translators t
ON b.translator_id = t.id;
SET Operations
• The set operations union, intersect, and
except operate on relations and correspond to
the relational algebra operations ∪, ∩, −.
• Each of the above operations automatically
eliminates duplicates; to retain all duplicates use
the corresponding multiset versions union all,
intersect all and except all.
SET Operations
• Find all customers who have a loan, an account, or
both:
▫ (select customer-name from depositor) union
(select customer-name from borrower)
• Find all customers who have an account but no loan.
▫ (select customer-name from depositor) except
(select customer-name from borrower)
• Find all customers who have both a loan and an
account.
▫ (select customer-name from depositor) intersect
(select customer-name from borrower)
Example Queries
Assume a Company
schema with the
following tables:
1. Employee
2. Department
3. Dept_Locations
4. Project
5. Works_On
Example Queries
Make a list of all project numbers for projects that
involve an employee whose last name is ‘Smith’,
either as a worker or as a manager of the
department that controls the project.

(Select distinct Pnumber


From Project, Department, Employee
Where Dnum = Dnumber AND Mgr_ssn= Ssn
AND Lname= ‘Smith’)
UNION
(Select distinct Pnumber
From Project, Works_On, Employee
Where Pnumber = Pno AND Essn= Ssn
AND Lname= ‘Smith’);
Nested Sub-queries
• SQL provides a mechanism for the nesting of sub
queries.
• A sub query is a select-from-where expression
that is nested within another query.
• A common use of sub queries is to perform tests
for set membership, set comparisons, and set
cardinality.
Nested Sub-queries
• Find all customers who have both an account
and a loan at the bank.
▫ select distinct customer-name from borrower
where customer-name in (select customer-
name from depositor)
• Find all customers who have a loan at the bank
but do not have an account at the bank
▫ select distinct customer-name from borrower
where customer-name not in (select customer-
name from depositor)
Example Queries
Make a list of all project numbers for projects that
involve an employee whose last name is ‘Smith’

SELECT DISTINCT Pnumber


FROM PROJECT
WHERE Pnumber IN

( 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.

SELECT DISTINCT Pnumber


FROM PROJECT
WHERE Pnumber IN
( SELECT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND
Mgr_ssn = Ssn AND Lname = ‘Smith’ );
Make a list of all project numbers for projects that
involve an employee whose last name is ‘Smith’,
either as a worker or as a manager of the department
that controls the project.

SELECT DISTINCT Pnumber


FROM PROJECT
WHERE Pnumber IN
( SELECT Pnumber
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE Dnum = Dnumber AND
Mgr_ssn = Ssn AND Lname = ‘Smith’ )
OR
Pnumber IN
( SELECT Pno
FROM WORKS_ON, EMPLOYEE
Example Queries
Query to find the employee whose salary is the
highest.
select * from employee where salary=(select Max(salary)
from employee);
Or
select * from employee ORDER BY salary DESC LIMIT 1;
Example Queries
Query to find the second highest salary.

SELECT max(salary) from employee


WHERE salary < (SELECT max(salary) from employee);
OR

SELECT salary from employee ORDER BY salary DESC


LIMIT 1 1
The LIMIT clause
The LIMIT clause takes in 2 components.
• The first component refers to the number of rows that we
need to skip from the top.
• The second component refers to the number of rows that
is to be displayed.

SELECT empname, salary FROM employee ORDER BY


salary DESC LIMIT N-1,1;
Example queries
• Find all branches that have greater assets than
some branch located in Brooklyn.
▫ select distinct T.branch-name from branch as
T, branch as S where T.assets > S.assets and
S.branch-city = ‘Brooklyn’
• Same query using > some clause
▫ select branch-name from branch where assets
> some (select assets from branch where
branch-city = ‘Brooklyn’)
Example queries
• Find the names of all branches that have greater
assets than all branches located in Brooklyn.
▫ select branch-name from branch where assets
> all (select assets from branch where branch-
city = ‘Brooklyn’)
Views
• Provide a mechanism to hide certain data from
the view of certain users. To create a view we use
the command:
• create view v as <query expression>

You might also like