Relational Language

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 69

Structured

Query
Language
Working with DATES
SYSDATE is a date function that returns the
current database server date.
E.g
SELECT sysdate
FROM dual
Where dual is a dummy table
E.g
SELECT 2*2
FROM dual
Arithmetic Operators
There are four arithmetic operators and their order of
precedence is as follows only:
1. Multiply (*)
2. Division (/)
3. Addition (+)
4. Subtraction (-)

E.g
Select ename, salary, salary+100
From emp;
Concatenation Operator

It concatenates columns to another columns.


It is represented by two vertical bars (||).

E.g
Select Fname||Lname
From emp;
Comparison Operators
Literal Character String

A Literal is a character, a number, or a date


included in SELECT list. This literal must
be in single quotes(‘ ‘).
E.g
Select Lname || ‘:1 Month salary =‘|| salary
From emp;
BETWEEN Condition

It helps in displaying rows based on a range


of values.

E.g
Select Lname,salary Lower Limit Upper Limit

From emp
Where salary BETWEEN 25000 AND 35000
IN Condition

It campares for values in a specified set of values. The


IN condition is also known as membership condition.
NOT IN is opposite of IN predicate.

E.g
Select ename,sal,empno,deptno
From emp
Where ename IN (‘Ramos’,’Clark’,Pramada’,’Aruna’)
Where ename NOT IN (‘Ramos’,’Clark’,Pramada’,’Aruna’)
LIKE Condition
LIKE condition is used to perform the wildcard search
of valid search string values. Here % represents any
sequence of zero or more characters. – represents any
single character.
E.g

SELECT Lname,hire_date
FROM emp
WHERE hire_date LIKE ‘%95’;

It displays the last name and hire_date of all employees


who joined between January 1995 and December 1995.
Logical Conditions
(AND,OR,NOT)
A logical condition combines the result of two component
conditions to produce a single result based on them or
inverts the result of a single condition.
E.g
SELECT empno,lname,job_id
FROM emp
WHERE salary>=10000 AND job_id LIKE ‘9%5’
WHERE salary>=10000 OR job_id LIKE ‘9%5’
WHERE job_id NOT LIKE ‘9%5’
Rules of precedence
1. Arithmetic Operators
2. Concatenation Operator
3. Comparison conditions
4. LIKE,IN
5. BETWEEN
6. NOT logical condition
7. AND logical condition
8. OR logical condition
Character Functions
Single-row character functions accept character data
as input and can return both character and numeric
values. Character Functions can be divided into :
 Case-manipulation function
 Character-manipulation function
LOWER – converts alpha character values to
lowercase
UPPER - converts alpha character values to
uppercase
INITCAP – converts alpha character values to
uppercase for the first letter of each
word and all others in lowercase
Character Functions
E.g
SELECT empno, lname, deptno empno,LOWER(lname)
FROM emp
WHERE LOWER(lname) = ‘wills’

E.g
SELECT empno, LOWER(lname), deptno
FROM emp
WHERE INITCAP(lname) = ‘wills’
Functions
1. AVG – SELECT AVG(sell_price) (Average)
2. MIN – SELECT MIN(bal_due) (Minimum
Balance)
3. COUNT(*) – SELECT COUNT(*) (No. of
rows in the table)
4. MAX – SELECT MAX(bal_due) (Maximum
Balance)
5. SUM – SELECT SUM(sal) (Total salary of all
employees)
6. ABS – SELECT ABS(n) (Absolute)
Functions
7. POWER – SELECT POWER(3,2) (Raised)
8. ROUND – SELECT ROUND(15.19,1) (Round)
9. SQRT – SELECT SQRT(25) (Square Root)
10. SUBSTR- SELECT SUBSTR(‘SECURE’,3,4)
(Substring)
11. LENGTH – SELECT LENGTH(‘ELEPHANT’)
(Length of the string)
12. LTRIM – SELECT LTRIM(‘NISHA’,’N’) (Removes
characters from the left of char with initial characters)
13. RTRIM – SELECT RTRIM(‘SUNILA’,’A’)
(Returns char removed after the last character not in
the set.)
Sorting results
• ORDER BY - sorts the final result rows in ascending or
descending order
• GROUP BY - groups rows in an intermediate results
table where the values in those rows are the same for
one or more columns
• HAVING - can only be used following GROUP BY
and acts as a secondary WHERE clause, returning only
those groups which meet a specified condition.It
applies on group functions only.
ORDER BY Clause
It sorts rows with the ORDER BY Clause
 ASC : Ascending order (by default)
 DESC : Descending order
