0% found this document useful (0 votes)
122 views64 pages

SQL Integrity Constraints 1

This document provides an overview of Structured Query Language (SQL). It defines SQL as a query language used to access and modify information in relational databases. Key points covered include: - SQL commands like SELECT, INSERT, UPDATE, DELETE for manipulating data - Data Definition Language (DDL) commands like CREATE TABLE for defining database structure - Operators like WHERE, ORDER BY, JOIN for filtering and combining data - SQL can be used to store, modify, retrieve, and delete data from databases - Examples of SQL statements and syntax are provided for common operations like selecting, inserting, updating, and joining data.

Uploaded by

Nilay Ghosh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
122 views64 pages

SQL Integrity Constraints 1

This document provides an overview of Structured Query Language (SQL). It defines SQL as a query language used to access and modify information in relational databases. Key points covered include: - SQL commands like SELECT, INSERT, UPDATE, DELETE for manipulating data - Data Definition Language (DDL) commands like CREATE TABLE for defining database structure - Operators like WHERE, ORDER BY, JOIN for filtering and combining data - SQL can be used to store, modify, retrieve, and delete data from databases - Examples of SQL statements and syntax are provided for common operations like selecting, inserting, updating, and joining data.

Uploaded by

Nilay Ghosh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 64

STRUCTURED QUERY

LANGUAGE (SQL)
STRUCTURED QUERY LANGUAGE
 SQL stands for “Structured Query Language” and can be
pronounced as “SQL” or “sequel – (Structured English Query
Language)”.
 It is a query language used for accessing and modifying
information in the database.
 IBM first developed SQL in 1970s. Also it is an ANSI/ISO
standard. It has become a Standard Universal Language used by
most of the relational database management systems (RDBMS).
 Some of the RDBMS systems are: Oracle, Microsoft SQL server,
Sybase etc. Most of these have provided their own implementation
thus enhancing it's feature and making it a powerful tool.
 Few of the sql commands used in sql programming are SELECT
Statement, UPDATE Statement, INSERT INTO Statement,
DELETE Statement, WHERE Clause, ORDER BY Clause,
GROUP BY Clause, ORDER Clause, Joins, Views, GROUP
Functions, Indexes etc.
CREATE DATABASE Statement
 The CREATE DATABASE statement is used
to create a database.
 SQL CREATE DATABASE Syntax
 CREATE DATABASE database_name
The CREATE TABLE Statement
 The CREATE TABLE statement is used to create a
table in a database.
 SQL CREATE TABLE Syntax
 CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
STRUCTURED QUERY LANGUAGE
 In a simple manner, SQL is a non-procedural, English-
like language that processes data in groups of records
rather than one record at a time. Few functions of SQL
are:
 store data
 modify data
 retrieve data
 modify data
 delete data
 create tables and other database objects
STRUCTURED QUERY LANGUAGE
 Database Tables
 A database most often contains one or more tables. Each table is
identified by a name (e.g. "Customers" or "Orders"). Tables contain
records (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 RICKY N.Y N.Y

3 SLEDON JONES GER CHI


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
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 also define
indexes (keys), specify links between tables, and impose constraints between 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)
 DROP INDEX - deletes an index
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)
FROM table_name
 and
 SELECT * FROM table_name
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
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
ORDER BY Keyword
 The ORDER BY keyword is used to sort the result-
set by a specified column.
 The ORDER BY keyword sort the records in
ascending order by default.
 If you want to sort the records in a descending order,
you can use the DESC keyword.
 SQL ORDER BY Syntax
 SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
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 two forms.
 The first form doesn't specify the column names where the data
will be inserted, only their values:
 INSERT INTO table_name
VALUES (value1, value2, value3,...)
 The second form specifies both the column names and the
values to be inserted:
 INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
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
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
LIKE Operator
 The LIKE operator is used to search for a
specified pattern in a column.
 SQL LIKE Syntax
 SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
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
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,...)
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_name
WHERE column_name BETWEEN value1
AND value2
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 or
complex 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_name
AS alias_nameSQL Alias Syntax for Columns
 SELECT column_name AS alias_name
FROM table_name
SQL JOIN
 The JOIN keyword is used in an SQL statement to
query data from two or more tables, based on a
relationship between certain columns in these tables.
 Tables in a database are often related to each other
with keys.
 A primary key is a column (or a combination of
columns) 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.
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 in
one of the tables
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_name1
INNER JOIN table_name2
ON
table_name1.column_name=table_name2.colum
n_nameok
SQL LEFT JOIN Keyword
 The LEFT JOIN keyword returns all rows from the
