Relational Language

Embed Size (px)

Citation preview

  • 8/8/2019 Relational Language

    1/69

    Structured

    QueryLanguage

  • 8/8/2019 Relational Language

    2/69

    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

  • 8/8/2019 Relational Language

    3/69

    Arithmetic Operators

    There are four arithmetic operators and theirorder ofprecedence is as follows only:

    1. Multiply (*)

    2. Division (/)3. Addition (+)

    4. Subtraction (-)

    E.g

    Select ename, salary, salary+100

    From emp;

  • 8/8/2019 Relational Language

    4/69

    ConcatenationOperator

    It concatenates columns to another columns.

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

    E.g

    Select Fname||Lname

    From emp;

  • 8/8/2019 Relational Language

    5/69

    Comparison Operators

  • 8/8/2019 Relational Language

    6/69

  • 8/8/2019 Relational Language

    7/69

    It helps in displaying rows based on a range

    of values.

    E.g

    Select Lname,salary Lower Limit Upper Limit

    From emp

    Where salaryBETWEEN25000 AND 35000

    BETWEENCondition

  • 8/8/2019 Relational Language

    8/69

    IN Condition

    It campares for values in a specified set of values. TheIN condition is also known as membership condition.

    NOT IN is opposite of IN predicate.

    E.g

    Select ename,sal,empno,deptno

    From empWhere ename IN (Ramos,Clark,Pramada,Aruna)

    Where ename NOT IN (Ramos,Clark,Pramada,Aruna)

  • 8/8/2019 Relational Language

    9/69

    LIKECondition

    LIKE condition is used to perform the wildcard searchof 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.

  • 8/8/2019 Relational Language

    10/69

    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.gSELECT empno,lname,job_id

    FROM emp

    WHERE salary>=10000 ANDjob_id LIKE 9%5

    WHERE salary>=10000 ORjob_id LIKE 9%5WHERE job_id NOT LIKE 9%5

  • 8/8/2019 Relational Language

    11/69

    Rules ofprecedence

    1. Arithmetic Operators

    2. Concatenation Operator

    3. Comparison conditions

    4. LIKE,IN

    5. BETWEEN

    6. NOT logical condition

    7. AND logical condition

    8. ORlogical condition

  • 8/8/2019 Relational Language

    12/69

    CharacterFunctions

    Single-row character functions accept character dataas input and can return both character and numericvalues. CharacterFunctions can be divided into :

    Case-manipulation function

    Character-manipulation functionLOWERconverts alpha character values to

    lowercase

    UPPER- converts alpha character values to

    uppercase

    INITCAP converts alpha character values touppercase for the first letter of eachword and all others in lowercase

  • 8/8/2019 Relational Language

    13/69

    CharacterFunctionsE.g

    SELECT empno, lname, deptno empno,LOWER(lname)

    FROM empWHERE LOWER(lname) = wills

    E.g

    SELECT empno, LOWER(lname), deptno

    FROM emp

    WHERE INITCAP(lname) = wills

  • 8/8/2019 Relational Language

    14/69

    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 allemployees)

    6. ABS SELECT ABS(n) (Absolute)

  • 8/8/2019 Relational Language

    15/69

    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 withinitial characters)

    13. RTRIM SELECT RTRIM(SUNILA,A)(Returns char removed after the last character not

    in the set.)

  • 8/8/2019 Relational Language

    16/69

    Sorting results ORDERBY - sorts the final result rows in ascending or

    descending order

    GROUP BY - groups rows in an intermediate resultstable where the values in those rows are the same forone or more columns

    HAVING - can only be used following GROUP BYand acts as a secondary WHERE clause, returning onlythose groups which meet a specified condition.Itapplies on group functions only.

  • 8/8/2019 Relational Language

    17/69

    ORDERBYClause

    It sorts rows with the ORDERBYClause

    ASC : Ascending order (by default)

    DESC : Descending order

    The ORDERBYclause comes last in the SELECTstatement

    E.gSELECT lname,job_id,hire_date SELECT lname,job_id,hire_date

    FROM emp FROM emp

    ORDERBY hire_date ORDERBY hire_date DESC

  • 8/8/2019 Relational Language

    18/69

    ORDERBY Clause

    Sorting by multiple columns

    E.g

    SELECT lname, salary

    FROM empORDERBY deptno, salary DESC;

  • 8/8/2019 Relational Language

    19/69

    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

  • 8/8/2019 Relational Language

    20/69

    GROU

    P 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;

  • 8/8/2019 Relational Language

    21/69

    HAVING Clause

    The HAVING clause can be used in conjunctionwith 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_orderORDERBY prod_no

    HAVING prod_no = p001 OR prod_no = p004

  • 8/8/2019 Relational Language

    22/69

  • 8/8/2019 Relational Language

    23/69

  • 8/8/2019 Relational Language

    24/69

  • 8/8/2019 Relational Language

    25/69

    Creating Tables

    create table

    (

    [constraint],

    [constraint],

    );

  • 8/8/2019 Relational Language

    26/69

    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)

  • 8/8/2019 Relational Language

    27/69

    Best Practices for Data Definitions -

    Tables

    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 whereverpossible

    To avoid ambiguities andpotential coding errors

    To avoid scripting bugs in MS tools (DMO, Query Analyzer)

    Security reasons

    CREATE TABLE PhoneBook(

    FirstName VARCHAR(128),

    LastName VARCHAR(128),

    PhoneNumber VARCHAR(32))

  • 8/8/2019 Relational Language

    28/69

    Explicitly indicate the target filegroup

    Important when production databases use more than one filegroup

    Specify the filegroup for

    Table data (location of datapages), e.g., ON [PRIMARY]

    TEXT / NTEXT / IMAGE / XML columns, e.g., TEXTIMAGE_ON [DEFAUL

    Talk to yourproduction 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 ofperformance impactCREATE TABLE dbo.utbPhoneBook(

    FirstName VARCHAR(128),

    LastName VARCHAR(128),

    PhoneNumber VARCHAR(32))

    ON [PRIMARY]

    Best Practices for Data Definitions

  • 8/8/2019 Relational Language

    29/69

    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

  • 8/8/2019 Relational Language

    30/69

    Example using create

    create table CD_MASTER

    (

    CD_NO number

    CONSTRAINTpk_cd PRIMARY KEY,

    CD_NAME varchar2(25),

    ARTIST varchar2(25),TYPE varchar2(15)

    );

  • 8/8/2019 Relational Language

    31/69

    Inserting Datainsert into

    (first_column, second_column,

    last_column)

    values (first_value, second_value, );

  • 8/8/2019 Relational Language

    32/69

    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 SWHERE S.name = Smith

    Powerful variants of these commands are available;more later!

  • 8/8/2019 Relational Language

    33/69

    Example using insertinsert into CD_MASTERvalues (101, Fields of

    Gold, Sting, Rock);

    insert into CD_MASTERvalues(102,

    Supernatural, Santana, Rock);

    insert into CD_MASTERvalues (103, Division

    Bell, PinkFloyd, Rock);

  • 8/8/2019 Relational Language

    34/69

    Modifying data

    update

    set =

    where ;

  • 8/8/2019 Relational Language

    35/69

    Deleting Data

    delete from

    where ;

  • 8/8/2019 Relational Language

    36/69

    Altering table definitionsalter table

    add | drop | modify

    ();

  • 8/8/2019 Relational Language

    37/69

    Deleting tables

    drop table

    [cascade constraints];

  • 8/8/2019 Relational Language

    38/69

    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'

    sid cid grade

    53831 arnatic101

    53831 Reggae203

    53650 Topology11253666 History105

    Given the following instance ofEnrolled

    S.name .cid

    Smith Topology112we get:

  • 8/8/2019 Relational Language

    39/69

    Basic Table Level Operations Creation:Using the create command

    Populating tables: Entering values into the table

    using the insertcommand 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 altercommand

    Deleting tables: Deleting tables using the dropcommand

  • 8/8/2019 Relational Language

    40/69

    SQL Overview CREATE TABLE ( , )

    INSERT INTO ()

    VALUES ()

    DELETE FROM WHERE

    UPDATE

    SET =

    WHERE

    SELECT

    FROM

    WHERE

  • 8/8/2019 Relational Language

    41/69

    Semantics of a Query

    A conceptual evaluation methodfor the previous query:

    1. do FROM clause: compute cross-productof 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 bemuch more efficient, but must produce the same answers.

  • 8/8/2019 Relational Language

    42/69

    SELECT < attribute list>

    FROM

    WHERE

    is the list of attribute names whose valuesare to be retrieved by the query

    is the list of the relation names required to

    process the query

    is a conditional expression that identifies the

    tuples to be retrieved by the query.

  • 8/8/2019 Relational Language

    43/69

    The SELECT Statement

    Is used for queries on single or multiple tables. It has the followingclauses:

    SELECT - Lists the columns (and expressions involving columns)from base tables or views to be projected into the table that will bethe result of the command

    FROM - Identifies the table(s) or view(s) from which columns willbe 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 singletable or view, and the conditions between tables or views for

    joining.

  • 8/8/2019 Relational Language

    44/69

    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

  • 8/8/2019 Relational Language

    45/69

    The SQL Query Language

    The most widely used relational querylanguage.

    To find all 18 year old students, we can

    write:SELECT *

    FROM Students S

    WHERE S.age=18

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

    SELECT S.name, S.login

    sid name login age gpa

    53666 Jones jones@cs 18 3.4

    53688 Smith smith@ee 18 3.2

  • 8/8/2019 Relational Language

    46/69

    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

  • 8/8/2019 Relational Language

    47/69

    ORDERBY

    e.g. list customer, city and state for all customers in theCUSTOMERview whose address is in Florida, Texas, CaliforniaorHawaii. List the customers alphabetically by state, andalphabetically by customer within each state: i.e. sort the resultsfirst by STATE, and within a state by CUSTOMER_NAME:

    SELECT CUSTOMER_NAME, CITY, STATE

    FROM CUSTOMER_V

    WHERE STATE IN (FL, TX, CA, HI)

    ORDERBY STATE, CU

    STOMER_NAME;

  • 8/8/2019 Relational Language

    48/69

    GROU

    P 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 eachcity to which we deliver. List the cities by state:

    SELECT STATE, CITY, COUNT(CITY)

    FROM CUSTOMER_V

    GROU

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

  • 8/8/2019 Relational Language

    49/69

    SQL statement

    processing order

  • 8/8/2019 Relational Language

    50/69

  • 8/8/2019 Relational Language

    51/69

  • 8/8/2019 Relational Language

    52/69

    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 _)

  • 8/8/2019 Relational Language

    53/69

    Creating Database Tables

    Specify target database before creatingtables

    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

  • 8/8/2019 Relational Language

    54/69

    Creating Database Tables

    Specify target database before creatingtables

    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

  • 8/8/2019 Relational Language

    55/69

    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 successfullymessage should appear in the Messagespane

    Save the query file with .sql extension

  • 8/8/2019 Relational Language

    56/69

    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.

  • 8/8/2019 Relational Language

    57/69

    Using wildcards

    The underscore ,_, is used to represent exactlyonce character

    So using LIKE _-drawer when searching

    PRODUCT_NAME will find any products with

    specified drawers, such as 3-drawer, 5-draweretc.

  • 8/8/2019 Relational Language

    58/69

    Assignment

    1. Draw the concerned E-Rdiagram 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)

  • 8/8/2019 Relational Language

    59/69

    Assignment 2

  • 8/8/2019 Relational Language

    60/69

    A i 3

  • 8/8/2019 Relational Language

    61/69

    Assignment 3

    S i lb e r s c h a t z , K o r t h a n d S u d a r s h a n

    M o d i f i c a t i o n s & a d d i t i o n s b y S B i r d 2 . 2 1

    4 3 3 - 3 5 1 , 2 0 0 3

    D a t a b a s e S y s t e m s

    E x e r c i s eE x e r c i s e

    M o v i e s S t a r s

    S t u d i o s

    t i t l e

    y e a r

    n a m e

    a d d r e s s

    n a m e a d d r e s s

    ??

    Q: What relationship or relationship set can be drawn among these

    entities? Label the attributes (if u find any appropirate for thatrelationship) also. Write the Schema for it. Specifying the Keys

    related to it (if any).

  • 8/8/2019 Relational Language

    62/69

    Sample Movie Database

    M

    ovies

    Studios

    Stars

    Owns

    Stars-in

    title year

    lengthfilmType

    name address

    address

    name

    street city zip

  • 8/8/2019 Relational Language

    63/69

    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)

  • 8/8/2019 Relational Language

    64/69

    Example Queries

    Find all loans of over $1200

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

    $1200

    Wamount> 1200(loan)

    loan-number(Wamount> 1200(loan))

  • 8/8/2019 Relational Language

    65/69

    Example Queries Find the names of all customers who have a loan,

    an account, or both, from the bank

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

    account at bank.

    customer-name (borrower)customer-name (depositor)

    customer-name (borrower)customer-name (depositor)

  • 8/8/2019 Relational Language

    66/69

    Example Queries Find the names of all customers who have a loan at thePerryridge branch.

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

    customer-name (Wbranch-name = Perryridge

    (Wborrower.loan-number = loan.loan-number(borrower x loan ))) customer-name(depositor)

    customer-name (Wbranch-name=Perryridge (Wborrower.loan-number = loan.loan-number(borrower x loan)))

  • 8/8/2019 Relational Language

    67/69

    Example Queries Find the names of all customers who have a loan at thePerryridge branch.

    Query 2

    customer-name(Wloan.loan-number = borrower.loan-number(

    (Wbranch-name = Perryridge(loan)) x borrower))

    Query 1

    customer-name(Wbranch-name = Perryridge (

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

  • 8/8/2019 Relational Language

    68/69

    Example Queries

    Find the largest account balance

    Rename accountrelation as d

    The query is:

    balance(account) - account.balance

    (Waccount.balance < d.balance (account xVd(account)))

  • 8/8/2019 Relational Language

    69/69