0% found this document useful (0 votes)
15 views25 pages

Week 4&5

The document provides an overview of SQL table creation, including the structure of the EMP and DEPT tables, along with their columns and data types. It also outlines various SQL commands for inserting data, selecting records, and performing calculations, as well as string, numeric, date, conversion, and aggregate functions. Additionally, it covers ordering query results and pattern matching using LIKE and regular expressions.

Uploaded by

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

Week 4&5

The document provides an overview of SQL table creation, including the structure of the EMP and DEPT tables, along with their columns and data types. It also outlines various SQL commands for inserting data, selecting records, and performing calculations, as well as string, numeric, date, conversion, and aggregate functions. Additionally, it covers ordering query results and pattern matching using LIKE and regular expressions.

Uploaded by

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

SQL

CREATE TABLE table_name


( column_name1 datatype [constraint],
column_name2 datatype [constraint], ...
[table_constraints] );

1.table_name: The name of the table.


2.column_name: The name of the column.
3.datatype: The data type of the column (e.g., VARCHAR2,
NUMBER, DATE).
4.constraint: Constraints for the column (e.g., NOT NULL,
UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, etc.).
5.table_constraints: Optional constraints at the table level.
Emp Table
Column Name Data Type Description
Employee number
EMPNO NUMBER(4)
(Primary Key).
ENAME VARCHAR2(10) Employee name.
JOB VARCHAR2(9) Job title of the employee.
Manager's employee
MGR NUMBER(4)
number (foreign key).
Date when the employee
HIREDATE DATE
was hired.
SAL NUMBER(7, 2) Salary of the employee.

COMM NUMBER(7, 2) Commission (if applicable).

Department number
DEPTNO NUMBER(2)
(foreign key).
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 1980-12-17 800.00 NULL 20

7499 ALLEN SALESMAN 7698 1981-02-20 1600.00 300.00 30

7521 WARD SALESMAN 7698 1981-02-22 1250.00 500.00 30

7566 JONES MANAGER 7839 1981-04-02 2975.00 NULL 20

7698 BLAKE MANAGER 7839 1981-05-01 2850.00 NULL 30

7782 CLARK MANAGER 7839 1981-06-09 2450.00 NULL 10

7788 SCOTT ANALYST 7566 1987-04-19 3000.00 NULL 20

7839 KING PRESIDENT NULL 1981-11-17 5000.00 NULL 10

7844 TURNER SALESMAN 7698 1981-09-08 1500.00 0.00 30

7900 JAMES CLERK 7698 1981-12-03 950.00 NULL 30

7902 FORD ANALYST 7566 1981-12-03 3000.00 NULL 20

7934 MILLER CLERK 7782 1982-01-23 1300.00 NULL 10


DEPT Table

Column Name Data Type Description


Department number
DEPTNO NUMBER(2)
(Primary Key).
DNAME VARCHAR2(14) Name of the department.
Location of the
LOC VARCHAR2(13)
department.
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Inserting values in tables
INSERT INTO table_name (column1, column2,
column3, ...) VALUES (value1, value2, value3, ...);

•table_name: The name of the table where you want to insert data.
•column1, column2, ...: A list of the columns to insert data int

value1, value2, ...: The corresponding values for the columns.
Select statement
SELECT column1, column2, ...
FROM table_name
WHERE condition
ALTER TABLE EMP ADD CONSTRAINT PK_EMP
PRIMARY KEY (EMPNO);

CREATE TABLE DEPT ( DEPTNO NUMBER(2)


PRIMARY KEY, DNAME VARCHAR2(50), LOC
VARCHAR2(50) );

ALTER TABLE EMP ADD CONSTRAINT FK_DEPT


FOREIGN KEY (DEPTNO) REFERENCES DEPT(DEPTNO);
1. Compute Annual Salary of Employees

SELECT ENAME, SAL, SAL * 12 AS ANNUAL_SALARY FROM EMP;

2. Compute Salary After a 10% Increase

SELECT ENAME, SAL, SAL * 1.10 AS NEW_SALARY FROM EMP;

3. Compute Total Salary Paid to All Employees

SELECT SUM(SAL) AS TOTAL_SALARY FROM EMP;

4. Compute Average Salary of Employees

SELECT AVG(SAL) AS AVERAGE_SALARY FROM EMP;

5. Compute Highest & Lowest Salary in the Company

