SQL_CONSTRAINTS

download SQL_CONSTRAINTS

of 41

Transcript of SQL_CONSTRAINTS

  • 8/7/2019 SQL_CONSTRAINTS

    1/41

    1

    The TOP option is used for limiting the output of a query result set. TOP can

    either specify the number of rows to return, or the percentage of rows to return.The ORDER BY clause can be used successfully with the TOP option.

    SELECT TOP 10 *FROM employees

    SELECT TOP 20 PERCENT *FROM employees

    SELECT TOP 10 *

    FROM employeesORDER BY Salary DESC

    Using TOP and PERCENT

    SELECT TOP 1 WITH TIES * FROM EMPORDER BY SAL

  • 8/7/2019 SQL_CONSTRAINTS

    2/41

    2

    INTO clause creates a new table and inserts rows and columns listed in theSELECT statement into it. INTO clause also inserts existing rows into a newtable.

    SELECT EMPNO,ENAME,JOB INTOEMP20 FROM EMPWHERE DEPTNO =10;

    INTO CLAUSE

  • 8/7/2019 SQL_CONSTRAINTS

    3/41

    3

    [ ] (Wildcard - Character(s) to Match)

    Matches any single character within the specified range or set

    that is specified between the brackets.

    SELECT * FROM EMPWHERE SAL LIKE '[0-9][0-9][0-9]'

  • 8/7/2019 SQL_CONSTRAINTS

    4/41

    4

    [^] (Wildcard - Character(s) Not to Match)

    Matches any single character that is not within the range or setspecified between the square brackets.

    SELECT * FROM EMP

    WHERE ENAME LIKE 'A[^L]%'

  • 8/7/2019 SQL_CONSTRAINTS

    5/41

    5

    SELECT AVG(SAL),DEPTNOFROM EMPWHERE DEPTNO IN(10,20)GROUP BY ALL DEPTNO

    GROUP BY ALL

    If you use ALL, the query results include all groups produced by theGROUP BY clause, even if some of the groups have no rows that meetthe search conditions. Without ALL, a SELECT statement that includesGROUP BY does not show groups for which no rows qualify.

  • 8/7/2019 SQL_CONSTRAINTS

    6/41

    6

    SELECT AVG(SAL),DEPTNO,JOB

    FROM EMPGROUP BY DEPTNO ,JOB WITH CUBE

    GROUP BY CUBE

    CUBE is an aggregate operator that produces a super aggregate row.

    In addition to the usual rows provided by the GROUP BY, it alsoprovides the summary of the rows that the GROUP BY clausegenerates.

    The Summary row is displayed for every possible combination ofgroups in the result set.

    The Summary row displays NULL in the result set

  • 8/7/2019 SQL_CONSTRAINTS

    7/41

  • 8/7/2019 SQL_CONSTRAINTS

    8/41

    8

    SQL Insert

    The SQL INSERT command allows you to insert arecord into a table in your database.

    INSERT INTO Student (Rollno, name, age)

    VALUES ( 1, 'Benny', 12)

  • 8/7/2019 SQL_CONSTRAINTS

    9/41

    9

    SQL Update

    The SQL UPDATE statement allows you to update an existingrecord in the database.

    The UPDATE command uses a WHERE clause. If you don't use a

    WHERE clause, all rows will be updated.

    UPDATE student

    SET age = 12WHERE rollno = 1

  • 8/7/2019 SQL_CONSTRAINTS

    10/41

    10

    SQL Delete

    The SQL DELETE statement allows you to delete a record from the database.

    The DELETE command uses a WHERE clause. If you don't use a WHEREclause, all rows in the table will be deleted.

    DELETE FROM Individual

    WHERE Rollno = 1

  • 8/7/2019 SQL_CONSTRAINTS

    11/41

    11

    Data type Range Storage

    bigint-2^63 (-9,223,372,036,854,775,808) to2^63-1 (9,223,372,036,854,775,807)

    8 Bytes

    int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes

    smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes

    tinyint 0 to 255 1 Byte

  • 8/7/2019 SQL_CONSTRAINTS

    12/41

    12

    numeric (p, s)Fixed-precision and scale-numeric data from10^38+1 through 10^381.

    Storage size is 19 bytes.

    money

    Monetary data values from (

    2^63/10000) (

    922,337,203,685,477.5808)through 2^631 (922,337,203,685,477.5807)

    Storage size is 8 bytes.

  • 8/7/2019 SQL_CONSTRAINTS

    13/41

    13

    datetime Date and time data from January 1, 1753, to December 31, 9999,

    smalldatetime January 1, 1900, through June 6, 2079

  • 8/7/2019 SQL_CONSTRAINTS

    14/41

    14

    char [ ( n ) ]Fixed-length, non-Unicode character data with a length of nbytes. n

    must be a value from 1 through 8,000.

    varchar [ ( n | max ) ]Variable-length, non-Unicode character data. ncan be a value from 1through 8,000.

    text Variable-length with a maximum length of 2^31-1 (2,147,483,647)characters.

  • 8/7/2019 SQL_CONSTRAINTS

    15/41

    15

    national character(n)

    Synonym: nchar(n)

    Fixed-length Unicode data with a maximum length of 4000 characters.

    national character

    varying(n)

    Synonym: nvarchar(n)

    Variable-length Unicode data with a length of 1 to 4000 characters.

  • 8/7/2019 SQL_CONSTRAINTS

    16/41

    16

    ntext

    Variable-length Unicode data with a maximum length of (2^302)/2

    (536,870,911) characters.

    binary(n) Fixed-length binary data with a maximum length of 8000 bytes.

    varbinary(n) Variable-length binary data with a maximum length of 8000 bytes.

    image

    Variable-length binary data with a maximum length of 2^301

    (1,073,741,823) bytes.

    Storage is the length of the value in bytes.

    uniqueidentifier A globally unique identifier (GUID). Storage size is 16 bytes.

  • 8/7/2019 SQL_CONSTRAINTS

    17/41

    17

    IDENTITY [(s, i)]

    Only data columns of the integer data types can be used for identity columns. A table canhave only one identity column. A seed and increment can be specified and the columncannot be updated.s (seed) = starting valuei (increment) = increment value

    ROWGUIDCOLThis is a property of a data column, not a distinct data type. It is a column in a table that isdefined by using the uniqueidentifier data type. A table can have only one ROWGUIDCOLcolumn.

  • 8/7/2019 SQL_CONSTRAINTS

    18/41

    18

    Using the IDENTITY property with CREATE TABLE

    IDENTITY property for an automatically incrementing identification number.

    CREATE TABLE employees ( id_num int IDENTITY(1,1),fname varchar (20), lname varchar(30) )

    INSERT employees (fname, lname) VALUES ('Karin, 'Josephs')

  • 8/7/2019 SQL_CONSTRAINTS

    19/41

    Naming Conventions

    Must begin with a letter

    Can be 130 characters long

    Must contain only AZ, az, 09 , _ Must not duplicate the name of another

    object owned by the same user

    Must not be an reserved word

  • 8/7/2019 SQL_CONSTRAINTS

    20/41

    The CREATE TABLE Statement

    You specify: Table name

    Column name, column datatype, and columnsize

    CREATE TABLE [schema.]table

    (column datatype [DEFAULT expr];

  • 8/7/2019 SQL_CONSTRAINTS

    21/41

    The DEFAULT Option

    Specify a default value for a column duringan insert.

    job varchar(15) DEFAULT clerk,

  • 8/7/2019 SQL_CONSTRAINTS

    22/41

    Creating Tables

    SQL> CREATE TABLE dept

    2 (deptno NUMBER(2),

    3 dname VARCHAR(14),

    4 loc VARCHAR(13));

    Table created.

    Create the table.

  • 8/7/2019 SQL_CONSTRAINTS

    23/41

    The ALTER TABLE Statement

    Use the ALTER TABLE statement to: Add a new column

    Modify an existing column

    Define a default value for the new columnALTER TABLE table

    ADD (column datatype [DEFAULT expr];

    ALTER TABLE table

    ALTER COLUMN(column_name datatype [DEFAULT expr]);

  • 8/7/2019 SQL_CONSTRAINTS

    24/41

    Adding a Column

    DEPT30

    EMPNO ENAME ANNSAL HIREDATE------ ---------- --------

    7698 BLAKE 34200 01-MAY-81

    7654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-81

    7844 TURNER 18000 08-SEP-81...

    add a

    newcolumnintoDEPT30table

    DEPT30

    EMPNO ENAME ANNSAL HIREDATE

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

    7698 BLAKE 34200 01-MAY-817654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-81

    7844 TURNER 18000 08-SEP-81...

    JOB

    JOB

    New column

  • 8/7/2019 SQL_CONSTRAINTS

    25/41

    Adding a Column

    You use the ADD clause to add columns.

    EMPNO ENAME ANNSAL HIREDATE JOB

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

    7698 BLAKE 34200 01-MAY-81

    7654 MARTIN 15000 28-SEP-817499 ALLEN 19200 20-FEB-81

    7844 TURNER 18000 08-SEP-81

    ...

    6 rows selected.

    SQL> ALTER TABLE dept30

    2 ADD (job VARCHAR(9));

    Table altered.

    The new column becomes the last column.

  • 8/7/2019 SQL_CONSTRAINTS

    26/41

    Modifying a Column

    You can change a column's datatype,size, and default value.

    A change to the default value affects

    only subsequent insertions to the table.

    ALTER TABLE dept30

    ALTER COLUMN (ename VARCHAR(15));

    Table altered.

  • 8/7/2019 SQL_CONSTRAINTS

    27/41

    Dropping a Table

    All data and structure in the table isdeleted.

    Any pending transactions are committed.

    All indexes are dropped.

    You cannot roll back this statement.

    SQL> DROP TABLE dept30;

    Table dropped.

  • 8/7/2019 SQL_CONSTRAINTS

    28/41

    Truncating a Table

    The TRUNCATE TABLE statement: Removes all rows from a table

    Releases the storage space used by thattable

    Cannot roll back row removal whenusing TRUNCATE

    Alternatively, remove rows by using theDELETE statement

    SQL> TRUNCATE TABLE department;

    Table truncated.

  • 8/7/2019 SQL_CONSTRAINTS

    29/41

    What Are Constraints?

    Constraints enforce rules at the table level. Constraints prevent the deletion of a table if

    there are dependencies.

    The following constraint types are :- NOT NULL

    UNIQUE Key

    PRIMARY KEY

    FOREIGN KEY CHECK

  • 8/7/2019 SQL_CONSTRAINTS

    30/41

    Constraint Guidelines

    Create a constraint: At the same time as the table is created

    After the table has been created

    Define a constraint at the column or tablelevel.

  • 8/7/2019 SQL_CONSTRAINTS

    31/41

    Defining Constraints

    CREATE TABLE [schema.]table

    (column datatype [DEFAULT expr]

    [column_constraint],

    [table_constraint]);

    CREATE TABLE emp(

    empno NUMBER(4),

    ename VARCHAR(10),

    deptno NUMBER(7,2) NOT NULL,CONSTRAINT emp_empno_pk

    PRIMARY KEY (EMPNO));

  • 8/7/2019 SQL_CONSTRAINTS

    32/41

    The NOT NULL Constraint

    Ensures that null values are notpermitted for the column

    EMP

    EMPNO ENAME JOB ... COMM DEPTNO

    7839 KING PRESIDENT 10

    7698 BLAKE MANAGER 307782 CLARK MANAGER 10

    7566 JONES MANAGER 20...

    NOT NULL constraint(no row may containa null value forthis column)

    Absence of NOT NULLconstraint(any row can containnull for this column)

    NOT NULL constraint

  • 8/7/2019 SQL_CONSTRAINTS

    33/41

    The NOT NULL Constraint

    Defined at the column level

    SQL> CREATE TABLE emp(

    2 empno NUMBER(4),

    3 ename VARCHAR(10) NOT NULL,

    4 job VARCHAR(9),5 mgr NUMBER(4),

    6 hiredate DATE,

    7 sal NUMBER(7,2),

    8 comm NUMBER(7,2),

    9 deptno NUMBER(7,2) NOT NULL);

  • 8/7/2019 SQL_CONSTRAINTS

    34/41

    The UNIQUE Key Constraint

    DEPT

    DEPTNO DNAME LOC

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

    10 ACCOUNTING NEW YORK20 RESEARCH DALLAS

    30 SALES CHICAGO40 OPERATIONS BOSTON

    UNIQUE key constraint

    50 SALES DETROIT

    60 BOSTON

    Insert into Not allowed(DNAME SALES

    already exists)

    Allowed

  • 8/7/2019 SQL_CONSTRAINTS

    35/41

  • 8/7/2019 SQL_CONSTRAINTS

    36/41

    The PRIMARY KEY Constraint

    DEPT

    DEPTNO DNAME LOC

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

    10 ACCOUNTING NEW YORK20 RESEARCH DALLAS

    30 SALES CHICAGO40 OPERATIONS BOSTON

    PRIMARY KEY

    Insert into

    20 MARKETING DALLAS

    FINANCE NEW YORK

    Not allowed(DEPTNO 20 alreadyexists)

    Not allowed(DEPTNO is null)

  • 8/7/2019 SQL_CONSTRAINTS

    37/41

    The PRIMARY KEY Constraint

    Defined at either the table level or thecolumn level

    SQL> CREATE TABLE dept(

    2 deptno NUMBER(2),3 dname VARCHAR(14),

    4 loc VARCHAR(13),

    5 CONSTRAINT dept_dname_uk UNIQUE (dname),

    6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));

  • 8/7/2019 SQL_CONSTRAINTS

    38/41

    The FOREIGN KEY Constraint

    DEPT

    DEPTNO DNAME LOC------ ---------- --------

    10 ACCOUNTING NEW YORK

    20 RESEARCH DALLAS...

    PRIMARYKEY

    EMPEMPNO ENAME JOB ... COMM DEPTNO

    7839 KING PRESIDENT 107698 BLAKE MANAGER 30

    ...

    FOREIGNKEY

    7571 FORD MANAGER ... 200 9

    7571 FORD MANAGER ... 200

    Insert into

    Not allowed

    (DEPTNO 9does not exist inthe DEPT table

    Allowed

  • 8/7/2019 SQL_CONSTRAINTS

    39/41

  • 8/7/2019 SQL_CONSTRAINTS

    40/41

    Adding a Constraint

    Add a FOREIGN KEY constraint to theEMP table indicating that a managermust already exist as a valid employee

    in the EMP table.SQL> ALTER TABLE emp2 ADD CONSTRAINT emp_mgr_fk

    3 FOREIGN KEY(mgr) REFERENCES emp(empno);

    Table altered.

  • 8/7/2019 SQL_CONSTRAINTS

    41/41

    Dropping a Constraint

    Remove the manager constraint fromthe EMP table.

    SQL> ALTER TABLE emp

    2 DROP CONSTRAINT emp_mgr_fk;

    Table altered.