left table (table_name1), even if there are no matches
in the right table (table_name2).
 SQL LEFT JOIN Syntax
 SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON
table_name1.column_name=table_name2.column_n
ame
SQL RIGHT JOIN Keyword
 The RIGHT JOIN keyword Return all rows from the
right table (table_name2), even if there are no
matches in the left table (table_name1).
 SQL RIGHT JOIN Syntax
 SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON
table_name1.column_name=table_name2.column_n
ame
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_name1
FULL JOIN table_name2
ON
table_name1.column_name=table_name2.col
umn_name
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 in the same order.
 SQL UNION Syntax
 SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
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
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
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 a
date/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
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
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 decimals
specified
 NOW() - Returns the current system date and time
 FORMAT() - Formats how a field is to be displayed
AVG() Function
 The AVG() function returns the average value
of a numeric column.
 SQL AVG() Syntax
 SELECT AVG(column_name) FROM
table_name
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 of
distinct values of the specified column:
 SELECT COUNT(DISTINCT column_name) FROM table_name
FIRST() Function
 The FIRST() function returns the first value
of the selected column.
 SQL FIRST() Syntax
 SELECT FIRST(column_name) FROM
table_name
LAST() Function
 The LAST() function returns the last value of
the selected column.
 SQL LAST() Syntax
 SELECT LAST(column_name) FROM
table_name
MAX() Function
 The MAX() function returns the largest value
of the selected column.
 SQL MAX() Syntax
 SELECT MAX(column_name) FROM
table_name
MIN() Function
 The MIN() function returns the smallest value
of the selected column.
 SQL MIN() Syntax
 SELECT MIN(column_name) FROM
table_name
SUM() Function
 The SUM() function returns the total sum of a
numeric column.
 SQL SUM() Syntax
 SELECT SUM(column_name) FROM
table_name
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_name
WHERE column_name operator value
GROUP BY column_name
HAVING Clause
 The HAVING clause was added to SQL because the
WHERE keyword could not be used with aggregate
functions.
 SQL HAVING Syntax
 SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name)
operator value
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) FROM
table_name
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) FROM
table_name
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, the MID() function returns the rest of the text
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
ROUND() Function
 The ROUND() Function
 The ROUND() function is used to round a numeric
field to the number of decimals specified.
 SQL ROUND() Syntax
 SELECT ROUND(column_name,decimals) FROM
table_name
 column_name -> Required. The field to round.
 Decimals -> Required. Specifies the number of
decimals to be returned.
NOW() Function
 The NOW() function returns the current
system date and time.
 SQL NOW() Syntax
 SELECT NOW() FROM table_name
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 be
formatted.
 Format -> Required. Specifies the format
SQL Integrity Constraints
Integrity Constraints are used to apply business rules
for the database tables.
The constraints available in SQL are Foreign Key,
Not Null, Unique, Check.
Constraints can be defined in two ways
1) The constraints can be specified immediately after
the column definition. This is called column-level
definition.
2) The constraints can be specified after all the columns
are defined. This is called table-level definition.
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,..)
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_pk PRIMARY KEY,
name char(20),
dept char(10),
age number(2),
salary number(10),
location char(10)
);
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_pk PRIMARY KEY (id));
SQL Foreign key or Referential Integrity
 This constraint identifies any column referencing the PRIMARY
KEY in another table. It establishes a relationship between two
columns in the same table or between different tables. For a column
to be defined as a Foreign Key, it should be a defined as a Primary
Key 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] REFERENCES
Referenced_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);
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_pk PRIMARY KEY,
product_name char(20),
supplier_name char(20),
unit_price number(10)
);
 CREATE TABLE order_items
( order_id number(5) CONSTRAINT od_id_pk PRIMARY 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)
);
SQL Foreign key or Referential Integrity
 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_pk PRIMARY KEY(order_id),
CONSTRAINT pd_id_fk FOREIGN KEY(product_id) REFERENCES product(product_id)
);
2) If the employee table has a 'mgr_id' i.e, manager id as a foreign key which references 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)
);
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 null
value is not allowed.
 Syntax to define a Not Null constraint:
 [CONSTRAINT constraint name] NOT
NULL
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)
);
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)
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
);
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)
);
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
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'))
);
SQL DEFAULT Constraint
 The DEFAULT constraint is used to insert a
default value into a column.
 The default value will be added to all new
records, if no other value is specified.

You might also like