SELECT MAX(SAL) AS HIGHEST_SALARY, MIN(SAL) AS LOWEST_SALARY FROM


EMP;
6. Compute Total Salary Paid by Each Department

SELECT DEPTNO, SUM(SAL) AS TOTAL_SALARY FROM EMP GROUP BY


DEPTNO;

7. Compute Number of Employees in Each Job Role

SELECT JOB, COUNT(*) AS TOTAL_EMPLOYEES FROM EMP GROUP BY JOB;

8. Compute Commission with Salary (If Applicable)

SELECT ENAME, SAL, COMM, NVL(COMM, 0) + SAL AS TOTAL_EARNINGS


FROM EMP;

9. Compute Rank of Employees Based on Salary

SELECT ENAME, SAL, RANK() OVER (ORDER BY SAL DESC) AS SALARY_RANK


FROM EMP;

10. Compute Employees Earning More than the Average Salary


SELECT ENAME, SAL FROM EMP WHERE SAL > (SELECT AVG(SAL) FROM EMP);
1. String Functions
Used to manipulate text data (VARCHAR2, CHAR, etc.).

Function Description Example


UPPER Converts text to uppercase SELECT UPPER('hello') FROM DUAL; → HELLO

LOWER Converts text to lowercase SELECT LOWER('HELLO') FROM DUAL; → hello

Capitalizes first letter of each


INITCAP SELECT INITCAP('oracle sql') FROM DUAL; → Oracle Sql
word

LENGTH Returns length of string SELECT LENGTH('Oracle') FROM DUAL; → 6

SUBSTR Extracts part of a string SELECT SUBSTR('DATABASE', 1, 3) FROM DUAL; → DAT

SELECT REPLACE('hello world', 'world', 'Oracle') FROM


REPLACE Replaces a part of a string
DUAL; → hello Oracle

SELECT CONCAT('Hello', ' Oracle') FROM DUAL; → Hello


CONCAT Joins two strings
Oracle

TRIM Removes spaces from both sides SELECT TRIM(' Oracle ') FROM DUAL; → Oracle
2. Numeric Functions
Used for mathematical operations.

Function Description Example


SELECT ABS(-10) FROM
ABS Returns absolute value
DUAL; → 10
Rounds up to nearest SELECT CEIL(10.2) FROM
CEIL
integer DUAL; → 11
Rounds down to nearest SELECT FLOOR(10.8)
FLOOR
integer FROM DUAL; → 10
SELECT ROUND(10.567, 2)
ROUND Rounds a number
FROM DUAL; → 10.57
SELECT TRUNC(10.567, 2)
TRUNC Truncates decimals
FROM DUAL; → 10.56
SELECT MOD(10, 3) FROM
MOD Finds remainder
DUAL; → 1
SELECT POWER(2, 3)
POWER Exponentiation
FROM DUAL; → 8
3. Date Functions
Used to manipulate date values.

Function Description Example


SYSDATE Returns current system date SELECT SYSDATE FROM DUAL;
Returns current date with
CURRENT_DATE session timezone SELECT CURRENT_DATE FROM DUAL;

ADD_MONTHS Adds months to a date SELECT ADD_MONTHS(SYSDATE, 2)


FROM DUAL;

LAST_DAY Returns last day of the month SELECT LAST_DAY(SYSDATE) FROM DUAL;

NEXT_DAY Returns next occurrence of a SELECT NEXT_DAY(SYSDATE, 'MONDAY')


weekday FROM DUAL;

MONTHS_BETWEEN Finds months between two SELECT MONTHS_BETWEEN(SYSDATE,


dates '01-JAN-2023') FROM DUAL;

EXTRACT Extracts part of a date SELECT EXTRACT(YEAR FROM SYSDATE)


FROM DUAL;
4. Conversion Functions
Used to convert data types.

Function Description Example