The ORDER BY clause comes last in the SELECT
statement
E.g
SELECT lname,job_id,hire_date SELECT lname,job_id,hire_date
FROM emp FROM emp
ORDER BY hire_date ORDER BY hire_date DESC
ORDER BY Clause

Sorting by multiple columns


E.g

SELECT lname, salary


FROM emp
ORDER BY deptno, salary DESC;
GROUP BY Clause

The GROUP BY clause is used to group


rows based on distinct values that exists for
specified columns.

E.g
SELECT prod_no, sum(qty_ordered)
FROM sales_order
GROUP BY prod_no
GROUP BY
• e.g. count the number of customers with
addresses in each state to which we deliver:

SELECT STATE, COUNT(STATE)


FROM CUSTOMER_V
GROUP BY STATE;
HAVING Clause
The HAVING clause can be used in conjunction
with the GROUP BY clause. HAVING imposes a
condition on the group by clause, which further
filters the groups created by the group by clause.
E.g
SELECT prod_no, sum(qty_ordered)
FROM sales_order
ORDER BY prod_no
HAVING prod_no = ‘p001’ OR prod_no = ‘p004’
Creating Tables

create table <table_name>


(
<column1> <datatype> [constraint],
<column2> <datatype> [constraint],
… … …
);
Creating Relations in SQL
• Creates the Students relation.
– Note: the type (domain) of each field is specified,
and enforced by the DBMS whenever tuples are
added or modified.

CREATE TABLE Students


(sid CHAR(20),
name CHAR(20),
login CHAR(10),
age INTEGER,
avg FLOAT)
Best Practices for Data Definitions -
Tables
CREATE TABLE PhoneBook(
FirstName VARCHAR(128),
LastName VARCHAR(128),
PhoneNumber VARCHAR(32))
• Naming conventions
– Make sure that table names follow a pre-determined naming convention
• e.g., every table name starts with ‘tub’
• Keep table names short, precise, self-explanatory, and clean
• Avoid spaces and wildcards (e.g., ‘_’) in object names
• To avoid ambiguities
• To easily search for the object in the database by name

• Explicitly indicate the table owner


