0% found this document useful (0 votes)
82 views74 pages

SQL Basics

The document provides an introduction to structured query language (SQL) and database concepts. It discusses SQL's data definition language for creating database structures, data manipulation language for storing and retrieving data, and data control language for controlling access. It also covers topics like database schemas, data types, table structures, constraints, indexes, and joining tables. The document is presented by Kuldeep Singh to NAM on February 18, 2016 as an introduction to SQL.

Uploaded by

Gaurav Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
82 views74 pages

SQL Basics

The document provides an introduction to structured query language (SQL) and database concepts. It discusses SQL's data definition language for creating database structures, data manipulation language for storing and retrieving data, and data control language for controlling access. It also covers topics like database schemas, data types, table structures, constraints, indexes, and joining tables. The document is presented by Kuldeep Singh to NAM on February 18, 2016 as an introduction to SQL.

Uploaded by

Gaurav Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 74

Introduction to Structured Query

Language (SQL)
Presented to NAM
18-Feb-2016
By Kuldeep Singh

Core Database Engine

ORACLE RDBMS (Oracle Universal server)

Integrated Data Dictionary: manage tables owned by all users


in a system

SQL: language to access and manipulate data

PL/SQL: a procedural extension to SQL language

SQL*PLUS

Command line tool that process users SQL statements

Requires Oracle account

DDL

Data Definition

DML

Data Manipulation

DCL

Data Control

SQL

Structured Query Language (SQL)

Data Definition Language (DDL) Used to create


(define) data structures such as tables, indexes,
clusters
Data Manipulation Language (DML) is used to store,
retrieve and update data from tables
Data Control Language used to control the access
to the database objects created using DDL and DML

Introduction to SQL

Introduction to SQL (continued)

Introduction to SQL (continued)

DCL: Data Control Language

Controlling Access to database


objects such as tables and views

Example : Granting Mary the access to Table


student (for inserting, updating and deleting)

GRANT INSERT, UPDATE, DELETE ON Student TO


Mary

GRANT <privileges> ON <object name>


TO <grantee> [ <comma> <grantee> ... ]
[ WITH GRANT OPTION ]

WITH GRANT OPTION: allows the grantee to


further grant privileges

Can be limited to a column of a table, Ex:


GRANT UPDATE(name) ON Student TO Mary

To revoke privileges : REVOKE

The Database Model

Creating the Database

Following two tasks must be completed:

Create database structure

Create tables that will hold end-user data

First task:

RDBMS creates physical files that will hold


database

Tends to differ substantially from one RDBMS to


another

The Database Schema

Authentication

Process through which DBMS verifies that only registered


users are able to access database

Log on to RDBMS using user ID and password created by


database administrator

Schema

Group of database objectssuch as tables and indexes


that are related to each other

Data Types

Data type selection is usually dictated by


nature of data and by intended use

Pay close attention to expected use of


attributes for sorting and data retrieval
purposes

Data Types (continued)

Primary key

CREATE TABLE order_header (


order_number NUMBER(10,0) NOT NULL,
order_date DATE,
sales_person VARCHAR(25),
bill_to VARCHAR(35),
bill_to_address VARCHAR(45),
bill_to_city VARCHAR(20),
bill_to_state VARCHAR(2),
bill_to_zip VARCHAR(10),
PRIMARY KEY (order_number) );

