Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views40 pages

Unit 3

The document discusses various SQL concepts, including operators, integrity constraints, keys, nested queries, and joins. It explains the use of operators like LIKE, BETWEEN, and NOT, as well as the creation of tables with foreign key relationships. Additionally, it covers integrity constraints such as NOT NULL, CHECK, DEFAULT, UNIQUE, and PRIMARY KEY, and details the implementation of different types of joins in SQL.

Uploaded by

Mahaboob Saniya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views40 pages

Unit 3

The document discusses various SQL concepts, including operators, integrity constraints, keys, nested queries, and joins. It explains the use of operators like LIKE, BETWEEN, and NOT, as well as the creation of tables with foreign key relationships. Additionally, it covers integrity constraints such as NOT NULL, CHECK, DEFAULT, UNIQUE, and PRIMARY KEY, and details the implementation of different types of joins in SQL.

Uploaded by

Mahaboob Saniya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

TOPIC:OPERATORS

• An operator is a reserved word or a character used primarily in an SQL


statement's WHERE clause to perform operation(s), such as comparisons
and arithmetic operations. These Operators are used to specify conditions in
an SQL statement and to serve as conjunctions for multiple conditions in a
statement.
• • Arithmetic operators
• • Comparison operators
• • Logical operators
COMPARISION OPERATORS
LOGICAL OPERATORS
SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in
a column.
There are two wildcards often used in conjunction with the LIKE operator:
• The percent sign % represents zero, one, or multiple characters
• The underscore sign _ represents one, single character
Syntax:
SELECT column1,column2,...FROM table_name WHERE columnN LIKE pattern;
EX:SELECT * FROM Customers WHERE CustomerName LIKE 'a%';
EX:SELECT * FROM Customers WHERE City LIKE 'L_nd__';
Return all customers from a city that contains the letter 'L':
EX:SELECT * FROM Customers WHERE city LIKE '%L%';
2.BETWEEN
SELECT * FROM Products WHERE Price BETWEEN 50 AND 60;
3. NOT
SELECT * FROM Customers WHERE City NOT LIKE 's%';

NOTE :REMAINING OPERATORS refer IN NESTED QUERIES


Topic: Creating tables with relationship,
Creating tables with relationships in SQL involves defining foreign key constraints
to establish connections between tables.
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.
Here’s a step-by-step guide to help you get started:
1. Creating Tables with Relationships
Example: Parent and Child Tables
Let’s create two tables: Parent and Child, where the Child table references
the Parent table.
SQL
CREATE TABLE Parent ( ParentId INT NOT NULL PRIMARY KEY, ParentName
VARCHAR(255) NOT NULL);
CREATE TABLE Child ( ChildId INT NOT NULL PRIMARY KEY, ChildName
VARCHAR(255) NOT NULL, ParentId INT NOT NULL, FOREIGN KEY
(ParentId) REFERENCES Parent (ParentId));
Topic:Implementation of integrity constraints
Integrity constraints are the set of predefined rules that are used to maintain the
quality of information. Integrity constraints ensure that the data insertion, data
updating, data deleting and other processes have to be performed in such a way that
the data integrity is not affected
Types of Integrity Constraints:

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))

TOPIC: Implementation of keys


