6 Basic SQL
6 Basic SQL
Basic SQL
Company Database Schema
SQL Overview
• It was originally developed by IBM in 1970
• It is the standard relational database language
• It stands for Standard Query Language
• It is non-procedural language, you specify what information
needed rather than how to get it
• It has two types:
Data Definition Language (DDL): Used it to define the structure
of the database. Define database, tables, attributes, datatypes,
constraints… Keywords: create, alter and drop
Example:
Select SSN, Fname, DOB
From Employee
Where salary > 100,000
Retrieve all Attributes, all
Rows
• Retrieve all the attributes and rows from the table:
• Select * from employee
• Retrieve some attributes for all employees:
• Select SSN, Fname, Lname, Salary from employee
• Retrieve some attributes for some employees:
• Select SSN, Fname, Dnumber from employee where
salary=2000
• Select SSN, Fname, DOB from employee where
salary=2000 and dnumber=3
Aliases for tables and
attributes
• Alias for attributes:
• Select Fname as First_Name, Lname as Last_Name from
Employee
• Alias for Tables:
• Select Fname as First_Name from employee as Emp
• Attribute reference by table name:
• Select employee.fname as First_name from employee
• Select emp.fname from employee as emp
Ordering of the retrieved
tuples
• Order of resulted rows without condition
• Select * from employee order by SSN
• Order of resulted rows with condition
• Select * from employee where salary<3000 order by SSN
• Order the resulted rows with different attributes
• Select SSN, Fname, address from employee order by salary, Dno
• Default ordering is ascending if descending then:
• Select * from employee order by salary desc
• Select * from employee order by salary desc, dno asc
Retrieve Distinct Values
• Retrieve department name and its locations and the name of its
manager with salary greater than 40000
Select Dname, dlocation,Fname+lname as manager_name from
employee join department on ssn=mgr_ssn join dept_locations on
department.dnumber =dept_locations.dnumber where salary> 40000
• Retrieve each department name and its location along with the
project name and location they manage
St_name Dept_no
Noha IS
Bashayer IS
Shahd CS
NULL IT
Left and Right outer join
Dept_no Dept_nam Student_ID St_name Dept_no
e
100 Noha 1
1 IS
200 Bashayer 1
2 CS
300 Shahd NULL
3 IT
• Select Dept_name, st_name from department right join student
on department.dept_no=student.dept_no
St_name Dept_no
Noha IS
Bashayer IS
Shahd NULL
Cross Join or Cartesian
Product
• In this type of join you don’t specify a join condition
• Unlike Inner, left, right outer join, cross join doesn’t
have On clause
• The number of rows resulted from cross join R1 and
R2 is R1x R2
• Syntax
Select * from R1 cross join R2
Cross Join or Cartesian
Product
Department Student
Dept_no Dept_nam Student_ID St_name Dept_no
e 100 Noha 1
1 IS
200 Bashayer 1
2 CS
300 Shahd 2
Employee as manager