Foreign key
CREATE TABLE order_items (
order_number NUMBER(10,0) NOT NULL,
line_item NUMBER(4,0) NOT NULL,
part_number VARCHAR(12) NOT NULL,
quantity NUMBER(4,0),
PRIMARY KEY (order_number, line_item),
FORIEGN KEY (order_number)
REFERENCES order_header (order_number);

Specifying Constraints on
Columns and Tables

Constraints on attributes:

NOT NULL - Attribute may not take a


NULL value
DEFAULT - Store a given default
value i
PRIMARY KEY - Indicate which
attribute(s) form the primary key
FOREIGN KEY - Indicate which
attribute(s) form a foreign key.

UNIQUE - Indicates which


attribute(s) must have unique
values.

Creating Table Structures

Use one line per column (attribute) definition

Use spaces to line up attribute characteristics


and constraints

Table and attribute names are capitalized

NOT NULL specification

UNIQUE specification

Creating Table Structures


(continued)

Primary key attributes contain both a NOT


NULL and a UNIQUE specification

RDBMS will automatically enforce referential


integrity for foreign keys

Command sequence ends with semicolon

Removing Schema Components


with DROP
DROP TABLE table_name
DROP TABLE table_name CASCADE
DROP TABLE table_name RESTRICT
DROP INDEX index_name
DROP CONSTRAINT
table_name.constraint_name

Changing Table Components with


ALTER
Changing Attributes:
ALTER TABLE student MODIFY last_name
VARCHAR(35);
alter table student modify gpa
NUMBER(6,3) default 0.0;
Adding Attributes:
ALTER TABLE student ADD admission
DATE;
Removing Attributes (not widely implemented):
ALTER TABLE student DROP column
home_phone

SQL Indexes

When primary key is declared, DBMS


automatically creates unique index
Often need additional indexes
Using CREATE INDEX command, SQL
indexes can be created on basis of
any selected attribute
Composite index

Index based on two or more attributes


Often used to prevent data duplication

Data Manipulation Commands

Adding table rows

Saving table changes

Listing table rows

Updating table rows

Restoring table contents

Deleting table rows

Inserting table rows with a select subquery

Adding Table Rows

INSERT

Used to enter data into table

Syntax:

INSERT INTO columnname


VALUES (value1, value2, , valuen);

Adding Table Rows (continued)

When entering values, notice that:

Row contents are entered between


parentheses

Character and date values are entered


between apostrophes

Numerical entries are not enclosed in


apostrophes

Attribute entries are separated by commas

A value is required for each column

Use NULL for unknown values

Saving Table Changes

Changes made to table contents are not


physically saved on disk until, one of the
following occurs:
Database is closed
Program is closed
COMMIT command is used

Syntax:

COMMIT [WORK];

Will permanently save any changes made


to any table in the database

Listing Table Rows

SELECT

Used to list contents of table

Syntax:

SELECT columnlist
FROM tablename;

Columnlist represents one or more attributes, separated


by commas

Asterisk can be used as wildcard character to list all


attributes

Updating Table Rows

UPDATE

Modify data in a table

Syntax:

UPDATE tablename
SET columnname = expression [, columname =
expression]
[WHERE conditionlist];

If more than one attribute is to be updated in


row, separate corrections with commas

Restoring Table Contents

ROLLBACK

Used to restore database to its previous


condition

Only applicable if COMMIT command has not


been used to permanently store changes in
database

Syntax:

ROLLBACK;

COMMIT and ROLLBACK only work with


data manipulation commands that are
used to add, modify, or delete table rows

Deleting Table Rows

DELETE

Deletes a table row

Syntax:

DELETE FROM tablename


[WHERE conditionlist ];

WHERE condition is optional

If WHERE condition is not specified, all rows


from specified table will be deleted

Inserting Table Rows with a


Select Subquery

INSERT

Inserts multiple rows from another table (source)

Uses SELECT subquery

Query that is embedded (or nested) inside another query

Executed first

Syntax:

INSERT INTO tablename SELECT columnlist FROM tablename;

Selecting Rows with


Conditional Restrictions

Select partial table contents by placing


restrictions on rows to be included in output

Add conditional restrictions to SELECT


statement, using WHERE clause

Syntax:

SELECT columnlist
FROM tablelist
[ WHERE conditionlist ] ;

Selecting Rows with


Conditional Restrictions (continued)

Arithmetic Operators:
The Rule of Precedence

Perform operations within parentheses

Perform power operations

Perform multiplications and divisions

Perform additions and subtractions

Arithmetic Operators:
The Rule of Precedence (continued)

Special Operators

BETWEEN

IS NULL

Used to check whether attribute value is within


a range

Used to check whether attribute value is null

LIKE

Used to check whether attribute value matches


given string pattern

Special Operators (continued)

IN

Used to check whether attribute value matches


any value within a value list

EXISTS

Used to check if subquery returns any rows

Advanced Data Definition


Commands

All changes in table structure are made by


using ALTER command

Followed by keyword that produces specific


change

Following three options are available:

ADD

MODIFY

DROP

Changing a Columns Data Type

ALTER can be used to change data type

Some RDBMSs (such as Oracle) do not permit


changes to data types unless column to be
changed is empty

Changing a Columns Data


Characteristics

Use ALTER to change data characteristics

If column to be changed already contains data,


changes in columns characteristics are
permitted if those changes do not alter the
data type

Adding a Column

Use ALTER to add column

Do not include the NOT NULL clause for new


column

ADVANCED DATA UPDATES

Adding Primary and Foreign


Key Designations

When table is copied, integrity rules do not


copy, so primary and foreign keys need to be
manually defined on new table

User ALTER TABLE command

Syntax:

ALTER TABLE tablename ADD


PRIMARY KEY(fieldname);

For foreign key, use FOREIGN KEY in place of


PRIMARY KEY

Advanced Select Queries

SQL provides useful functions that can:

Count

Find minimum and maximum values

Calculate averages

SQL allows user to limit queries to only those


entries having no duplicates or entries whose
duplicates may be grouped

Aggregate Functions

Virtual Tables: Creating a View

View is virtual table based on SELECT query

Can contain columns, computed columns,


aliases, and aggregate functions from one or
more tables

Base tables are tables on which view is based

Create view by using CREATE VIEW command

Virtual Tables: Creating a View


(continued)

Joining Database Tables

Ability to combine (join) tables on common


attributes is most important distinction
between relational database and other
databases

Join is performed when data are retrieved from


more than one table at a time

Join is generally composed of an equality


comparison between foreign key and primary
key of related tables

Obtaining Data from Multiple Tables


EMPLOYEES

DEPARTMENTS

What is the Join


Use a join to query data from more than one table
SELECT
FROM
WHERE

table1.column, table2.column
table1, table2
table1.column1=table2.column2

Write the join condition in the WHERE clause


Prefix the column name with the table name when
the same column name appears in more than one
table

Types of Joins
Joins that are compliant with the SQL include the
following:

Cross joins

Equijoin

Natural joins

USING clause

Self join

Non-equijoin

Outer join

Joining Tables Using SQL


CROSS JOIN (operator )
SELECT
table1.column, table2.column
FROM
table1
[CROSS JOIN table2]

NATURAL JOIN(retrieve data from two tables by the


same column)
SELECT
table1.column, table2.column
FROM
table1
[NATURAL JOIN table2]

Join with USING clasue(if they have multiple


column
have the same name)
SELECT
table1.column, table2.column
FROM
table1
[JOIN table2 USING (column_name)]

JOIN WITH ON CLASUE(IF WE NEED A


CONDITION,LIKE WHERE CLAUSE)
SELECT
table1.column, table2.column
FROM
table1
[JOIN table2
ON (table1.column_name = table2.column_name)]

Outer join
SELECT
table1.column, table2.column
FROM
table1
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)]