In SQL, keys are attributes or combinations of attributes that uniquely identify a row
in a table. They enforce entity integrity and establish relationships between tables in
a relational database. There are several types of keys in SQL, each serving a specific
purpose.
Types of SQL Keys:
1. Primary Key (PK):
• Function: A primary key uniquely identifies each record in a table and
ensures that there are no duplicate values.
• Properties: Cannot contain NULL values and must be unique for each record.
• Example: Consider a Students table:
Ex:CREATE TABLE Students (StudentID INT PRIMARY KEY, Name
VARCHAR(50) );
2)Foreign Key (FK):
Function: A foreign key establishes a relationship between two tables by
referencing the primary key of another table.
Properties: Ensures referential integrity by enforcing that values in the foreign key
column must exist in the referenced table's primary key column
CREATE TABLE Orders ( OrderID INT PRIMARY KEY, CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
3)Unique Key:
Function: A unique key ensures that values in a column or a combination of
columns are unique, similar to a primary key.
Properties: Allows NULL values, but does not allow duplicate values.
CREATE TABLE Employees (EmployeeID INT UNIQUE,NameVARCHAR(50));
4) Candidate Key:
Function: A candidate key is a set of attributes that can uniquely identify a record
in a table.
Example: Consider a Students table with both StudentID and Email columns as
candidate keys:
CREATE TABLE Students ( StudentID INT, Email VARCHAR(50), PRIMARY
KEY (StudentID), UNIQUE (Email));
5)Composite Key:
Function: A composite key is a combination of two or more columns that together
uniquely identify a record.
Ex:Consider an Orders table with a composite key on OrderID and ProductID
CREATE TABLE Orders ( OrderID INT,ProductID INT, PRIMARY KEY
(OrderID, ProductID));

TOPIC: NESTED QUERIES, SUB QUERIES


In SQL, a nested query involves a query that is placed within another query. Output
of the inner query is used by the outer query. A nested query has two SELECT
statements: one for the inner query and another for the outer query.
Sy:
• SELECT column1, column2, ... FROM table1 WHERE column1 operator
(SELECT column1 FROM table2 WHERE condition );

Here,

• column is the name of the column(s) to filter


