SQL Integrity Constraints 1
-
Upload
nilay-ghosh -
Category
Documents
-
view
222 -
download
0
Transcript of SQL Integrity Constraints 1
-
8/8/2019 SQL Integrity Constraints 1
1/64
STRUCTURED QUERY
LANGUAGE (SQL)
-
8/8/2019 SQL Integrity Constraints 1
2/64
STRUCTURED QUERY LANGUAGE SQL stands for Structured Query Language and can be
pronounced as SQL or sequel (Structured English QueryLanguage).
It is a query language used for accessing and modifyinginformation in the database.
IBM first developed SQL in 1970s. Also it is an ANSI/ISOstandard.It has become a Standard Universal Language usedby most of the relational database management systems(RDBMS).
Some of the RDBMS systems are: Oracle, Microsoft SQLserver, Sybase etc.Most of these have provided their own
implementation thus enhancing it's feature and making it apowerful tool.
Few of the sql commands used in sql programming areSELECT Statement, UPDATE Statement, INSERT INTOStatement, DELETE Statement, WHERE Clause, ORDER
BY Clause, GROUP BY Clause, ORDER Clause, Joins,Views, GROUP Functions, Indexes etc.
-
8/8/2019 SQL Integrity Constraints 1
3/64
CREATE DATABASE Statement The CREATE DATABASE statement is used
to create a database.
SQL CREATE DATABASE Syntax
CREATE DATABASE database_name
-
8/8/2019 SQL Integrity Constraints 1
4/64
The CREATE TABLE Statement The CREATE TABLE statement is used to create a
table in a database.
SQL CREATE TAB
LE Syntax CREATE TABLE table_name
(column_name1 data_type,column_name2 data_type,column_name3 data_type,....
)
-
8/8/2019 SQL Integrity Constraints 1
5/64
STRUCTURED QUERY LANGUAGE In a simple manner, SQL is a non-procedural,
English-like language that processes data in groupsof records rather than one record at a time.Fewfunctions of SQL are:
store data
modify data
retrieve data modify data
delete data
create tables and other database objects
-
8/8/2019 SQL Integrity Constraints 1
6/64
STRUCTURED QUERY LANGUAGE Database Tables
A database most often contains one or more tables. Each table isidentified by a name (e.g. "Customers" or "Orders"). Tables containrecords (rows) with data.
Below is an example of a table called "Persons":
P_Id LastName FirstName Address City
1 HANSEN ANNIE L.A CAL
2 PEETERSON R ICKY N.Y N.Y
3 SLEDON JONES GER CHI
-
8/8/2019 SQL Integrity Constraints 1
7/64
STRUCTURED QUERY LANGUAGE SQL Statements
Most of the actions you need to perform on a
database are done with SQL statements.
The following SQL statement will select all
the records in the "Persons" table:
SELECT * FROM Persons
-
8/8/2019 SQL Integrity Constraints 1
8/64
SQL DML and DDL SQL can be divided into two parts: The Data Manipulation Language (DML) and
the Data Definition Language (DDL).
The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted.It alsodefine indexes (keys), specify links between tables, and impose constraintsbetween tables. The most important DDL statements in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROPINDEX - deletes an index
-
8/8/2019 SQL Integrity Constraints 1
9/64
SQL SELECT Statement The SELECT statement is used to select data from a
database.
The result is stored in a result table, called the result-set.
SQL SELECT Syntax
SELECT column_name(s)F
ROM
table_name and
SELECT * FROM table_name
-
8/8/2019 SQL Integrity Constraints 1
10/64
SQL SELECT DISTINCT Statement In a table, some of the columns may contain
duplicate values. This is not a problem, however,
sometimes you will want to list only the different(distinct) values in a table.
The DISTINCT keyword can be used to return only
distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)
FROM table_name
-
8/8/2019 SQL Integrity Constraints 1
11/64
WHERE Clause The WHERE clause is used to extract only
those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
-
8/8/2019 SQL Integrity Constraints 1
12/64
ORDERBY Keyword The ORDERBY keyword is used to sort the result-
set by a specified column.
The ORDERBY keyword sort the records inascending order by default.
If you want to sort the records in a descending order,you can use the DESC keyword.
SQL ORDERB
Y Syntax SELECT column_name(s)
FROM table_nameORDERBY column_name(s) ASC|DESC
-
8/8/2019 SQL Integrity Constraints 1
13/64
INSERT INTO Statement The INSERT INTO statement is used to insert a new row in a
table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in twoforms.
The first form doesn't specify the column names where thedata will be inserted, only their values:
INSERT INTO table_nameVALUES (value1, value2, value3,...)
The second form specifies both the column names and thevalues to be inserted:
INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)
-
8/8/2019 SQL Integrity Constraints 1
14/64
UPDATE Statement The UPDATE statement is used to update
existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
-
8/8/2019 SQL Integrity Constraints 1
15/64
DELETE Statement The DELETE statement is used to delete rows
in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value
-
8/8/2019 SQL Integrity Constraints 1
16/64
-
8/8/2019 SQL Integrity Constraints 1
17/64
SQL Wildcards SQL wildcards can substitute for one or more
characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE
operator WildcardDescription
% ->A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] ->Any single character in charlist [^charlist] or [!charlist] ->Any single character not
in charlist
-
8/8/2019 SQL Integrity Constraints 1
18/64
IN Operator The IN operator allows you to specify
multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
-
8/8/2019 SQL Integrity Constraints 1
19/64
BETWEEN Operator The BETWEEN operator selects a range of
data between two values. The values can be
numbers, text, or dates. SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_nameWHERE column_name BETWEEN value1
AND value2
-
8/8/2019 SQL Integrity Constraints 1
20/64
SQL Alias You can give a table or a column another name by using an
alias. This can be a good thing to do if you have very long orcomplex table names or column names.
An alias name could be anything, but usually it is short. SQL Alias Syntax for Tables
SELECT column_name(s)FROM table_nameAS alias_nameSQL Alias Syntax for Columns
SELECT column_name AS alias_nameFROM table_name
-
8/8/2019 SQL Integrity Constraints 1
21/64
SQL JOIN The JOIN keyword is used in an SQL statement to
query data from two or more tables, based on arelationship between certain columns in these tables.
Tables in a database are often related to each otherwith keys.
A primary key is a column (or a combination ofcolumns) with a unique value for each row. Each
primary key value must be unique within the table.The purpose is to bind data together, across tables,without repeating all of the data in every table.
-
8/8/2019 SQL Integrity Constraints 1
22/64
Different SQL JOINs JOIN: Return rows when there is at least one match
in both tables
LEFT JOIN: Return all rows from the left table,even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table,
even if there are no matches in the left table
FULL JOIN: Return rows when there is a match inone of the tables
-
8/8/2019 SQL Integrity Constraints 1
23/64
SQL INNER JOIN Keyword The INNER JOIN keyword return rows when
there is at least one match in both tables.
SQL INNER JOIN Syntax SELECT column_name (s)
FROM table_name1INNER JOIN table_name2
ONtable_name1.column_name=table_name2.column_nameok
-
8/8/2019 SQL Integrity Constraints 1
24/64
SQL LEFT JOIN Keyword The LEFT JOIN keyword returns all rows from the
left table (table_name1), even if there are no matchesin the right table (table_name2).
SQL LEFT JOIN Syntax
SELECT column_name(s)FROM table_name1LEFT JOIN table_name2
ONtable_name1.column_name=table_name2.column_name
-
8/8/2019 SQL Integrity Constraints 1
25/64
SQL RIGHT JOIN Keyword The RIGHT JOIN keyword Return all rows from the
right table (table_name2), even if there are nomatches in the left table (table_name1).
SQL RIGHT JOIN Syntax
SELECT column_name(s)FROM table_name1RIGHT JOIN table_name2
ONtable_name1.column_name=table_name2.column_name
-
8/8/2019 SQL Integrity Constraints 1
26/64
SQL FULL JOIN Keyword The FULL JOIN keyword return rows when
there is a match in one of the tables.
SQL FULL JOIN Syntax SELECT column_name(s)
FROM table_name1FULL JOIN table_name2
ONtable_name1.column_name=table_name2.column_name
-
8/8/2019 SQL Integrity Constraints 1
27/64
SQL UNION Operator The UNION operator is used to combine the result-
set of two or more SELECT statements.
Notice that each SELECT statement within the
UNION must have the same number of columns.The columns must also have similar data types. Also,the columns in each SELECT statement must be inthe same order.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1UNIONSELECT column_name(s) FROM table_name2
-
8/8/2019 SQL Integrity Constraints 1
28/64
SQL Dates Different Functions of SQL dates
NOW() -Returns the current date and time
CURDATE() -Returns the current date
CURTIME() -Returns the current time
DATE() -Extracts the date part of a date or date/time expression EXTRACT() -Returns a single part of a date/time
DATE_ADD() -Adds a specified time interval to a date
DATE_SUB() -Subtracts a specified time interval from a date
DATEDIFF() -Returns the number of days between two dates
DATE_FORMAT() -Displays date/time data in different formats
-
8/8/2019 SQL Integrity Constraints 1
29/64
SQL Server Date Functions Function
GETDATE() -Returns the current date and time
DATEPART() -Returns a single part of a date/time DATEADD() -Adds or subtracts a specified time
interval from a date
DATEDIFF() -Returns the time between two dates
CONVERT() -Displays date/time data in different
formats
-
8/8/2019 SQL Integrity Constraints 1
30/64
SQL Date Data Types MySQL comes with the following data types for storing a date or a
date/time value in the database:
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MM:SS
TIMESTAMP - format: YYYY-MM-DD HH:MM:SS YEAR- format YYYY or YY
SQL Server comes with the following data types for storing a date or adate/time value in the database:
DATE - format YYYY-MM-DD
DATETIME - format: YYYY-MM-DD HH:MM:SS SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS
TIMESTAMP - format: a unique number
-
8/8/2019 SQL Integrity Constraints 1
31/64
SQL Aggregate Functions SQL aggregate functions return a single value,
calculated from values in a column.
Useful aggregate functions:
AVG() - Returns the average value COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value MIN() - Returns the smallest value
SUM() - Returns the sum
-
8/8/2019 SQL Integrity Constraints 1
32/64
SQL Scalar functions SQL scalar functions return a single value, based on the input
value.
Useful scalar functions:
UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LEN() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of decimalsspecified
NOW() - Returns the current system date and time
FORMAT() - Formats how a field is to be displayed
-
8/8/2019 SQL Integrity Constraints 1
33/64
AVG() Function The AVG() function returns the average value
of a numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM
table_name
-
8/8/2019 SQL Integrity Constraints 1
34/64
COUNT() function The COUNT() function returns the number of rows that matches a
specified criteria.
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values
(NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_nameSQL COUNT(*)
Syntax
The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number ofdistinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name
-
8/8/2019 SQL Integrity Constraints 1
35/64
FIRST() Function The FIRST() function returns the first value of
the selected column.
SQL FIRST() Syntax
SELECT FIRST(column_name) FROM
table_name
-
8/8/2019 SQL Integrity Constraints 1
36/64
LAST() Function The LAST() function returns the last value of
the selected column.
SQL LAST() Syntax
SELECT LAST(column_name) FROM
table_name
-
8/8/2019 SQL Integrity Constraints 1
37/64
-
8/8/2019 SQL Integrity Constraints 1
38/64
MIN() Function The MIN() function returns the smallest value
of the selected column.
SQL MIN() Syntax
SELECT MIN(column_name) FROM
table_name
-
8/8/2019 SQL Integrity Constraints 1
39/64
SUM() Function The SUM() function returns the total sum of a
numeric column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM
table_name
-
8/8/2019 SQL Integrity Constraints 1
40/64
GROUP BY Statement The GROUP BY statement is used in
conjunction with the aggregate functions to
group the result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name,aggregate_function(column_name)
FROM table_nameWHERE column_name operator valueGROUP BY column_name
-
8/8/2019 SQL Integrity Constraints 1
41/64
HAVING Clause The HAVING clause was added to SQL because the
WHERE keyword could not be used with aggregatefunctions.
SQL HAVING Syntax SELECT column_name,
aggregate_function(column_name)FROM table_nameWHERE column_name operator value
GROUP BY column_nameHAVING aggregate_function(column_name)operator value
-
8/8/2019 SQL Integrity Constraints 1
42/64
UCASE() Function The UCASE() function converts the value of a
field to uppercase.
SQL UCASE() Syntax
SELECT UCASE(column_name) FROM
table_nameSyntax for SQL Server
SELECT UPPER(column_name) FROMtable_name
-
8/8/2019 SQL Integrity Constraints 1
43/64
LCASE() Function The LCASE() function converts the value of a
field to lowercase.
SQL LCASE() Syntax
SELECT LCASE(column_name) FROM
table_nameSyntax for SQL Server
SELECT LOWER(column_name) FROMtable_name
-
8/8/2019 SQL Integrity Constraints 1
44/64
MID() Function The MID() function is used to extract characters from a text
field.
SQL MID() Syntax
SELECT MID(column_name,start[,length]) FROM table_name column_name -> Required. The field to extract characters from
Start -> Required. Specifies the starting position (starts at 1)
Length -> Optional. The number of characters to return.If
omitted, theMI
D() function returns the rest of the text
-
8/8/2019 SQL Integrity Constraints 1
45/64
LEN() Function The LEN() function returns the length of the
value in a text field.
SQL LEN() Syntax SELECT LEN(column_name) FROM
table_name
-
8/8/2019 SQL Integrity Constraints 1
46/64
ROUND() Function The ROUND() Function
The ROUND() function is used to round a numericfield to the number of decimals specified.
SQL ROUND() Syntax
SELECT ROUND(column_name,decimals) FROMtable_name
column_name -> Required.The field to round
.
Decimals -> Required. Specifies the number ofdecimals to be returned.
-
8/8/2019 SQL Integrity Constraints 1
47/64
NOW() Function The NOW() function returns the current
system date and time.
SQL NOW() Syntax SELECT NOW() FROM table_name
-
8/8/2019 SQL Integrity Constraints 1
48/64
FORMAT() Function The FORMAT() function is used to format how
a field is to be displayed.
SQL FORMAT() Syntax SELECT FORMAT(column_name,format)
FROM table_name
column_name -> Required. The field to beformatted.
Format -> Required. Specifies the format
-
8/8/2019 SQL Integrity Constraints 1
49/64
SQL Integrity ConstraintsIntegrity Constraints are used to apply business rulesfor the database tables.
The constraints available in SQL are Foreign Key,Not Null, Unique, Check.Constraints can be defined in two ways1) The constraints can be specified immediately afterthe column definition. This is called column-leveldefinition.2) The constraints can be specified after all the columnsare defined. This is called table-level definition.
-
8/8/2019 SQL Integrity Constraints 1
50/64
SQL Primary key This constraint defines a column or combination of
columns which uniquely identifies each row in the
table.
Syntax to define a Primary key at column level:
column name datatype [CONSTRAINT
constraint_name] PRIMARY KEY
Syntax to define a Primary key at table level:
[CONSTRAINT constraint_name] PRIMARY KEY
(column_name1,column_name2,..)
-
8/8/2019 SQL Integrity Constraints 1
51/64
SQL Primary key For Example: To create an employee table with Primary Key constraint, the
query would be like.
Primary Key at table level: CREATE TABLE employee
( id number(5) PRIMARY KEY,
name char(20),dept char(10),age number(2),salary number(10),location char(10));
or
CREATE TABLE employee( id number(5) CONSTRAINT emp_id_pkPRIMARY KEY,name char(20),dept char(10),age number(2),salary number(10),location char(10));
-
8/8/2019 SQL Integrity Constraints 1
52/64
SQL Primary key
Primary Key at table level:
CREATE TABLE employee
( id number(5),
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10),
CONSTRAINT emp_id_pkPRIMARY KEY (id));
-
8/8/2019 SQL Integrity Constraints 1
53/64
SQL Foreign key or Referential Integrity This constraint identifies any column referencing the PRIMARY
KEY in another table. It establishes a relationship between twocolumns in the same table or between different tables. For a columnto be defined as a Foreign Key, it should be a defined as a PrimaryKey in the table which it is referring. One or more columns can be
defined as Foreign key.
Syntax to define a Foreign key at column level:
[CONSTRAINT constraint_name] REFERENCESReferenced_Table_name(column_name)
Syntax to define a Foreign key at table level:
[CONSTRAINT constraint_name] FOREIGN KEY(column_name)REFERENCES referenced_table_name(column_name);
-
8/8/2019 SQL Integrity Constraints 1
54/64
SQL Foreign key or Referential Integrity For Example:
1) Lets use the "product" table and "order_items".
Foreign Key at column level:
CREATE TABLE product( product_id number(5) CONSTRAINT pd_id_pkPRIMARY KEY,
product_name char(20),supplier_name char(20),unit_price number(10));
CREATE TABLE order_items( order_id number(5) CONSTRAINT od_id_pkPRIMARY KEY,product_id number(5) CONSTRAINT pd_id_fk REFERENCES, product(product_id),
product_name char(20),supplier_name char(20),unit_price number(10));
-
8/8/2019 SQL Integrity Constraints 1
55/64
SQLF
oreign key or ReferentialIntegrity
Foreign Key at table level:
CREATE TABLE order_items( order_id number(5) ,product_id number(5),product_name char(20),supplier_name char(20),unit_price number(10)CONSTRAINT od_id_pkPRIMARY KEY(order_id),CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCESproduct(product_id));2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key whichreferences primary key 'id' within the same table, the query would be like,
CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),mgr_id number(5) REFERENCES employee(id),salary number(10),location char(10)
);
-
8/8/2019 SQL Integrity Constraints 1
56/64
SQL Not Null Constraint This constraint ensures all rows in the table
contain a definite value for the column which
is specified as not null. Which means a nullvalue is not allowed.
Syntax to define a Not Null constraint:
[CONSTRAINT constraint name] NOTNULL
-
8/8/2019 SQL Integrity Constraints 1
57/64
SQL Not Null Constraint For Example: To create a employee table with Null value,
the query would be like
CREATE TABLE employee( id number(5),name char(20) CONSTRAINT nm_nn NOT NULL,dept char(10),age number(2),
salary number(10),location char(10));
-
8/8/2019 SQL Integrity Constraints 1
58/64
SQL Unique Key This constraint ensures that a column or a group of
columns in each row have a distinct value. A
column(s) can have a null value but the values
cannot be duplicated.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE
Syntax to define a Unique key at table level:
[CONSTRAINT constraint_name]
UNIQUE(column_name)
-
8/8/2019 SQL Integrity Constraints 1
59/64
SQL Unique Key For Example: To create an employee table with Unique key, the query would be
like,
Unique Key at column level:
CREATE TABLE employee( id number(5) PRIMARY KEY,
name char(20),dept char(10),age number(2),salary number(10),location char(10) UNIQUE);
or
CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),salary number(10),location char(10) CONSTRAINT loc_un UNIQUE
);
-
8/8/2019 SQL Integrity Constraints 1
60/64
SQL Unique Key Unique Key at table level:
CREATE TABLE employee( id number(5) PRIMARY KEY,
name char(20),dept char(10),age number(2),salary number(10),location char(10),
CONSTRAINT loc_un UNIQUE(location));
-
8/8/2019 SQL Integrity Constraints 1
61/64
SQL Check Constraint This constraint defines a business rule on a column.
All the rows must satisfy this rule. The constraint
can be applied for a single column or a group of
columns.
Syntax to define a Check constraint:
[CONSTRAINT constraint_name] CHECK
(condition) For Example: In the employee table to select the
gender of a person, the query would be like
-
8/8/2019 SQL Integrity Constraints 1
62/64
SQL Check Constraint Check Constraint at column level:
CREATE TABLE employee( id number(5) PRIMARY KEY,name char(20),dept char(10),age number(2),
gender char(1) CHECK (gender in ('M','F')),salary number(10),location char(10));
Check Constraint at table level:
CREATE TABLE employee( id number(5) PRIMARY KEY,
name char(20),dept char(10),age number(2),gender char(1),salary number(10),location char(10),CONSTRAINT gender_ck CHECK (gender in ('M','F')));
-
8/8/2019 SQL Integrity Constraints 1
63/64
SQL DEF
AULT Constraint The DEFAULT constraint is used to insert a
default value into a column.
The default value will be added to all newrecords, if no other value is specified.
-
8/8/2019 SQL Integrity Constraints 1
64/64