Generating a Cartesian
Product
EMPLOYEES (20 rows)

Cartesian product:
20 x 8 = 160 rows

DEPARTMENTS (8 rows)

Creating Cross Joins

The CROSS JOIN clause produces the cross-product of


two tables.

This is also called a Cartesian product between the two


tables.

SELECT last_name, department_name


FROM
employees
CROSS JOIN departments ;

Retrieving Record with Equijoin


Employees Department
EMPLOYEES

Foreign key

DEPARTMENTS

Primary key

Using Equijoin
Write SQL statement to do this: Employees Department

Select *
From employees ,departments
Where employees.department_id=departments.department_id

Creating Natural Joins

The NATURAL JOIN clause is based on all columns in the


two tables that have the same name.

It selects rows from the two tables that have equal


values in all matched columns.

If the columns having the same names have different


data types, an error is returned.

Natural join is special case of Equijoin

Natural join removes duplicate attributes

Retrieving Records with Natural


Joins
SELECT department_id, department_name,
location_id, city
FROM
departments
NATURAL JOIN locations ;

Creating Joins with the USING Clause

If several columns have the same names but the data


types do not match, the NATURAL JOIN clause can be
modified with the USING clause to specify the columns
that should be used for an equijoin.

Use the USING clause to match only one column when


more than one column matches.