• OPERATOR is any SQL operator to connect the two queries
• table is the name of the table to fetch the column from

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:SELECT emp_name FROM employees WHERE dept_id IN (SELECT


dept_id FROM departments WHERE dept_name = 'Sales’);
2.NOT IN Operator
• This operator checks if a column value in the outer query's result is not
present in the inner query's result. The final result will have rows that satisfy
the NOT IN condition.
EX: SELECT id, name FROM Students WHERE class_id NOT IN ( SELECT
class_id FROM Teachers WHERE name = 'Manan);
.ALL Operator
• This operator compares a value of the outer query's result with all the values
of the inner query's result and returns the row if it matches all the values.
Find the names of all employees who have made sales greater than $1000.
Ex: SELECT emp_name FROM employees WHERE emp_id = ALL (SELECT
emp_id FROM sales WHERE sale_amt > 1000);
ANY Operator
• This operator compares a value of the outer query's result with all the inner
query's result values and returns the row if there is a match with any value.
Ex: we want to find teachers whose age is similar to any of the student's
age. Then, we can use the following query:
SELECT *FROM Teachers WHERE age = ANY ( SELECT age FROM
Students);
EXISTS Operator:
• This operator checks whether a subquery returns any row. If it returns at
least one row. EXISTS operator returns true, and the outer query continues
to execute. If the subquery returns no row, the EXISTS operator returns
false, and the outer query stops execution.

EX: Find the names of all employees who have made a sale

SELECT emp_name FROM employee WHERE EXISTS (SELECT emp_id

FROM sales WHERE employee.emp_id = sales.emp_id);

NOT EXISTS Operator


• This operator checks whether a subquery returns no rows. If the subquery
returns no row, the NOT EXISTS operator returns true, and the outer query
continues to execute. If the subquery returns at least one row, the NOT
EXISTS operator returns false, and the outer query stops execution.
Find the names of all employees who have NOT made a sale

SELECT emp_name FROM employee WHERE NOT EXISTS (SELECT


emp_id FROM sales WHERE employee.emp_id = sales.emp_id);

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

SQL INNER JOIN


The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. This keyword will create the result-set by combining all rows
from both the tables where the condition satisfies i.e value of the common field
will be the same.
The syntax for SQL INNER JOIN is:
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;
Ex:
CREATE TABLE students ( student_id INT PRIMARY KEY, student_name
VARCHAR(50), student_age INT, student_gender VARCHAR(10));

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:

SELECT students.student_name, courses.course_name FROM students


INNER JOIN courses ON students.student_id = courses.student_id

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;

Ex: SELECT Students.NAME,Courses.COURSE_ID FROM Student


LEFT JOIN Courses ON students.student_id = courses.student_id
RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right
table and the matched rows from the left table. If there is no match, NULL values
are returned for the columns from the left table.
Syn:
SELECT table1.column1,table1.column2,table2.column1,....FROM table1
RIGHT JOIN table2 ON table1.matching_column = table2.matching_column;
Ex:SELECT Students.NAME,Courses.COURSE_ID FROM Student LEFT
JOIN Courses ON students.student_id = courses.student_id
FULL JOIN creates the result-set by combining results of both LEFT JOIN and
RIGHT JOIN. The result-set will contain all the rows from both tables. For the
rows for which there is no matching, the result-set will contain NULL values
Sy:
SELECT table1.column1,table1.column2,table2.column1,.... FROM table1
FULL JOIN table2 ON table1.matching_column = table2.matching_column;
Ex: Ex:SELECT Students.NAME,Courses.COURSE_ID FROM Student
LEFT JOIN Courses ON students.student_id = courses.student_id

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

1.Concat() : This function Concatenates two strings.

Select CONCAT(‘Ravindra’,’College’) from dual;

O/P : RanindraCollege

2.Len ():This string Returns the number of character

Select length(‘DIET ’) from dual;

O/P :

3.Lower() :This string Converts the string to lower case.

Select LOWER(‘DIET’) from dual;

O/P : diet

4.Upper() :This string Converts the string to upper case.

Select UPPER(‘diet’) from dual;

O/P : DIET

5.Ltrim() : This function is used to remove extra spaces from the beginning of a string.

Trim blanks from the left of x.

Select LTRIM(‘ diet ’) from dual;

6.Rtrim() : This function is used to remove extra spaces from the end of a string.

Trim blanks from the right of x.

Select RTRIM(‘ diet ’) from dual;

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.

Syn: SUBSTRING(source_string, position, length);

Select Substr(‘this is college’,6,7) from dual;


O/P : is my c

8.lpad() The LPAD() function left-pads a string with another string, to a certain length.

SELECT LPAD("ravindra college", 30, "*") from dual;

9.Rpad() The RPAD() function right-pads a string with another string, to a certain length

SELECT RPAD("Ravindra college", 30, "ABC") from dual;

10.Reverse() :This function Returns the reversed string.

Select Reverse(‘DIET’);

O/P : TEID

11. Instr()The INSTR() function returns the position of the first occurrence of a string in
another string.

SELECT INSTR(ename, "a") from employee;

Select instr(“Ravindra college”,”o”) from dual;

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.

Select initcap(“hello world”) from dual;

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

alue in a list of expressions.

Syntax: SELECT GREATEST(30, 2, 36, 81, 125) from dual;

2.LEAST(): It returns the smallest value in a list of expressions.

Syntax: SELECT LEAST(30, 2, 36, 81, 125) from dual;


4.POWER(m, n): It returns m raised to the nth power.

Syntax: SELECT POWER(4, 2) from dual;

5.SQRT(): It returns the square root of a number.

Syntax: SELECT SQRT(25) from dual;

Output: 243.5

7.MOD(n, m)

• n: The number you want to divide.

• m: The number by which you want to divide n.

SELECT MOD(18, 4) from dual;

8.Truncate()

Truncates a number to the specified no of decimal places

Select trunc(357.445,1) from dual;

o/p 357.4

9.CEIL(): It returns the smallest integer value that is greater than or equal to a number.

Syntax: SELECT CEIL(25.75) from dual;

10.COS(): It returns the cosine of a number, in radians.

Syntax: SELECT COS(30) from dual

11.FLOOR(): It returns the largest integer value that is less than or equal to a number.

Syntax: SELECT FLOOR(25.75) from dual;

12.1ROUND(): It returns a number rounded to a certain number of decimal places.

Syntax: SELECT ROUND(5.553) from dual;

Output: 6

3.SIGN(): It returns a value indicating the sign of a number. A return value of 1 means
positive; 0 means negative.

Syntax: SELECT SIGN(255.5) from dual;


Output: 1

Date and time function


Date manipulating functions in SQL

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 –

Select ADD_MONTHS(SYSDATE, 4) from dual;

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)

SELECT LAST_DAY('15-FEB-2024') FROM dual;

3.MONTHS_BETWEEN :
Returns number of months between date1 and date2.

Syntax :MONTHS_BETWEEN(date1, date2)

Select MONTHS_BETWEEN('02-FEB-2024', '01-July-2024’) from dual;

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

Syntax :NEXT_DAY(date, char)

SELECT NEXT_DAY('06-JUL-02', 'saturday’) from dual;

5. SYSDATE: Returns the current date and time.

Example: SELECT SYSDATE FROM DUAL;

6.sysdate():display system date

Select SYSDATE from dual;


6. currentdate()

Select current_date from dual;

7. current time()

Select current_time from dual;

8.current timestamp(): display date and time

Select current_timestamp from dual;

Topic: String conversions


1.To_char():
TO_CHAR function is used to typecast a numeric or date input to a character type
with a format model (optional).
Formatting Dates with TO_CHAR
TO_CHAR offers a wide range of format elements for dates. Here are some
common ones:
• YYYY: Four-digit year
• MM: Two-digit month
• MON: Abbreviated month name
• DAY: Full name of the day
• HH24: Hour in 24-hour format
• MI: Minutes
• SS: Seconds
1) to_char --> takes date type input as argument 1 and converts the date to text of
what you specify in 2nd argument. Output is string.
select to_char(sysdate,'DD-MON-YYYY') from dual;
-- Output--

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;

TOPIC:GROUPBY HAVING CLAUSE


The SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword cannot be
used with aggregate functions.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
• Having clause is used to filter data according to the conditions provided.
• Having a clause is generally used in reports of large data.
• Having clause is only used with the SELECT clause.
• The expression in the syntax can only have constants.
• In the query, ORDER BY is to be placed after the HAVING clause, if any.
• HAVING Clause is implemented in column operation.
• Having clause is generally used after GROUP BY.
EX:

SELECT Department, sum(Salary) as Salary FROM employee GROUP BY


department

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

Topic:Relational set operations IN SQL


The SQL Set operation is used to combine the two or more SQL SELECT
statements.
Types of Set Operation
1. Union
2. UnionAll
3. Intersect
4. Minus
1.Union
The SQL Union operation is used to combine the result of two or more SQL
SELECT queries.
In the union operation, all the number of datatype and columns must be same in
both the tables on which UNION operation is being applied.
The union operation eliminates the duplicate rows from its resultset.
Syntax
SELECT column_name1,columnname2………. FROM table1
UNION
SELECT column_name1,columnname2………. FROM table2;
2.Union All
Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.
Syntax:
SELECT column_name FROM table1 UNION ALL
SELECT column_name FROM table2;
3.Intersect
It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
In the Intersect operation, the number of datatype and columns must be the same. o
It has no duplicates and it arranges the data in ascending order by default.
Syntax
SELECT column_name FROM table1 INTERSECT
• SELECT column_name FROM table2;
• Minus
It combines the result of two SELECT statements. Minus operator is used to
display the rows which are present in the first query but absent in the second query.
It has no duplicates and data arranged in ascending order by default.
Syntax:
SELECT column_name FROM table1 MINUS
SELECT column_name FROM table2;
EX:

1.SELECT dept_id FROM employee UNION SELECT dept_id FROM dept;

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.

You might also like