SQL Constraints
Constraints meaning restriction or limitation
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply
to a column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
NOT NULL - Ensures that a column cannot have a NULL value
create table empl( id int not null,
name varchar(10) not null);
UNIQUE - Ensures that all values in a column are different
any number of columns appplied unique key. Unique means no duplicate data.
create table empl( id int unique,
name varchar(10) unique);
id name
1 ram
2 ravan
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table.only one column has applied primary key,
no duplicate data.
FOREIGN KEY - Uniquely identifies a row/record in another table.
Foreign key references primary key data
CHECK - Ensures that all values in a column satisfies a specific
condition
Example:
Create table tblstudent (
roll int ,
name varchar(20),
CONSTRAINT tstud CHECK (roll > 0)
);
“tstud” is name of constraint, you can give any name
DEFAULT - Sets a default value for a column when no value is specified
Example:
Create table tblstudent (
roll int
fees int default “10000” );
Relational Algebra
Relational algebra is a procedural query language, which takes instances of relations
as input and yields instances of relations as output. It uses operators to perform
queries. An operator can be either unary or binary. They accept relations as their
input and yield relations as their output. Relational algebra is performed recursively
on a relation and intermediate results are also considered relations.
The fundamental operations of relational algebra are as follows −
• Select
• Project
• Union
• Set different
• Cartesian product
• Rename
We will discuss all these operations in the following sections.
Select Operation (σ)
It selects tuples that satisfy the given predicate from a relation.
Notation− σp(r)
Where σ stands for selection predicate and r stands for relation. P is prepositional
logic formula which may use connectors like and, or, and not. These terms may use
relational operators like − =,≠,≥,< , >, ≤.
For example−
σsubject = "database"(Books)
Output− Selects tuples from books where subject is 'database'.
σsubject = "database" and price = "450"(Books)
Output− Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450" or year > "2010"(Books)
Output− Selects tuples from books where subject is 'database' and 'price' is 450 or
those books published after 2010.
Project Operation (∏)
It projects columns that satisfy a given predicate.
Notation − ∏A1, A2, An(r)
Where A1, A2, An are attribute names of relationr.
Duplicate rows are automatically eliminated, as relation is a set.
For example−
∏subject, author (Books)
Selects and projects columns named as subject and author from the relation Books.
Union Operation (∪)
It performs binary union between two given relations and is defined as −
r ∪ s = { t | t ∈ r or t ∈ s}
Notation− r U s
Where r and s are either database relations or relation result set (temporary
relation).
For a union operation to be valid, the following conditions must hold −
r, and s must have the same number of attributes.
Attribute domains must be compatible.
Duplicate tuples are automatically eliminated.
∏ author (Books) ∪ ∏ author (Articles)
Output − Projects the names of the authors who have either written a book or an
article or both.
Set Difference (−)
The result of set difference operation is tuples, which are present in one relation but
are not in the second relation.
Notation− r −s
Finds all the tuples that are present in r but not in s.
∏ author (Books) − ∏ author (Articles)
Output− Provides the name of authors who have written books but not articles.
Cartesian Product (Χ)
Combines information of two different relations into one.
Notation − r Χ s
Where r and s are relations and their output will be defined as −
r Χ s = { q t | q ∈ r and t ∈ s}
σauthor = 'tutorialspoint'(Books Χ Articles)
Output − Yields a relation, which shows all the books and articles written by
tutorialspoint.
Rename Operation (ρ)
The results of relational algebra are also relations but without any name. The
rename operation allows us to rename the output relation. 'rename' operation is
denoted with small Greek letter rho ρ.
Notation −ρ x(E)
Where the result of expression E is saved with name of x.
DDL : create,alter, drop,
DML : insert, update, delete,
DQL : select.
SQL operator: Logical - and ,or,not,
relational -<,>,<=,>=,<>,in, between, like, not, is null.
SQL Clauses: Where, Order by, Group by , Having,
Aggregate Functions :SUM(), MAX(), MIN(), COUNT(), AVG()
Aggregate Functions
table- emp
Name Salary
A 5000
B 3000
C 1000
1)MIN( )
returns the smallest value in a given column
Select min(salary) from emp;
O/p
min(salary)
1000
2)MAX( )
returns the largest value in a given column
Select max(salary) from emp;
O/p
max(salary)
5000
3) SUM( )
returns the sum of the numeric values in a given column
Select sum(salary) from emp;
O/p
Sum(salary)
9000
4) AVG( )
returns the average value of a given column
Select avg(salary) from emp;
O/p
Avg(salary)
3000
5) COUNT( )
returns the total number of values in a given column
Select count(salary) from emp;
O/p
Count(salary)
6) COUNT(*)
returns the number of rows in a table
Select count(*) from emp;
O/p
Count(*)
...............................
Extra info......
Aggregate functions by subquery
Select name,salary from emp where salary=(select min(salary) from emp);
O/p
Name Salary
C 1000
....................................
DDL(Data Definition Language) :DDL or Data Definition Language actually
consists of the SQL commands that can be used to define the database
schema. It simply deals with descriptions of the database schema and is used
to create and modify the structure of database objects in database.
DDL is set of commands used to create ,modify and delete database structure but not data,This are
used by DBA’s(Database Administrators) ,DDL command would commit all updates ,hence they
can not rollback (not reversed).
• Create
• Alter -add,modify, drop
• drop
create: To create tables ,views,synonyms,sequences,functions,procedures,etc
create -create statement used for creating tables ,creating structure of table specyfying column
name,datatype and size .integrity constraints also applied like check,default,primary key ,foreign
key,
syntax
create table tablename ( columnname datatype(size),
columnname datatype(size)
..........
);
example
create table student (roll int,
name varchar(20)
);
Alter: To change structure of table.
You can add column,modify its datatype,drop column.or remove column
1)add column
syntax alter table tablename add( col datatype(size));
eg: alter table student add (class varchar(10));
here class column added
roll name class
2)modify column
syntax alter table tablename modify( col datatype(size));
eg: alter table student modify (class varchar(5));
here class column datatype changed
roll name class
1)drop column
syntax alter table tablename drop col ;
eg: alter table student drop name
here class column added
roll class
Here name column is removed.
Drop table:
here complete structure of table is removed.
Syntax: drop table tablename;
drop table student;
here table dropped student
DML: data manipulation language
it is the area of sql that allows changing data within the database.
3 major DML statements:
-insert
-update
-delete
insert:insert statement is used to add data in the table.
Syntax-
insert into tablename (colname 1,colname 2,....) values( ‘value1’,’value2’........);
suppose we want to add employee information like empno and ename then insert into statement will
be-
insert into empl( empno,empname) VALUES (‘100’,’Ajay patil’);
empno empname
100 Ajay patil
Update :updates existing data within table
synatx-
update tablename
set col=value
where col=value;
suppose we want to update empname ajay patil to abheejeet patil whose empno is 100
then query will be-
update empl
set empname=’Abheejeet patil’
where empno=’100’;
empno empname
100 Abheejeet patil
Here old value ajay patil is changed to Abheejeet patil
Delete: Delete row specified in where condition.
If where condition is not specified then all rows will be deleted.
Synatax : delete from tablename where col=value;
delete from empl where empno=’100’;
here row will be deleted from empl table whose empno was 100
delete from empl;
all data will be deleted from table empl
you can rollback data if you used savepoint for delete statement.
You can not rollback data if you truncate statement used.
...............................................................................................................................................
SQL Clauses: Where, Order by, Group by , Having,
WHERE Clause
Description
The SQL WHERE clause is used to filter the results and apply conditions in a
SELECT, INSERT, UPDATE, or DELETE statement.
Example - One Condition in the WHERE Clause
roll name
1 Ajay mane
2 manoj
3 rahul
4 Ajay sane
Enter the following SQL statement:
SELECT * FROM student
WHERE name = 'manoj';
. These are the results that you should see:
roll name
2 manoj
AND Condition
SELECT * FROM student
WHERE roll >2 AND roll < 5;
roll name
3 rahul
4 Ajay sane
.
OR Condition
SELECT *
FROM student
WHERE roll = '6' OR name = 'rahul';
roll name
3 rahul
ORDER BY Clause
Description
The SQL ORDER BY clause is used to sort the records in the result set for a
SELECT statement.
The syntax for the ORDER BY clause in SQL is:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
example
Ascending order by name
abc................z
SELECT * FROM student
ORDER BY name ASC;
roll name
1 Ajay mane
4 Ajay sane
2 manoj
3 rahul
DESCENDING order by name zyx...........a
SELECT * FROM student
ORDER BY name DESC;
roll name
3 rahul
2 manoj
4 Ajay sane
roll name
1 Ajay mane
Group by clause:
The SQL GROUP BY clause can be used in a SELECT statement to collect data
across multiple records and group the results by one or more columns.
Syntax
The syntax for the GROUP BY clause in SQL is:
SELECT ....
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ...
carname presentcars
tata 4
maruti 5
tata 4
maruti 10
SELECT carname,presentcars
FROM parking
GROUP BY carname;
carname presentcars
tata 4
tata 4
maruti 5
maruti 10
Using aggregate function in group by
SELECT carname,sum(presentcars)
FROM parking
GROUP BY carname;
carname presentcars
tata 4+4=8
maruti 5+10=15
HAVING clause
group by----having
The SQL HAVING clause is used in combination with the GROUP BY clause to
restrict the groups of returned rows to only those whose the condition is TRUE.
SELECT carname,sum(presentcars)
FROM parking
GROUP BY carname
having carname=’tata’;
carname presentcars
tata 4+4=8
DQL : select
Description
The SQL SELECT statement is used to retrieve records from one or more tables
in your SQL database. The records retrieved are known as a result set.
Syntax
The syntax for the SELECT statement in SQL is:
SELECT expressions
FROM tables
[WHERE conditions]
[ORDER BY expression [ ASC | DESC ]];
roll name
1 ram
3 raj
2 sam
Example
SELECT roll,name
FROM student
WHERE roll=’3’;
roll name
3 raj
SQL operator: Logical, relational,in, between, like, not, is null.
SQL logical operators:
logical operator -and ,or,
The SQL AND conditionandOR condition can be combined to test for multiple
conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
When combining these conditions, it is important to use parentheses so that
the database knows what order to evaluate each condition.
roll name
1 ram
3 raj
2 sam
AND-logic
if two conditions satisfies both true then result is true
t + t=t
Example
SELECT roll,name
FROM student
WHERE roll=’3’ and name=’raj’;
roll name
3 raj
OR -logic
if any one condition is true then result is true
t or t =t
SELECT roll,name
FROM student
WHERE roll=’3’ or name=’pankaj’;
roll name
3 raj
Relational operators:
<, >, <=,>=, <> not equal,
SELECT roll,name
FROM student
WHERE roll >2;
roll name
3 raj
SELECT roll,name FROM student
WHERE roll <2;
roll name
1 ram
SELECT roll,name FROM student
WHERE roll <>2;
roll name
1 ram
3 raj
SELECT roll,name FROM student
WHERE roll <=2;
roll name
1 ram
2 sam
The SQL IN condition (sometimes called the IN operator) allows you to easily
test if an expression matches any value in a list of values
IN (value1, value2, .... value_n);
NOT IN (value1, value2, .... value_n);
id carname
100 maruti
101 tata
102 swift
SELECT * FROM suppliers
WHERE carname IN ('maruti', 'tata', 'omni’);
id carname
100 maruti
101 tata
Between : between ---and---
The SQL BETWEEN condition allows you to easily test if an expression is within
a range of values .
roll name
1 ram
2 raj
3 sam
4 popat
5 nilesh
SELECT * FROM suppliers
WHERE roll between 1 and 3;
roll name
1 ram
2 raj
3 sam
Like operator:
The SQL LIKE condition allows you to use wildcards to perform pattern
matching in a query.
_ means after any 1 character
_ _ means after any 2 character
% any number of characters
show name after 1 character am
SELECT * FROM student
WHERE name like ‘_am’;
roll name
1 ram
3 sam
Show name whose name contains j character anywhere
SELECT * FROM student
WHERE name like ‘ % ji%’;
roll name
1 rajiv
2 jitendra
IS NULL:
The IS NULL condition is used in SQL to test for a NULL value. It returns
TRUE if a NULL value is found, otherwise it returns FALSE
roll name
1 ram
2
SELECT * FROM customers
WHERE name IS NULL;
output:
roll name
2 NULL
NOT:
The SQL NOT condition (sometimes called the NOT Operator) is used to negate
a condition in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE
statement.
SELECT * FROM students
WHERE name NOT IN ('ram', 'raj');
roll name
3 sam