Converts number or date to SELECT TO_CHAR(SYSDATE, 'DD-MON-
TO_CHAR
string YYYY') FROM DUAL;
SELECT TO_DATE('01-JAN-2024', 'DD-
TO_DATE Converts string to date
MON-YYYY') FROM DUAL;
TO_NUMBER Converts string to number SELECT TO_NUMBER('100') FROM DUAL;
5. Aggregate Functions
Used for calculations on a group of rows.

Function Description Example


SUM Returns sum of values SELECT SUM(SAL) FROM EMP;
AVG Returns average value SELECT AVG(SAL) FROM EMP;
COUNT Returns number of rows SELECT COUNT(*) FROM EMP;
MAX Returns highest value SELECT MAX(SAL) FROM EMP;
MIN Returns lowest value SELECT MIN(SAL) FROM EMP;
Order by clause
The ORDER BY clause is used to sort query
results in either ascending (ASC) or descending
(DESC) order.

SELECT column1, column2 FROM table_name


ORDER BY column_name [ASC | DESC];
1. Order Employees by Salary (Ascending - Default)
SELECT ENAME, JOB, SAL FROM EMP ORDER BY SAL;

2. Order Employees by Salary (Descending)


SELECT ENAME, JOB, SAL FROM EMP ORDER BY SAL DESC;

3. Order Employees by Job Title (Alphabetically)


SELECT ENAME, JOB FROM EMP ORDER BY JOB;

4. Order Employees by Department and Then by Salary


SELECT ENAME, DEPTNO, SAL FROM EMP ORDER BY DEPTNO, SAL DESC;

5. Order Employees by Hire Date (Oldest to Newest)


SELECT ENAME, HIREDATE FROM EMP ORDER BY HIREDATE;
6. Order Employees by Multiple Columns
SELECT ENAME, JOB, SAL FROM EMP ORDER BY JOB ASC,
SAL DESC;

ORDER BY with NULL Values


By default, NULL values appear last in ascending order and
first in descending order.
SELECT ENAME, COMM FROM EMP ORDER BY COMM
NULLS LAST;
SELECT ENAME, COMM FROM EMP ORDER BY COMM
NULLS FIRST;
Pattern Matching
1. Using the LIKE Operator
The LIKE operator is used to search for a specified pattern in a column.
Basic Syntax:
SELECT column1 FROM table_name WHERE column_name LIKE 'pattern';
% represents zero or more characters.
_ represents one character.

1. Find Employees Whose Name Starts with 'A'

SELECT ENAME FROM EMP WHERE ENAME LIKE 'A%';


2. Find Employees Whose Name Ends with 'N'
SELECT ENAME FROM EMP WHERE ENAME LIKE '%N';
3. Find Employees Whose Name Has 'E' as the Second Letter
SELECT ENAME FROM EMP WHERE ENAME LIKE '_E%';

4. Find Employees with 'A' in Any Position


SELECT ENAME FROM EMP WHERE ENAME LIKE '%A%';
2. Using Regular Expressions with REGEXP_LIKE
REGEXP_LIKE is used to search for a regular expression pattern within a
column.
Basic Syntax:
SELECT column1 FROM table_name WHERE REGEXP_LIKE(column_name,
'pattern');

1. Find Employees Whose Name Contains Any Digit


SELECT ENAME FROM EMP WHERE REGEXP_LIKE(ENAME, '[0-9]');

2. Find Employees Whose Name Contains Exactly 5 Characters


SELECT ENAME FROM EMP WHERE REGEXP_LIKE(ENAME, '^\w{5}$');
3. Using REGEXP_INSTR
REGEXP_INSTR returns the position of the first occurrence of a
regular expression pattern in a string.
Basic Syntax:
SELECT REGEXP_INSTR(column_name, 'pattern') FROM
table_name;

Example:
SELECT ENAME, REGEXP_INSTR(ENAME, '[A-Z]') FROM EMP;
Finds the position of the first uppercase letter in the employee
name.
4. Using REGEXP_SUBSTR
REGEXP_SUBSTR returns the substring that matches the regular
expression.
Basic Syntax:
SELECT REGEXP_SUBSTR(column_name, 'pattern') FROM
table_name;

Example:
SELECT ENAME, REGEXP_SUBSTR(ENAME, 'A[AEIOU]') FROM
EMP;

Extracts the substring starting with 'A' followed by a vowel (e.g.,


'AE', 'AI') from the employee's name.
5. Using REGEXP_REPLACE
REGEXP_REPLACE is used to replace parts of a string that
match a regular expression.
Basic Syntax:
SELECT REGEXP_REPLACE(column_name, 'pattern',
'replacement') FROM table_name;

Example:
SELECT ENAME, REGEXP_REPLACE(ENAME, '[AEIOU]', '*')
FROM EMP;
Replaces all vowels in the employee's name with '*'.

You might also like