Lecture SQL 1

download Lecture SQL 1

of 68

Transcript of Lecture SQL 1

  • 8/4/2019 Lecture SQL 1

    1/68

    SQL

    SELECT Statement

  • 8/4/2019 Lecture SQL 1

    2/68

    Introduction

    SQL is the Structured Query Language

    It is used to interact with the DBMS SQL can

    Create Schemas in the DBMS

    Alter Schemas

    Add data

    Remove data

    Change data

    Access Data

  • 8/4/2019 Lecture SQL 1

    3/68

    DSL

    SQL is a Data Sub Language DSL

    This is a combination of two languages

    DDL Data Definition Language

    DML Data Manipulation Language

    The main way of accessing data is using the DMLcommand SELECT.

    The abilities of the SELECT command forms themajority of this material on SQL

  • 8/4/2019 Lecture SQL 1

    4/68

    Database Models

    A data model comprises

    a data structure

    a set of integrity constraints

    operations associated with the data structure

    Examples of data models include: hierarchic

    network

    relational

  • 8/4/2019 Lecture SQL 1

    5/68

    Relational Databases

    The relational data model comprises:

    relational data structure

    relational integrity constraints

    relational algebra or equivalent (SQL) SQL is an ISO language based on relational

    algebra

    relational algebra is a mathematical formulation

  • 8/4/2019 Lecture SQL 1

    6/68

    Relational Data Structure

    A relational data structure is a collection of

    tables or relations.

    A relation is a collection of rows or tuples

    A tuple is a collection of columns or attributes

    A domain is a pool of values from which theactual attribute values are taken.

  • 8/4/2019 Lecture SQL 1

    7/68

    Relational Structure cont

    Description Price

    Tuple

    Attributes

    Domain

    MENU Relation or

    Table

  • 8/4/2019 Lecture SQL 1

    8/68

    Domain and Integrity Constraints

    Domain Constraints limit the range of domain values of an attribute

    specify uniqueness and nullness of an attribute specify a default value for an attribute when no value is

    provided.

    Entity Integrity every tuple is uniquely identified by a unique non-null

    attribute, the primary key.

    Referential Integrity rows in different tables are correctly related by valid key

    values (foreign keys refer to primary keys).

  • 8/4/2019 Lecture SQL 1

    9/68

    Example Database

    In order to better understand SQL, all the examplequeries make use of a simple database.

    The database is formed from 2 tables, CAR andDRIVER.

    Each car may be owned by a DRIVER.

    A DRIVER may own multiple CARs.

    DRIVER CAR

  • 8/4/2019 Lecture SQL 1

    10/68

    DRIVER

    NAME DOB

    Jim Smith 11 Jan 1980

    Bob Smith 23 Mar 1981

    Bob Jones 3 Dec 1986

  • 8/4/2019 Lecture SQL 1

    11/68

    CAR

    REGNO MAKE COLOUR PRICE OWNER

    F611 AAA FORD RED 12000 Jim Smith

    J111 BBB SKODA BLUE 11000 Jim Smith

    A155 BDE MERCEDE

    S

    BLUE 22000 Bob Smith

    K555 GHT FIAT GREEN 6000 Bob Jones

    SC04 BFE SMART BLUE 13000

  • 8/4/2019 Lecture SQL 1

    12/68

    Each column holds data of a particular type Integer, string, decimal, blobs

    The range of values can be further constrained

    If a column in a row contains no data, it is NULL.

    It can indicate no possible value or unavailable data.

    All rows must differ from each other in some way Sometimes a row is called a tuple

    Cardinality is the number of rows of a table

    Arity is the number of columns of a table

  • 8/4/2019 Lecture SQL 1

    13/68

    Primary Keys

    In the design section the idea of a Primary Key isdefined.

    A Primary Key is a group of 1 or more columnswhich, when taken together, is unique in the table

    No part of a primary key can be NULL.

    In our example,

    DRIVER: the primary key is NAME CAR: the primary key is REGNO

    In our example this means that no two drivers canhave the same name. In the real world this would bea problem, but this is just an example.

  • 8/4/2019 Lecture SQL 1

    14/68

    Referential Integrity

    Note that there is a link between CAR and DRIVERvia OWNER.

    If there is a value in OWNER, then this value mustalso appear somewhere in DRIVER.

    If you change a drivers name in DRIVER, you must

    make sure the same change is made in OWNER of

    CAR.

    The DBMS enforces the rules.

    If you try to break the rules the DBMS reports theproblem as a REFERENTIAL INTEGRITY error.

  • 8/4/2019 Lecture SQL 1

    15/68

    SQL Basics

    Basic SQL statements include

    CREATE a data structure

    SELECT read one or more rows from a table

    INSERT one of more rows into a table

    DELETE one or more rows from a table

    UPDATE change the column values in a row

    DROP a data structure

    In this lecture the focus is on SELECT.

  • 8/4/2019 Lecture SQL 1

    16/68

    Simple SELECT SELECT column FROM tablename;

    SELECT column1,column2,column3 FROM tablename;

    SELECT * from tablename;

    SELECT * from CAR;

    REGNO MAKE COLOUR PRICE OWNER

    F611 AAA FORD RED 12000 Jim Smith

    J111 BBB SKODA BLUE 11000 Jim Smith

    A155 BDE MERCEDES BLUE 22000 Bob SmithK555 GHT FIAT GREEN 6000 Bob Jones

    SC04 BFE SMART BLUE 13000

  • 8/4/2019 Lecture SQL 1

    17/68

    SELECT regno from CAR;

    REGNOF611 AAA

    J111 BBB

    A155 BDE

    K555 GHTSC04 BFE

  • 8/4/2019 Lecture SQL 1

    18/68

    SELECT colour,owner from CAR;

    COLOUR OWNER

    RED Jim Smith

    BLUE Jim Smith

    BLUE Bob Smith

    GREEN Bob Jones

    BLUE

  • 8/4/2019 Lecture SQL 1

    19/68

    Formatting

    SPACES do not matter

    NEWLINES do not matter

    Good practice to put ; at the end of the query.

    CASE (except between single quotes) does notmatter.

    These are all valid:

    SELECT REGNO FROM CAR;

    SElecT regno

    From Car

    ;

  • 8/4/2019 Lecture SQL 1

    20/68

    Comments

    To give you the ability to make notes in queries youare allowed to have comments.

    Comments are not executed A comment starts with -- and ends with a newline

    They are only permitted within a query.

    SELECT regno -- The registration number

    FROM car -- The car storage table

    ;

  • 8/4/2019 Lecture SQL 1

    21/68

    SELECT filters

    You can have rules in your queries

    These rules are tested for each row your queryproduces

    If the rule is true, the row is displayed

    If the rule is false, the row is not displayed

    The rule starts with WHERE

    SELECT columns

    FROM table

    WHERE rule

  • 8/4/2019 Lecture SQL 1

    22/68

    Simple Rule

    A simple rule might be tolook for a car with a colour ofRED.

    The rule would be colour ='RED'

    SELECT regno FROM CAR

    SELECT regno from CAR

    WHERE colour = 'RED'

    REGNO

    F611 AAAJ111 BBB

    A155 BDE

    K555 GHT

    SC04 BFE

    REGNO

    F611 AAA

  • 8/4/2019 Lecture SQL 1

    23/68

    Note

    Things between quotes is CASE SENSITIVE.

    RED is not the same as Red or red

    Rules which mention fields they can beused if they appear on the SELECT line or

    not.

    SELECT regno from CAR

    WHERE colour = 'RED'

    REGNO COLOUR

    F611 AAA RED

  • 8/4/2019 Lecture SQL 1

    24/68

    Comparisons

    Valid comparisons include =,!=,,=

    Colour = RED The colour must be red Colour != RED The colour is not red

    Colour Red Same as !=

    Price > 10000 More than 10000

    Price >= 10000 More than or equal to 10000 Price < 10000 Cheaper than 10000

    Price

  • 8/4/2019 Lecture SQL 1

    25/68

    DATE

    Date comparisons can be tricky

    You can use all the normal comparators with dates.

    SELECT name,dob SELECT name,dob from driver

    from driver; where DOB = 3 Dec 1986;

    NAME DOB

    Jim Smith 11 Jan 1980

    Bob Smith 23 Mar 1981

    Bob Jones 3 Dec 1986

    NAME DOB

    Bob Jones 3 Dec 1986

  • 8/4/2019 Lecture SQL 1

    26/68

    The tricky part with dates is remembering that datesget bigger as you move into the future.

    DATE1>DATE2 indicates DATE1 is in the futureafter DATE2.

    SELECT name,dob from driver

    WHERE DOB >= 1 Jan 1981;

    NAME DOB

    Bob Smith 23 Mar 1981

    Bob Jones 3 Dec 1986

  • 8/4/2019 Lecture SQL 1

    27/68

    DATE Syntax

    It must be in quotes

    Each DBMS handles dates in a slightly different way

    Dates like 1 Jan 2003 work quite well.

    Oracle permits dates like 1-Jan-2003

    Oracle also permits dates like 1-Jan-03

    Be careful if you type this it will assume 2003. If you mean 1984 type 1984 not04.

    You must always specify a day and a month. If youdo not the DBMS will report an error.

  • 8/4/2019 Lecture SQL 1

    28/68

    BETWEEN

    When dealing with dates sometimes you want to testto see if a field value falls between two dates.

    The easiest way to do this is with BETWEEN

    Find all drivers born between 1995 and 1999

    SELECT name,dob from driver

    WHERE DOB between 1 Jan 1985 and 31 Dec1999

    Between works for other things, not just dates

    SELECT regno from CAR

    where price between 5000 and 10000;

  • 8/4/2019 Lecture SQL 1

    29/68

    NULL

    NULL indicates that something has no value

    It is not a value, and you cannot use normal comparison

    operators. For instance, looking for cars without owners

    Wrong: SELECT regno from car where owner = NULL;

    Wrong: SELECT regno from car where owner = NULL;

    Instead there are two special operators, IS NULL, andIS NOT NULL

  • 8/4/2019 Lecture SQL 1

    30/68

    SELECT regno from car

    WHERE OWNER is null

    SELECT regno from carWHERE OWNER is not null

    REGNO

    SC04 BFE

    REGNO

    F611 AAA

    J111 BBB

    A155 BDE

    K555 GHT

    SC04 BFE

  • 8/4/2019 Lecture SQL 1

    31/68

    LIKE

    Sometimes you want to have a rule involvingpartial strings, substrings, or wildcards

    LIKE does this, and is a slot-in replacementfor =

    If the string contains % or _, LIKE uses

    them to support wildcards. % - Matches 0 or more characters in the string

    _ - Matches exactly 1 character in the string

  • 8/4/2019 Lecture SQL 1

    32/68

    Examples

    Name LIKE Jim Smith e.g. Jim Smith

    Name LIKE _im Smith e.g. Tim Smith

    Name LIKE ___ Smith e.g. Bob Smith Name LIKE % Smith e.g. Frank Smith

    Name LIKE % S% e.g. Brian Smart

    Name LIKE Bob % e.g. Bob Martin

    Name LIKE % i.e. match anyone

    LIKE is more expensive than =

    If you are not using wildcards, always use = rather than LIKE.

  • 8/4/2019 Lecture SQL 1

    33/68

    SQL

    Logical Operators andaggregation

  • 8/4/2019 Lecture SQL 1

    34/68

    Logical Operators

    Combining rules in a single WHERE clause would beuseful

    AND and OR allow us to do this

    NOT also allows us to modify rule behaviour

    When these are combined together, problems in ruleordering can occur.

    This is solved using parentheses.

  • 8/4/2019 Lecture SQL 1

    35/68

    AND

    AND combines rules together so that they ALL must be true.

    Lets revisit the CAR table:

    REGNO MAKE COLOUR PRICE OWNER

    F611 AAA FORD RED 12000 Jim Smith

    J111 BBB SKODA BLUE 11000 Jim Smith

    A155 BDE MERCEDES BLUE 22000 Bob Smith

    K555 GHT FIAT GREEN 6000 Bob Jones

    SC04 BFE SMART BLUE 13000

  • 8/4/2019 Lecture SQL 1

    36/68

    SELECT regno from car SELECT regno from car

    where colour = BLUE; WHERE regno LIKE %5;

    REGNO

    J111 BBB

    A155 BDE

    SC04 BFE

    REGNO

    A155 BDE

    K555 GHT

  • 8/4/2019 Lecture SQL 1

    37/68

    SELECT regno from car

    WHERE colour = BLUE and regno LIKE %5%;

    REGNO

    A155 BDE

  • 8/4/2019 Lecture SQL 1

    38/68

    Multiple AND rules

    You can have as many rules as you like ANDedtogether.

    For example:

    SELECT regno

    FROM carWHERE colour = BLUE

    AND regno like %5%

    AND owner like Bob %

    ;

  • 8/4/2019 Lecture SQL 1

    39/68

    OR

    OR is like either. So long as one of the rules is true then thefilter is true.

    Looks for cars which are EITHER red or blue

    SELECT regno,colour from CAR

    WHERE colour = RED OR colour = BLUE;

    REGNO COLOUR

    F611 AAA RED

    J111 BBB BLUE

    A155 BDE BLUE

    SC04 BFE BLUE

  • 8/4/2019 Lecture SQL 1

    40/68

    NOT

    NOT inverts the rule it is put in front of:

    WHERE colour = RED

    This could be inverted as: WHERE colour != RED

    WHERE NOT colour = RED

    NOT is not really useful in this example, butcomes into its own in more complex rulesets.

  • 8/4/2019 Lecture SQL 1

    41/68

    Precedence

    Precedence is the order in which the rules are evaluated andcombined together.

    It is NOT in the order they are written. Rules are combined together firstly at AND, then OR, and

    finally at NOT.

    Consider : Car has a 5 in reg and is either red or blue.

    SELECT regno,colour from carWHERE colour = RED -- Line 1

    OR colour = BLUE -- Line 2

    AND regno LIKE %5% -- Line 3

  • 8/4/2019 Lecture SQL 1

    42/68

    Brackets

    Rewrite as:SELECT regno,colour from car

    WHERE (colour = REDOR colour = BLUE )AND regno LIKE %5%;

    Might be clearer as:SELECT regno,colour from carWHERE ( colour = RED OR colour = BLUE )AND regno LIKE %5%;

  • 8/4/2019 Lecture SQL 1

    43/68

    DISTINCT

    Find all the colours used in cars.

    SELECT colour from car; COLOUR

    RED

    BLUE

    BLUEGREEN

    BLUE

  • 8/4/2019 Lecture SQL 1

    44/68

    DISTINCT

    SELECT DISTINCT colour from car;COLOUR

    RED

    BLUE

    GREEN

  • 8/4/2019 Lecture SQL 1

    45/68

    ORDER BY

    It would be nice to be able to order the output usinga sort.

    SELECT make from car; MAKE

    FORD

    SKODA

    MERCEDESFIAT

    SMART

  • 8/4/2019 Lecture SQL 1

    46/68

    ASCending order

    Sort by alphabetical or numeric order: ASC

    ORDER BY ASC is the default.

    SELECT make from car

    ORDER BY make;

    MAKE

    FORD

    FIAT

    MERCEDESSKODA

    SMART

  • 8/4/2019 Lecture SQL 1

    47/68

    DESCending order

    Sort by reverse alphabetical or numeric order: DESC

    ORDER BY DESC must be selected.

    SELECT make from car

    ORDER BY make DESC;MAKE

    SMART

    SKODA

    MERCEDES

    FIAT

    FORD

  • 8/4/2019 Lecture SQL 1

    48/68

    Multi Column Sort

    ORDER BY can take multiple columns.

    SELECT make,colour FROM carORDER BY colour,make;

    MAKE COLOUR

    SKODA BLUE

    SMART BLUE

    MERCEDES BLUE

    FIAT GREEN

    FORD RED

  • 8/4/2019 Lecture SQL 1

    49/68

    IN

    When you have a list of OR, all on the sameattribute, then IN could be a simpler way:

    Rather Than:

    SELECT regno,make FROM car

    WHERE make = SKODA or make = SMART

    Have

    SELECT regno,make FROM car

    WHERE make in (SKODA,SMART);

  • 8/4/2019 Lecture SQL 1

    50/68

    Single Value Functions

    A single value is one number,

    Such asa literal number,544.343

    A variable in PL/SQL

  • 8/4/2019 Lecture SQL 1

    51/68

    Cont..

    Value1 + value 2

    Value1 * value 2

    Value1 - value 2

    Value1 + value 2

    ABS(value)

    COS(value) LOG(value)

    NVL(value,subsitute)

    Power(value,exponent)

    SIGN(value)

  • 8/4/2019 Lecture SQL 1

    52/68

    NULL

    Any arithmetic operation that includes a nullvalue has null as result.

    The calculated columns(whose values arethe result of a calculation)plus,subr,times,and divided are empty.

    Null is not zero,it is unknown.

  • 8/4/2019 Lecture SQL 1

    53/68

    NVL (null value substitution)

    Select client,weightfrom shipping;

    Client weight

    ----------- ------------

    John 59

    Dagg 27

    Nony

    Select client,NVL(weight,43) from

    shipping; Client weight

    ----------- ------------

    John 59

    Dagg 27

    Nony 43

  • 8/4/2019 Lecture SQL 1

    54/68

    NVL(value,subsitute)

    If values is null, this function is equal tosubsitute.

    If value is not null ,this function is equal tovalue.

    Subsitute can be a number,another columnor computation.

  • 8/4/2019 Lecture SQL 1

    55/68

    Aggregate Functions

    Aggregate functions allow you to write queries toproduce statistics on the data in the database.

    These functions are sometimes also called SETfunctions.

    These include:

    AVG (calculate the average) SUM

    MAX

    MIN

    COUNT

  • 8/4/2019 Lecture SQL 1

    56/68

    Null in aggregate function

    Group functions ignore NULL values andcalculate a result in spite of them.

    Count is special case.

    It will count all the non-NULL rows of acolumn,

    Or it will count all the rows.

  • 8/4/2019 Lecture SQL 1

    57/68

    AVERAGE

    SELECT price FROM car;

    SELECT avg(price) FROM car;

    PRICE

    12000

    11000

    22000

    6000

    13000

    AVG(PRICE)

    12800

  • 8/4/2019 Lecture SQL 1

    58/68

    SUM

    Add up all the values in a column

    SELECT sum(price) FROM car;

    SUM(PRICE)

    64000

  • 8/4/2019 Lecture SQL 1

    59/68

    MAX

    What is the maximum value in a column

    SELECT max(price) FROM car;

    max(PRICE)

    22000

  • 8/4/2019 Lecture SQL 1

    60/68

    MIN

    What is the minimum value in a column

    SELECT min(price) FROM car;

    MIN(PRICE)

    6000

  • 8/4/2019 Lecture SQL 1

    61/68

    COUNT

    How many rows make up a column

    SELECT count(price) FROM car;COUNT(PRICE)

    5

    Count(*) is similar, but also counts when price isNULL.

    SELECT count(*) FROM car;

  • 8/4/2019 Lecture SQL 1

    62/68

    COUNT DISTINCT

    Sometimes you do not want to count how many rowsare in a column, but how many different values could

    be found in that column. There is a special variant of count which does this:

    SELECT count(colour) from car;

    SELECT count(DISTINCT colour) from car;

    COUNT(colour)

    5

    COUNT(colour)

    3

  • 8/4/2019 Lecture SQL 1

    63/68

    Combining Group-value and single-

    value functions

    Select city,noon-midnight from comfort wherecity=KEENE;

    City noon-midnight

    .. ----------------------

    KEENE 41.1

    KEENE 18.4 KEENE 17.2

    KEENE -6

  • 8/4/2019 Lecture SQL 1

    64/68

    example

    Select avg(noon-midnight) from comfort

    Where city =KEENE;

    Avg(Noon-midnight)

    ------------------------

    17.675

    select avg(abs(noon-midnight) from comfort

    where city=KEENE; Avg(abs(Noon-

    midnight))

    ------------------------

    20.675

  • 8/4/2019 Lecture SQL 1

    65/68

    GROUP BY

    Aggregation functions so far have only been shown in querieswith only the single aggregation function on the select line.

    You can combine functions and non-functions on the selectline.

    To do this you need GROUP BY.

    Question: What is the most expensive car for each colour.

    Intuitively the following seems right, but will not execute!

    SELECT colour,max(price)

    FROM car;

  • 8/4/2019 Lecture SQL 1

    66/68

    SELECT colour,priceFROM car;

    SELECT colour,max(price)FROM carGROUP BY colour;

    COLOUR PRICE

    RED 12000

    BLUE 11000

    BLUE 22000

    GREEN 6000

    BLUE 13000

    COLOUR PRICE

    RED 12000

    BLUE 22000

    GREEN 6000

  • 8/4/2019 Lecture SQL 1

    67/68

    HAVING

    WHILE allows rules for each row.

    HAVING allows rules for each group of a GROUP

    BY.

    Consider the problem Who has more than 1 car.

    We would like to say:SELECT owner from car where count(owner) > 1

    Aggregate functions are not allowed in WHERE.

    They are allowed in HAVING.

  • 8/4/2019 Lecture SQL 1

    68/68

    SELECT owner,count(regno)

    FROM car

    GROUP BY ownerHAVING count(regno) > 1

    OR

    SELECT owner

    FROM carGROUP BY owner

    HAVING count(regno) > 1