– Use the dbo object owner wherever possible
• To avoid ambiguities and potential coding errors
• To avoid scripting bugs in MS tools (DMO, Query Analyzer)
• Security reasons
Best Practices for Data Definitions
• Explicitly indicate the target filegroup
– Important when production databases use more than one filegroup
– Specify the filegroup for
• Table data (location of data pages), e.g., ON [PRIMARY]
• TEXT / NTEXT / IMAGE / XML columns, e.g., TEXTIMAGE_ON [DEFAULT
– Talk to your production DB administrator!

• Make sure that total column length does not exceed 8060 bytes
– SQL 2K gives a warning upon such table creation; error upon 8060+ insert
– SQL 2005 handles 8060+ tables with variable length columns
• At a price of performance impact
CREATE TABLE dbo.utbPhoneBook(
FirstName VARCHAR(128),
LastName VARCHAR(128),
PhoneNumber VARCHAR(32))
ON [PRIMARY]
Best Practices for Data Definitions -
Columns
• Naming convention
– Column names should be standardized, self-explanatory

• Every table must have a unique identifier


– A column with distinct entries
– A set of columns that their combined value is unique
• Number of columns should be kept minimal

• Add a fixed set of columns to every table


– e.g., InsertTime, UpdateTime, SQLLogin, BitArray
– Helps to control, synchronize, and audit data
– Populate these columns with an UPDATE trigger
– Do not use timestamp/rowversion column types
• Column types do not contain enough information
– These columns may be omitted in performance sensitive tables
• Minimize overhead and performance impact
Example using “create”

create table CD_MASTER


(
CD_NO number
CONSTRAINT pk_cd PRIMARY KEY,
CD_NAME varchar2(25),
ARTIST varchar2(25),
TYPE varchar2(15)
);
Inserting Data
insert into <table_name>

(first_column, second_column, …
last_column)

values (first_value, second_value, … );


Adding and Deleting Tuples
• Can insert a single tuple using:
INSERT INTO Students (sid, name, login, age, avg)
VALUES (‘53688’, ‘Smith’, ‘smith@ee’, 18, 3.2)

• Can delete all tuples satisfying some condition


(e.g., name = Smith):

DELETE
FROM Students S
WHERE S.name = ‘Smith’
Powerful variants of these commands are available;
more later!
Example using “insert”
insert into CD_MASTER values (101, ‘Fields of
Gold’, ‘Sting’, ‘Rock’);

insert into CD_MASTER values(102,


‘Supernatural’, ‘Santana’, ‘Rock’);

insert into CD_MASTER values (103, ‘Division


Bell’, ‘Pink Floyd’, ‘Rock’);
Modifying data

update <table_name>

set <column_name> = <new_value>

where <condition>;
Deleting Data

delete from <table_name>

where <SQL_condition>;
Altering table definitions
alter table <table_name>

add | drop | modify

(<column specification[s]>);
Deleting tables

drop table <table_name>

[cascade constraints];
Querying Multiple Relations
• What does the following query compute?
SELECT S.name, E.cid
FROM Students S, Enrolled E
WHERE S.sid=E.sid AND E.grade='A'

Given the following instance of sid cid grade


Enrolled 53831 Carnatic101 C
53831 Reggae203 B
53650 Topology112 A
53666 History105 B

S.name E.cid
we get:
Smith Topology112
Basic Table Level Operations
• Creation: Using the create command
• Populating tables: Entering values into the table using
the insert command
• Modifying data: Modifying data in the tables using the
update command
• Deleting data: Deleting data from tables using the delete
command
• Altering tables: Using the alter command
• Deleting tables: Deleting tables using the drop command
SQL Overview
• CREATE TABLE <name> ( <field> <domain>, … )

• INSERT INTO <name> (<field names>)


VALUES (<field values>)

• DELETE FROM <name>


WHERE <condition>

• UPDATE <name>
SET <field name> = <value>
WHERE <condition>

• SELECT <fields>
FROM <name>
WHERE <condition>
Semantics of a Query

• A conceptual evaluation method for the previous query:


1. do FROM clause: compute cross-product of Students and
Enrolled
2. do WHERE clause: Check conditions, discard tuples that fail
3. do SELECT clause: Delete unwanted fields
• Remember, this is conceptual. Actual evaluation will be
much more efficient, but must produce the same answers.
SELECT < attribute list>
FROM <table list>
WHERE <condition>

<attribute list> is the list of attribute names whose values


are to be retrieved by the query
<table list> is the list of the relation names required to
process the query
<condition> is a conditional expression that identifies the
tuples to be retrieved by the query.
The SELECT Statement

• Is used for queries on single or multiple tables. It has the following clauses:
• SELECT - Lists the columns (and expressions involving columns) from base tables
or views to be projected into the table that will be the result of the command
• FROM - Identifies the table(s) or view(s) from which columns will be chosen to
appear in the result table, and includes the tables or views needed to join tables to
process the query
• WHERE - Includes the conditions for row selection within a single table or view,
and the conditions between tables or views for joining.

• .
SELECT Example
• Find products with standard price less than $275

• SELECT PRODUCT_NAME, STANDARD_PRICE


• FROM PRODUCT_V
• WHERE STANDARD_PRICE < 275

Comparison Operators in SQL


The SQL Query Language
• The most widely used relational query
language.
• To find all 18 year old students, we can
write:
SELECT * sid name login age gpa
FROM Students S
WHERE S.age=18 53666 Jones jones@cs 18 3.4
53688 Smith smith@ee 18 3.2

• To find just names and logins, replace the first line:


SELECT S.name, S.login
Distinct and *
• If the user does not want to see duplicate rows in the
result, SELECT DISTINCT can be used, so SELECT
DISTINCT PRODUCT_NAME would display a results
table without duplicate rows
• SELECT * (where * is a wildcard to indicate all columns)
displays all columns from all the tables or views in the
FROM clause
ORDER BY
• e.g. list customer, city and state for all customers in the
CUSTOMER view whose address is in Florida, Texas, California
or Hawaii. List the customers alphabetically by state, and
alphabetically by customer within each state: i.e. sort the results
first by STATE, and within a state by CUSTOMER_NAME:

• SELECT CUSTOMER_NAME, CITY, STATE


• FROM CUSTOMER_V
• WHERE STATE IN (‘FL’, ‘TX’, ‘CA’, ‘HI’)
• ORDER BY STATE, CUSTOMER_NAME;
GROUP BY
• It is also possible to nest groups within groups, the same logic is
used as when sorting multiple items
• e.g. count the number of customers with addresses in each city to
which we deliver. List the cities by state:
• SELECT STATE, CITY, COUNT(CITY)
• FROM CUSTOMER_V
• GROUP BY STATE, CITY;
• In general, each column referenced in the SELECT statement
must be referenced in the GROUP BY clause, unless the column
is an argument for an aggregate function included in the
SELECT clause.
SQL statement
processing order
Creating and Managing
Database Tables
• Naming conventions for tables and columns
– Must begin with a letter
– Between one and 128 characters
• Alphanumeric characters
• Symbols
• Special characters like @, #, $, _
– Place the table or field name in square brackets if
• The name begins with a character or symbol
• Name contains a reserved word
– Good idea: avoid special characters, reserved words
and symbols (except for _)
Creating Database Tables
• Specify target database before creating
tables
• Three ways to specify target database
– Select the target database in the Object
Explorer
– Select the target database in the database list on
the Management Studio toolbar
– Execute the T-SQL USE command
• USE DatabaseName
Creating Database Tables
• Specify target database before creating
tables
• Three ways to specify target database
– Select the target database in the Object
Explorer
– Select the target database in the database list on
the Management Studio toolbar
– Execute the T-SQL USE command
• USE DatabaseName
Creating Database Tables
• Open the Query Editor window
• Type the SQL commands in Query Editor
– To specify target database
– To create the table
• Execute the query
– “Command(s) completed successfully”
message should appear in the Messages pane
• Save the query file with .sql extension
Using wildcards

• Wildcards can also be used in the WHERE clause if an


exact match is not possible
• Here the keyword LIKE is paired with wildcard characters
and usually a string containing the characters that are
known to be the desired matches
• The wildcard character ‘%’ is used to represent any
collection of characters
• e.g. using LIKE ‘%DESK’ when searching
PRODUCT_DESCRIPTION will find all the different
kinds of desks.
Using wildcards

• The underscore ,_, is used to represent exactly


once character
• So using LIKE ‘_-drawer’ when searching
PRODUCT_NAME will find any products with
specified drawers, such as ‘3-drawer’, ‘5-drawer’
etc.
Assignment

1. Draw the concerned E-R diagram for it:


University Schema
STUDENT(studno,name,hons,tutor,year)

ENROL(studno,courseno,labmark,exammark)

COURSE(courseno,subject,equip)

STAFF(lecturer,roomno,appraiser)

TEACH(courseno,lecturer)

YEAR(yearno,yeartutor)
Assignment 2
                                                                                                                         
Assignment 3
Q: What relationship or relationship set can be drawn among these
entities? Label the attributes (if u find any appropirate for that
relationship) also. Write the Schema for it. Specifying the Keys
related to it (if any).
Exercise

title
name

Movies Stars
year
address

Studios

name address

433-351, 2003 ©Silberschatz, Korth and Sudarshan


Database Systems Modifications & additions by S Bird
2.21
Sample Movie Database
name address
title year

Stars-in Stars
Movies

name
length
filmType
Owns
Studios

address

street city zip


Banking Example
branch (branch-name, branch-city, assets)

customer (customer-name, customer-street, customer-only)

account (account-number, branch-name, balance)

loan (loan-number, branch-name, amount)

depositor (customer-name, account-number)

borrower (customer-name, loan-number)


Example Queries
• Find all loans of over $1200

amount > 1200 (loan)

Find the loan number for each loan of an amount greater than

$1200
loan-number (amount > 1200 (loan))
Example Queries
• Find the names of all customers who have a loan, an
account, or both, from the bank
customer-name (borrower)  customer-name (depositor)

Find the names of all customers who have a loan and an

account at bank.

customer-name (borrower)  customer-name (depositor)


Example Queries
• Find the names of all customers who have a loan at the
Perryridge branch.
customer-name (branch-name=“Perryridge”

(borrower.loan-number = loan.loan-number(borrower x loan)))


 Find the names of all customers who have a loan at the
Perryridge branch but do not have an account at any branch of
the bank.

customer-name (branch-name = “Perryridge”

(borrower.loan-number = loan.loan-number(borrower x loan))) –


customer-name(depositor)
Example Queries
• Find the names of all customers who have a loan at the Perryridge branch.

Query 1
customer-name(branch-name = “Perryridge” (
borrower.loan-number = loan.loan-number(borrower x loan)))

 Query 2

customer-name(loan.loan-number = borrower.loan-number(
(branch-name = “Perryridge”(loan)) x borrower))
Example Queries
Find the largest account balance
• Rename account relation as d
balance
• The query(account)
is: - account.balance

(account.balance < d.balance (account x d (account)))

You might also like