Unit 3
Unit 3
Domain Constraints
These are defined as the definition of valid set of values for an attribute. The
data type of domain include string, char, time, integer, date, currency etc. The
value of the attribute must be available in comparable domains.
There are two types of constraints that come under domain constraint and they
are:
1. Domain Constraints – Not Null: ,CHECK
Not-Null Constraints
NOT NULL: we know that by default all the columns in a table allow null values.
When a NOT NULL constraint is enforced through either on a column or a set of
columns in a table, it will not allow null values. Adding a constraint at the time of
table creation:
sy:CREATE TABLE TableName (ColumnName1 datatype NOT NULL,
ColumnName2 datatype,…., ColumnNameN datatype);
ex: create table stu1(sno number(5) constraint nn1 not null, name char(10) not
null, address varchar2(10) not null);
2.CHECK CONSTRAINT:
The check constraint specifies condition that each row must satisfy. These rules are
formed by logical expressions or Boolean expression.
Sy:CREATE TABLE TableName (ColumnName1 datatype CHECK
(ColumnName1 Condition), ColumnName2 datatype,…., ColumnNameN
datatype);
Ex: create table emp(eno number(5),sal number(8,2) constraint ch1
check(sal>500));
Syntax to apply check constraint on multiple columns:
CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype
CHECK (ColumnName1 Condition AND ColumnName2 Condition),….,
ColumnNameN datatype);
3. DEFAULT CONSTRAINT:
When a row is inserted, it is not necessary that value for every column should not be
inserted. SQL offers the provision to specify default values for columns.
sy:CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value,
ColumnName2 datatype,…., ColumnNameN datatype);
Ex: create table emp(eno number(5), sal number(8,2) default 5000);
Key constraints
There must be at least one minimal subset of attributes in the relation, which can
identify a tuple uniquely. This minimal subset of attributes is called key for that
relation. If there are more than one such minimal subsets, these are called candidate
keys.
1. UNIQUE:
Duplicate values are not allowed in the columns to which the UNIQUE
constraint is applied.
○ The column with the unique constraint will always contain a unique value.
○ This constraint can be applied to one or more than one column of a table, which
means more than one unique constraint can exist on a single table
. ○ Using the UNIQUE constraint, you can also modify the already created tables.
Syntax to apply the UNIQUE constraint on a single column:
sy:CREATE TABLE TableName (ColumnName1 datatype UNIQUE,
ColumnName2 datatype,…., ColumnNameN datatype);
ex: create table stu2(sno number(5) constraint un1 unique, name char(20) not null,
address varchar2(10));
→Syntax to apply the UNIQUE constraint on more than one column:
CREATE TABLE TableName (ColumnName1 datatype, ColumnName2
datatype,…., ColumnNameN datatype, UNIQUE (ColumnName1, ColumnName
2)); →Alter to add unique
2. PRIMARY KEY:
Primary Key is a field which uniquely identifies each row in the table.
The primary key constraint avoids duplication of rows and does not allow null
values. A table can have only one primary key.
If a primary key constraint is assigned to a combination of columns. It is said to be
a composite primary key which contains a maximum of 16 columns.
PRIMARY KEY Constraint is a combination of NOT NULL and Unique
constraints.
sy:CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY,
ColumnName2 datatype,…., ColumnNameN datatype);
ex:create table stu3(sno number(5) constraint pk1 primary key, name char(10)); To
add a constraint:)
Referential Integrity Constraints :
Referential integrity constraints work on the concept of Foreign Keys. .
FOREIGN KEY CONSTRAINT: To establish a parent child relationship between
two tables having a same column.
To implement this we should define the column in the parent table as a primary key
and the same column in the child table as a foreign key referencing to the
corresponding parent entity.
A foreign key is used for referential integrity.
sy:CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY,
ColumnNameN Datatype(SIZE), FOREIGN KEY( ColumnName ) REFERENCES
PARENT_TABLE_NAME(Primary_Key_ColumnName));
ex:1. CREATE TABLE employee (Emp_ID INT PRIMARY KEY, Emp_Name
VARCHAR (40), Emp_Salary VARCHAR (40));
2. CREATE TABLE department(Dept_ID INT PRIMARY KEY, Dept_Name
VARCHAR(40), Emp_ID INT NOT NULL, FOREIGN KEY(Emp_ID)
REFERENCES employee(Emp_ID))
Here,
Inner query or subquery is executed first and returns a set of values that are then
used by the outer query
Independent Nested Queries: In independent nested queries, query execution
starts from innermost query to outermost queries. The execution of inner query is
independent of outer query, but the result of inner query is used in execution of
outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing
independent nested queries.
In correlated nested queries: the inner query uses values from the outer query,
and the execution order is different from that of independent nested queries.
Ex:
1.IN
• This operator checks if a column value in the outer query's result is present
in the inner query's result. The final result will have rows that satisfy the IN
condition.
if we want to fetch the record of all the students whose Teacher name
is ‘Manan’, then:
SELECT id, name FROM Students WHERE class_id IN ( SELECT class_id
FROM Teachers WHERE name = 'Manan);
In the above query,
• The inner SELECT statement fetches the class_id from the Teachers table
where the teacher’s name is ‘Manan’.
• The outer SELECT statement fetches the id and name from
the Students table where the class_id matches any values returned by the
inner SELECT statement.
O/P:
EX: Find the names of all employees who have made a sale
TOPIC: subquery
A subquery is a query nested inside another query, often used to perform more
complex data retrieval operations. Subqueries can be placed in various SQL
clauses such as SELECT, FROM, WHERE, and HAVING. They are also known as
inner queries or inner selects, while the containing query is called the outer query
or outer select
1.IN
• This operator checks if a column value in the outer query's result is present
in the inner query's result. The final result will have rows that satisfy the IN
condition.
if we want to fetch the record of all the students whose Teacher name
is ‘Manan’, then:
SELECT id, name FROM Students WHERE class_id IN ( SELECT class_id
FROM Teachers WHERE name = 'Manan);
Topic: Implementation of different types of joins in sql
SQL Join statement is used to combine data or rows from two or more tables based
on a common field between them.
SQL JOIN clause is used to query and access data from multiple tables by
establishing logical relationships between them
Different types of Joins are as follows:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• NATURAL JOIN
Table 2
CREATE TABLE courses ( course_id INT PRIMARY KEY, course_name
VARCHAR(50), course_description VARCHAR(255), student_id INT,
FOREIGN KEY (student_id) REFERENCES students(student_id));
INSERT INTO students (student_id, student_name, student_age, student_gender)
• VALUES
• (1, 'a', 20, 'Male'),
• (2, 'b', 22, 'Female'),
• (3, 'c', 21, 'Male'),
• (4, 'd', 19, 'Female’);
INSERT INTO courses (course_id, course_name, course_description,student_id)
• VALUES
• (101, 'Mathematics', 'Introduction to Mathematics',1),
• (102, 'Physics', 'Introduction to Physics,1'),
• (103, 'Biology', 'Introduction to Biology',2),
• (104, 'History', 'Introduction to History',3);
Ex:
LEFT JOIN (or LEFT OUTER JOIN):This join returns all the rows of the table
on the left side of the join and matches rows for the table on the right side of the
join. For the rows for which there is no matching row on the right side, the result-
set will contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
Syn:.
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1 LEFT
JOIN table2 ON table1.matching_column =table2.matching_column;
Topic: view
Views in SQL are kind of virtual tables. A view also has rows and columns as
they are in a real table in the database. We can create a view by selecting fields
from one or more tables present in the database. A View can either have all the
rows of a table or specific rows based on certain condition
1.Creating view
• A view can be created using the CREATE VIEW statement.
• We can create a view from a single table or multiple tables.
Syntax:
CREATE VIEW view_name AS SELECT column1, column2..... FROM
table_name WHERE condition;
• Creating View from a single table
In this example,
• CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM
Student_Details WHERE STU_ID < 4;
Just like table query, we can query the view to view the data
. SELECT * FROM DetailsView;
2.Creating View from multiple tables :View from multiple tables can be
created by simply include multiple tables in the SELECT statement.
In the given example, a view is created named MarksView from two tables
Student_Detail and Student_Marks.
• Query: CREATE VIEW MarksView AS SELECT Student_Detail.NAME,
Student_Detail.ADDRESS, Student_Marks.MARKS FROM
Student_Detail, Student_Mark WHERE Student_Detail.NAME =
Student_Marks.NAME;
To display data of View MarksView:
• SELECT * FROM MarksView;
3) Deleting View: A view can be deleted using the Drop View statement.
Syntax DROP VIEW view_name;
Example: If we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
4) Updating a View: A view can be updated under certain conditions: • The
SELECT clause may not contain the keyword DISTINCT.
• • The SELECT clause may not contain summary functions.
• • The SELECT clause may not contain set operators
• The SELECT clause may not contain an ORDER BY clause.
• The FROM clause may not contain multiple tables.
• The WHERE clause may not contain sub queries.
• The query may not contain GROUP BY or HAVING
Topic: Functions in sql
String functions
O/P : RanindraCollege
O/P :
O/P : diet
O/P : DIET
5.Ltrim() : This function is used to remove extra spaces from the beginning of a string.
6.Rtrim() : This function is used to remove extra spaces from the end of a string.
O/P : diet
7.Substring() Returns the part of string . The SUBSTRING function extracts a substring that
starts at a specified position with a given length.
8.lpad() The LPAD() function left-pads a string with another string, to a certain length.
9.Rpad() The RPAD() function right-pads a string with another string, to a certain length
Select Reverse(‘DIET’);
O/P : TEID
11. Instr()The INSTR() function returns the position of the first occurrence of a string in
another string.
12. initcap() It is used to set the first character in each word to UPPERCASE.
The first character in each word is left as UPPERCASE and the rest characters are set to
lowercase.
NUMERIC FUNCTION
Numeric Functions are used to perform operations on numbers and return numbers.
Following are the numeric functions defined in SQL:
1.GREATEST(): It returns the greatest v
Output: 243.5
7.MOD(n, m)
8.Truncate()
o/p 357.4
9.CEIL(): It returns the smallest integer value that is greater than or equal to a number.
11.FLOOR(): It returns the largest integer value that is less than or equal to a number.
Output: 6
3.SIGN(): It returns a value indicating the sign of a number. A return value of 1 means
positive; 0 means negative.
1.ADD_MONTHS :
It will add the total number of months specified in n to the date parameter and Returns
date.
Syn:ADD_MONTHS(d, n)
Example –
2.LAST_DAY :
In the LAST_DAY function, It will return the last date of the month, and for the specified
month like if the system date is 1 Nov then it will return 30 Nov.
Syntax : LAST_DAY(date)
3.MONTHS_BETWEEN :
Returns number of months between date1 and date2.
4.NEXT_DAY :
It will return the date of the first weekday that comes after the date specified in date
parameter. char specified should be someday of the week
7. current time()
01-FEB-2017
2.select to_char(sysdate,'DD Month') from dual;
-- Output--
01 February
3.select to_char(sysdate,'DD Month, Year') from dual;
-- Output--
01 February , Twenty Seventeen;
4.select to_char( ‘25 january 2024’,‘dd month yyyy’)from dual;
5.SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS FROM
DUAL;
6. select TO_CHAR(SYSDATE, 'DAY, DD MON YYYY') from dual;
o/p
-------------------- ---------------------- --------------------------------
5.2023-06-15 14:30:00
6. THURSDAY, 15 JUN 202
7.SELECT TO_CHAR(1234567.89, '999,999,999.99') from dual
8. select TO_CHAR(1234567.89, '$999,999,999.99') from dual;
formatted_number with_dollar
----------------- ------------------ --------------------
1,234,567.89 $1,234,567.89
2.To_number()
1.Select 5+5 from dual;
o/p10
2.select 5+$50.99 from dual;
Error so
3. select 5+to_number(‘$50.99’,’$99.99’)from dual;
Or
Select 5+to_number(‘$50.99’,’$99d99’)from dual;
4. select TO_NUMBER('1210.73', '9999.99') from dual;
Result: 1210.73
5.select TO_NUMBER('23', '99') from dual;
Result: 23
3.to_date()
2) TO_DATE -- can take either a string/date value are argument1 and converts it to
a date , 2nd argument specifies the format the date appears in first argument.
1.select to_date('01-FEB-2017','DD-MON-YYYY') from dual;
-- OUTPUT --
2017-02-01
2.select to_DATE(sysdate,'DD-MON-YYYY') from dual;
REQ_DATE
-----------
01-FEB-2017.
3.select to_date('01-01-2017','DD-MM-YYYY') from dual;
--Output--
2017-01-01
4. select to_date(’01-jan-05’,’dd-mm-yy’)from dual;
5.select to_date('070903', 'MMDDYY') from dual;
Now if we need to display the departments where the sum of salaries is 50,000 or
more. In this condition, we will use the HAVING Clause.
EX:SELECT Department, sum(Salary) as Salary FROM employee GROUP BY
department HAVING SUM(Salary) >= 50000;
TOPIC:ORDERING
ORDER BY Clause
The ORDER BY clause is used in SQL queries to sort the data returned by a query
in ascending or descending order. If we omit the sorting order, it sorts the
summarized result in the ascending order by default. The ORDER BY clause, like
the GROUP BY clause, could be used in conjunction with the SELECT
statement. ASC denotes ascending order, while DESC denotes descending order.
The following is the syntax to use the ORDER BY clause in a SQL statement:
SELECT expressions FROM tables [WHERE conditions] ORDER BY
expression [ ASC | DESC ];
EX:SELECT D_name, D_state, D_salary FROM developers ORDER BY
D_state ASC;
TOPIC: Aggregate Functions(OR)Aggregation
• SQL aggregation function is used to perform the calculations on multiple
rows of a single column of a table.
• It returns a single value.
• It is also used to summarize the data.
Types:
1.SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
SUM() or SUM( [ALL|DISTINCT] expression )
Example:
SELECT SUM(salary) FROM emp;
Select sum(salary) from emp where salary>60;
Select sum( distinct salary) from emp;
SELECT Department, sum(Salary) as Salary FROM employee GROUP BY
department
COUNT FUNCTION
• COUNT function is used to Count the number of rows in a database table.
• It can work on both numeric and non-numeric data types.
• COUNT function uses the COUNT(*) that returns the count of all the rows
in a specified table.
• COUNT(*) considers duplicate and Null.
Syn:COUNT(*)
or COUNT( [ALL|DISTINCT] expression )
examples:
SELECT COUNT(*) FROM emp
SELECT COUNT(*) FROM emp WHERE salary>80;
SELECT COUNT(DISTINCT salary) FROM emp;
COUNT() with GROUP BY
SELECT company, COUNT(*) FROM emp GROUP BY COMPANY;
COUNT() with HAVING
SELECT COMPANY, COUNT(*) FROM emp GROUP BY COMPANY
HAVING COUNT(*)>2;
SELECT working_area, COUNT(*) From agents GROUP BY working_area;
o/p
Agents table
AVG function
• The AVG function is used to calculate the average value of the numeric type.
AVG function returns the average of all non-Null values.
• Syntax
• AVG() or AVG( [ALL|DISTINCT] expression )
• Example:
SELECT AVG(salary) FROM emp;
4.MAX Function
• MAX function is used to find the maximum value of a certain column. This
function determines the largest value of all selected values of a column.
Syntax: MAX()
or MAX( [ALL|DISTINCT] expression )
• Example:
• SELECT MAX(salary) FROM emp
5. MIN Function
• MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.
• Syntax MIN()
• or MIN( [ALL|DISTINCT] expression )
• SELECT MIN(salary) FROM emp
2.SELECT dept_id FROM employee UNION ALL SELECT dept_id FROM dept;
3.SELECT dept_id FROM employee intersect SELECT dept_id FROM dept;
4.SELECT dept_id FROM employee minus SELECT dept_id FROM dept;
Practice Questions
Q1)
Write a query to return all customers whose
names end with "n".
Answer
SELECT *
FROM Customers
WHERE CustomerName LIKE '%n';
Q2)
Find all customers whose city names start with
"S" and have at least 3 letters.
Answer
SELECT *
FROM Customers
WHERE City LIKE 'S__%';
• S → must start with S
• __ → at least 2 more letters
• % → anything after
Q3)
Get all customers whose second letter in their
name is "a".
Answer
SELECT *
FROM Customers
WHERE CustomerName LIKE '_a%';
• _ → any first letter
• a → second letter must be "a"
• % → rest can be anything
Q4)
Find all customers whose city name contains
"or" anywhere.
Answer
SELECT *
FROM Customers
WHERE City LIKE '%or%';
(Ex: London, Toronto, Córdoba).
Q5)
Display all customers whose names have
exactly 5 letters.
Answer
SELECT *
FROM Customers
WHERE CustomerName LIKE '_____';
• Five underscores (_ _ _ _ _) = exactly 5
characters.