Retrieving Records with the USING


Clause
SELECT employees.employee_id, employees.last_name,
departments.location_id, department_id
FROM
employees JOIN departments
USING (department_id) ;

Using Table Aliases

Use table aliases to simplify queries.

Use table aliases to improve performance.

SELECT e.employee_id, e.last_name,


d.location_id, department_id
FROM
employees e JOIN departments d
USING (department_id) ;

Creating Joins with the ON Clause

The join condition for the natural join is basically an


equijoin of all columns with the same name.

Use the ON clause to specify arbitrary conditions or


specify columns to join.

The join condition is separated from other search


conditions.

The ON clause makes code easy to understand.

Retrieving Records with the ON


Clause
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM
employees e JOIN departments d
ON
(e.department_id = d.department_id);

Self-Joins Using the ON Clause


EMPLOYEES (WORKER)

EMPLOYEES (MANAGER)

MANAGER_ID in the WORKER table is equal to


EMPLOYEE_ID in the MANAGER table.

Self-Joins Using the ON Clause


SELECT e.last_name emp, m.last_name mgr
FROM
employees e JOIN employees m
ON
(e.manager_id = m.employee_id);

Joining More than two table


Employees

Departments

Locations

Joining More than two table


select first_name,department_name,city
from employees JOIN departments using(department_id)
JOIN locations using(location_id)

OR:

select first_name,department_name,city
from employees
JOIN departments ON(employees.department_id=departments.department_id)
JOIN locations
ON(departments.location_id=locations.location_id)

OR:
select first_name,department_name,city
from employees E,departments D,locations L
where E.department_id=D.department_id
and D.location_id=L.location_id

Applying Additional Conditions


to a Join
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM
employees e JOIN departments d
ON
(e.department_id = d.department_id)
AND
e.manager_id = 149 ;

NON-EQUIJOINS
EMPLOYEES

JOB_GRADES

Salary in the EMPLOYEES


table must be between
lowest salary and highest
salary in the JOB_GRADES
table.

Retrieving Records with Non-Equijoins


SELECT e.last_name, e.salary, j.grade_level
FROM
employees e JOIN job_grades j
ON
e.salary
BETWEEN j.lowest_sal AND j.highest_sal;

Summary

SQL commands can be divided into two overall


categories:

Data definition language commands

Data manipulation language commands

The ANSI standard data types are supported by


all RDBMS vendors in different ways

Basic data definition commands allow you to


create tables, indexes, and views

71

Summary (continued)

DML commands allow you to add,


modify, and delete rows from tables

The basic DML commands are


SELECT, INSERT, UPDATE, DELETE,
COMMIT, and ROLLBACK

INSERT command is used to add new


rows to tables

SELECT statement is main data


retrieval command in SQL

72

Summary (continued)

Many SQL constraints can be used with columns

The column list represents one or more column


names separated by commas

WHERE clause can be used with SELECT, UPDATE,


and DELETE statements to restrict rows affected by
the DDL command

Natural join uses join condition to match only rows


with equal values in specified columns

Right outer join and left outer join used to select


rows that have no matching values in other related
table

73

Thank You

You might also like