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

Dbms 1

The document provides an overview of SQL commands categorized into DDL, DQL, DML, and DCL, detailing their syntax and examples for creating, altering, and managing database tables. It also covers advanced querying techniques using clauses like ANY, ALL, IN, EXISTS, and aggregate functions such as COUNT, SUM, AVG, MAX, and MIN. Additionally, it demonstrates how to execute queries to retrieve specific data, including the use of joins and subqueries.

Uploaded by

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

Dbms 1

The document provides an overview of SQL commands categorized into DDL, DQL, DML, and DCL, detailing their syntax and examples for creating, altering, and managing database tables. It also covers advanced querying techniques using clauses like ANY, ALL, IN, EXISTS, and aggregate functions such as COUNT, SUM, AVG, MAX, and MIN. Additionally, it demonstrates how to execute queries to retrieve specific data, including the use of joins and subqueries.

Uploaded by

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

Date: Exp No: Page

No:

1)Creation, altering and droping of tables and inserting rows into a table (use constraints
while creating tables) examples using SELECT command.

1. DDL (Data Definition Language):DDL commands are used to define and modify the
structure of database objects. This includes creating, altering, and deleting databases,
tables, indexes, and other database elements.

a) CREATE : Used to create database objects .


Syntax: CREATE TABLE table_name (column1 datatype constraints, column2 datatype
constraints, ...);
Eg: CREATE TABLE Student (StuID INT PRIMARY KEY, FirstName VARCHAR(50), LastName
VARCHAR(50));
Output : Table created.

SQL> DESC STUD;


Name Null? Type
-------------------- -------- -----------------------
STUID NOT NULL NUMBER(38)
FirstNAME VARCHAR2(50)
LASTNAME VARCHAR2(50)

b) ALTER: Used to modify existing database objects .


Syntax: ALTER TABLE table_name ADD column_name datatype;
Eg: ALTER TABLE Student ADD email VARCHAR(100);
Output: Table altered.
SQL> DESC STUD;
Name Null? Type
------------------- ---------------- --------------------
STUID NOT NULL NUMBER(38)
F_NAME VARCHAR2(50)
LASTNAME VARCHAR2(50)
EMAIL VARCHAR(100)

c)DROP: Used to delete database objects.


Syntax: Drop table tablename;
Eg : Drop table Student;
Output: table dropped
SQL> DESC STUD;
ERROR:
ORA-04043: object STUD does not exist

d)TRUNCATE: Used to remove all rows from a table.


Syntax: Truncate table table name;
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
Eg: Truncate table Student;
Output: table truncated
SQL> DESC STUD;
ERROR:
ORA-04043: object STUD does not exist

2. DQL (Data Query Language):DQL commands are used to retrieve data from the database.
The primary DQL command is:
a)SELECT: Used to query and retrieve data from tables.
Syntax: SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY
column_name;
Eg: select * from Student;
Output:
EMPLOYEEID FIRSTNAME LASTNAME AGE
------------------- ---------------- ----------------- ----------

1 Sasra Jupelli 19
2 Veda Rohan 18
3 Rishi Karanam 18
4 Mahesh Babu 22
5 Kalyani Tamatam 25

b)WHERE CLAUSE: Filters records based on a condition.

SYNTAX: SELECT column1, column2 FROM table_name WHERE condition;

EG: SELECT * FROM Student WHERE FIRSTNAME = 'Rishi';

OUTPUT: stuID F_NAME LASTNAME MARKS

------- ---------- ----------------- ----------

23501 KEERA RAJINI 99

C)ORDER BY: Sorts the result in ascending (ASC) or descending (DESC) order.

SYNTAX: SELECT column1, column2 FROM table_name ORDER BY column_name [ASC|


DESC];

EG: SELECT F_NAME, Marks FROM Stud ORDER BY Marks DESC LIMIT 2;

OUTPUT: F_NAME MARKS

----------------------- ----------
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
balani 100

Keera 99

D)GROUP BY: Groups rows with the same values and performs aggregate functions.

SYNTAX: SELECT column1, COUNT(*) FROM table_name GROUP BY column1;

EG:SQL> SELECT Marks, COUNT(*) FROM Stud GROUP BY Marks;


MARKS COUNT(*)
---------- ----------
100 1
87 1
78 1
90 1
86 1
66 1
99 1
98 1

8 rows selected.

E)HAVING: Filters aggregated results (used with GROUP BY).

SYNTAX: SELECT column1, COUNT(*) FROM table_name GROUP BY column1 HAVING


condition;

EG: SQL> SELECT Marks, COUNT(*) FROM Stud GROUP BY Marks HAVING COUNT(*) > 1;

OUTPUT: no rows selected (BECAUSE ALL MARKS ARE UNIQUE).

3. DML (Data Manipulation Language):DML commands are used to manipulate the data
within database tables. This involves inserting, updating, and deleting data.
Key DML commands:

a)INSERT: Used to add new rows to a table.


Syntax: INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Eg:
INSERT INTO Student(StuID,FirstName,LastName,age)
VALUES(1,'Sasra','Jupelli',19);
INSERT INTO Student (StuID,FirstName, LastName,age)
VALUES(2,'Veda’,’Rohan’ ,18);
INSERT INTO Student (StuID,FirstName, LastName, age)
VALUES(3,'Rishi','Karanam',18);
INSERT INTO Student (StuID,FirstName, LastName, age)
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
VALUES(4,’Mahesh’ ,’Babu ',22);
INSERT INTO Student (StuID,FirstName, LastName, age)
VALUES(5,'Kalyani','Tamatam',25);
Output: 1 row created.(for all)

select * from Student;


EMPLOYEEID FIRSTNAME LASTNAME AGE
------------------- ---------------- ----------------- ----------

1 Sasra Jupelli 19
2 Veda Rohan 18
3 Rishi Karanam 18
4 Mahesh Babu 22
5 Kalyani Tamatam 25

b)UPDATE: Used to modify existing rows in a table.


Syntax: UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
Eg: UPDATE Student SET age=22 WHERE StuID = 2;
Output: 1 row updated.
select * from Student;
Output:
EMPLOYEEID FIRSTNAME LASTNAME AGE
------------------- ---------------- ----------------- ----------

1 Sasra Jupelli 19
2 Veda Rohan 22
3 Rishi Karanam 18
4 Mahesh Babu 22
5 Kalyani Tamatam 25

c)DELETE: Used to remove rows from a table.


Syntax: DELETE FROM table_name WHERE condition;
Eg: DELETE FROM student WHERE StuID=4;
Output: 1 row deleted.
select * from Student;
Output:
EMPLOYEEID FIRSTNAME LASTNAME AGE
------------------- ---------------- ----------------- ----------

1 Sasra Jupelli 19
2 Veda Rohan 18
3 Rishi Karanam 18
5 Kalyani Tamatam 25
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:

4. DCL (Data Control Language):DCL commands are used to control access to data within
the database. This involves granting and revoking permissions to users.
Key DCL commands:

a) GRANT : Used to give users access privileges.


Syntax: Grant privellages _names on table_name to user;
Eg: SQL> GRANT CREATE SESSION TO lbsnaa;
Grant succeeded.
SQL> grant all on staff to lbsnaa;
Output: Grant succeeded.

b) REVOKE : Used to remove access privileges.


Syntax: revoke privileges on tablename from user;
Eg: revoke all on student fromlbsnaa;
Output: Revoke succeeded.

RESULT: Hence to Creation, altering and droping of tables and inserting rows into a table is
executed successfully.

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:

2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints. Example:- Select the roll number and name of the student who
secured fourth rank in the class.

Description
This query retrieves the roll number and name of the student who secured the 4th rank in the
class by joining the teacher and results tables.

SQL> create table stu(


2 stid int primary key,
3 stname varchar(15),
4 stage number(3)
5 );
Table created.

SQL> insert into stu values(1,'rishi',20);


1 row created.

SQL> insert into stu values(2,'rohith',16);


1 row created.

SQL> insert into stu values(3,'vedit',18);


1 row created.

SQL> insert into stu values(4,'kumar',20);


1 row created.

SQL> insert into stu values(5,'mansoor',19);


1 row created.

SQL> select * from stu;

STID STNAME STAGE


CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
---------- --------------- ----------
1 rishi 20
2 rohith 16
3 vedit 18
4 kumar 20
5 mansoor 19

SQL> update stu


2 set stmarks=case
3 when stid=1 then 67
4 when stid=2 then 89
5 when stid=3 then 76
6 when stid=4 then 98
7 when stid=4 then 55
8 else 0
9 end;
5 rows updated.

SQL> select * from stu;


STID STNAME STAGE STMARKS
---------- --------------- --------- ----------
1 rishi 20 67
2 rohith 16 89
3 vedit 18 76
4 kumar 20 98
5 mansoor 19 55

SQL> create table stu(


2 stu_id int ,
3 subject varchar(5),
4 cls varchar(5)
5 rank int );
Table created.

SQL> insert into results(stu_id,subject,cls ,rank)


2 values(1,'os',’cse’,4);
1 row created.

SQL> insert into results(stu_id,subject, cls,rank)


2 values(2,'se',’ece’,1);
1 row created.

SQL> insert into results(stu_id,subject, cls,rank)


2 values(3,'es',’me’,3);
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
1 row created.

SQL> insert into results(stu_id,subject, cls,rank)


2 values(4,'os',’cse’,7);
1 row created.

SQL> insert into results(stu_id,subject, cls,rank)


2 values(5,'es',’ce’,6);
1 row created.

SQL> select * from results;


STU_ID SUBJECT CLS RANK
---------- ---------- ---------- ----------
1 os cse 4
2 se ece 1
3 es me 3
4 os cse 7
5 es ce 6

1. Selecting Data with a JOIN


SYNTAX: SELECT column1, column2 FROM table1 JOIN table2 ON table1.common_column =
table2.common_column WHERE condition;
EXAMPLE: SELECT s.stid, s.stname
FROM stu s
JOIN results r ON s.stid = r.stu_id
WHERE r.rank = 4;

2.USING ANY CLAUSE:


Syntax:
SELECT column_name
FROM table_name
WHERE column_name > ANY (SELECT column_name FROM table_name WHERE condition);
EXAMPLE:
select stu_id from results where marks>any(select marks from results where rank =4);
OUTPUT:
STU_ID
----------
2
3
5

3.USING ALL CLAUSE:


SYNTAX:

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:
SELECT column_name FROM table_name WHERE column_name > ANY (SELECT
column_name FROM table_name WHERE condition);
EXAMPLE:
select stu_id from results where marks>all(select marks from results where rank =4);
OUTPUT:
STU_ID
----------
2
3
5

4.USING IN CLAUSE:
SYNTAX: SELECT column_name FROM table_name WHERE column_name IN (value1,
value2, ...);
EXAMPLE: select stu_id from results where rank in (1,2,3);
OUTPUT:
STU_ID
----------
2
3

5.USING EXIST CLAUSE:


SYNTAX: SELECT column_name FROM table1 WHERE EXISTS (SELECT * FROM table2
WHERE condition);
EXAMPLE: select stu_id from results s where exists (select * from results where s.rank =4
and s.marks=marks);
OUTPUT:
STU_ID
----------
1

6.USING NOT EXIST CLAUSE:


SYNTAX: SELECT column_name FROM table1 WHERE NOT EXISTS (SELECT * FROM table2
WHERE condition);
EXAMPLE: select stu_id from results s where not exists (select * from results where s.rank
=4 and s.marks>marks);
OUTPUT:
STU_ID
----------
2
3
4
5

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:

7.Using UNION Clause:


SYNTAX:
SELECT column_name FROM table1 WHERE condition UNION SELECT column_name FROM
table2 WHERE condition;
EXAMPLE: select stu_id from results where rank=4 union select stu_id from results where
rank=3;
OUTPUT:
STU_ID
----------
1
3
8. Using INTERSECT Clause:
SYNTAX: SELECT column_name FROM table1 WHERE condition INTERSECT SELECT
column_name FROM table2 WHERE condition;
EXAMPLE: select stu_id,subject from results where rank>3
intersect
select stu_id,subject from results where marks>80;
OUTPUT:
STU_ID SUBJE
---------- -----
1 os
4 os
5 es

RESULT: Hence Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS,
UNION, INTERSET, Constraints. Example:- Select the roll number and name of the student
who secured fourth rank in the class is executed successfully.

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:

3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
Aggregate functions perform calculations on a set of values and return a single value.

 COUNT() → Counts the number of rows.


 SUM() → Returns the sum of values.
 AVG() → Returns the average value.
 MAX() → Returns the maximum value.
 MIN() → Returns the minimum value.

SQL>select * from stu;

STID STNAME STAGE STMARKS


---------- --------------- --------- ----------
1 rishi 20 67
2 rohith 16 89
3 vedit 18 76
4 kumar 20 98
5 mansoor 19 55
5 rows selected.

(a) COUNT() :Counts the number of rows in a table or a specific column.


Syntax: SELECT COUNT(column_name) FROM table_name;
EXAMPLE: select count (stname) from stu;
OUTPUT
COUNT(stname)
--------------
5

(b) SUM():Returns the total sum of a numeric column.

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:
SYNTAX: SELECT SUM(column_name) FROM table_name;
EXAMPLE: select sum(stmarks) from stu;
OUTPUT:

SUM(MARKS)
----------
385

(c) AVG():Returns the average (mean) of a numeric column.


SYNTAX: SELECT AVG(column_name) FROM table_name;
EXAMPLE: select avg(stmarks) from stu;
OUTPUT:
AVG(STMARKS)
----------
77

(d) MAX(): Returns the highest value in a column.j


Syntax : SELECT MAX(column_name) FROM table_name;
Example: select max(stmarks) from stu;
OUTPUT:
MAX(STMARKS)
----------
98

(e) MIN():Returns the lowest value in a column.


SYNTAX: SELECT MIN(column_name) FROM table_name;
EXAMPLE: select min(stmarks) from stu;
OUTPUT:
MIN(MARKS)
----------
55

GROUP BY: groups rows with the same values.


SYNTAX: SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
EXAMPLE: select subject, sum(stmarks) from stu GROUP BY stage;
OUTPUT:
STAGE SUM(STMARKS)
---- --------------------
16 89
18 76
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
19 55
20 165

ORDER BY:order rows with the same values


SYNTAX: : SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
EXAMPLE: select stname,stage from stu ORDER BY stname;

OUTPUT:
STNAME STAGE
----- ----
kumar 20
mansoor 19
vedit 18
rishi 20
rohit 16
5 rows selected.

HAVING: filters grouped results based on conditions.


SYNTAX: SELECT column_name, aggregate_function(column_name) FROM table_name
GROUP BY column_name HAVING condition;
EXAMPLE: select stage, sum(stmarks) from stu GROUP BY subject HAVING
SUM(stmarks)>100;
OUTPUT:
STAGE STMARKS
---- ----------
20 165

CREATE VIEW: A view is a virtual table based on an SQL query.


SYNTAX: CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name
WHERE condition;
EXAMPLE: create view high_achievers AS select stname,stmarks from stu where marks>90;
Output: View created.
select * from high_achievers;
STNAME STMARKS
----- ---------
Kumar 98
create view v2 as select stmarks from high_achievers with read only constraint c1;
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
View created.
select * from v2;
STMARKS
----------
98

DROP VIEW: Deletes a view from the database.


Syntax: DROP VIEW view_name;
Example: drop view high_achievers;
Output: View dropped.

Result: Hence Queries using Aggregate functions is executed successfully.


4. Queries using Conversion functions (to_char, to_number and to_date), string functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr),
date functions (Sysdate, next_day, add_months, last_day, months_between, least,
greatest, trunc, round, to_char, to_date)

1.Conversion functions
To_char: Converts a number or date to a string.
Syntax: TO_CHAR(value, format)
Example: SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') AS formatted_date
FROM DUAL;
Output:
FORMATTED_DATE
-----------------------------
06-MAR-2025 17:07:04

TO_NUMBER: Converts a string to a number.


Syntax: TO_NUMBER(string, format)
Example: SELECT TO_NUMBER('12345') AS number_value FROM DUAL;
Output:
NUMBER_VALUE
------------
12345

TO_DATE: Converts a string to a date.


Syntax: TO_DATE(string, format)
Example: SELECT TO_DATE('05-MAR-2025', 'DD-MON-YYYY') AS date_value FROM DUAL;
Output:
DATE_VALUE
-----------
06-MAR-25

1. String Functions
Concatenation (||): Combines two or more strings.
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
Syntax: string1 || string2
Example: SELECT 'lighter' || ' Princess' AS greeting FROM DUAL;
Output:
GREETING
-----------
Lighter Princess
LPAD: Pads a string from the left with a specified character.
Syntax: LPAD(string, length, pad_char)
Example: SELECT LPAD('535', 5, '0') AS padded_string FROM DUAL;
Output:
PADDED_STRING
--------------
00535

RPAD: Pads a string from the right with a specified character.


Syntax: RPAD(string, length, pad_char)
Example: SELECT RPAD('laari', 6, '*') AS padded_string FROM DUAL;
Output:
PADDED
------
laari*
L:TRIM: Removes leading spaces or specified characters.
Syntax: LTRIM(string, trim_char)
Example: SELECT LTRIM('kalyani', ' ') AS trimmed_string FROM DUAL;
Output:
TRIMMED_STRING
--------------
Kalyani
RTRIM: Removes trailing spaces or specified characters.
Syntax: RTRIM(string, trim_char)
Example: SELECT RTRIM('ravi', ' ') AS trimmed_string FROM DUAL;
Output:
TRIMMED_STRING
--------------
ravi
LOWER: Converts a string to lowercase
Syntax: LOWER(string)
Example: SELECT LOWER('Lbsnaa') AS lower_case FROM DUAL;
Output:
LOWER_CASE
------------
lbsnaa
UPPER: Converts a string to uppercase.
Syntax: UPPER(string)

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:
Example: SELECT UPPER('lbsnaa') AS upper_case FROM DUAL;
Output:
UPPER_CASE
------------
LBSNAA
INITCAP: Converts the first letter of each word to uppercase.
Syntax: INITCAP(string)
Example: SELECT INITCAP('hello youth') AS title_case FROM DUAL;
Output:
TITLE_CASE
------------
Hello Youth
LENGTH: Returns the length of a string.
Syntax: LENGTH(string)
Example: SELECT LENGTH('programming') AS string_length FROM DUAL;
Output:
STRING_LENGTH
-------------
11
SUBSTR: Extracts a substring from a string.
Syntax: SUBSTR(string, start_position, length)
Example: SELECT SUBSTR('Datamanagement', 2, 4) AS substring FROM DUAL;
Output:
SUBSTRING
------------
ata
INSTR: Finds the position of a substring in a string
Syntax: INSTR(string, substring)
Example: SELECT INSTR('lahari', 'a') AS position FROM DUAL;
Output:
POSITION
---------
2

3.Date Functions
SYSDATE: Returns the current system date and time.
Syntax: SYSDATE
Example: SELECT SYSDATE FROM DUAL;
Output:
SYSDATE
-----------
06-MAR-25
NEXT_DAY: Returns the next occurrence of a given day of the week.
Syntax: NEXT_DAY(date, 'day')

CSE Dept DBMS


Laboratory
Date: Exp No: Page
No:
Example: SELECT NEXT_DAY(SYSDATE, 'Monday') AS next_monday FROM DUAL;
Output:

NEXT_MONDAY
-----------
10-MAR-25
ADD_MONTHS: Adds a number of months to a date
Syntax: DD_MONTHS(date, number_of_months)
Example: SELECT ADD_MONTHS(SYSDATE, 3) AS future_date FROM DUAL;
Output:
FUTURE_DATE
-----------
05-JUN-25
LAST_DAY: Returns the last day of the month for a given date.
Syntax: LAST_DAY(date)
Example: SELECT LAST_DAY(SYSDATE) AS last_day FROM DUAL;
Output:
LAST_DAY
-----------
31-MAR-25
MONTHS_BETWEEN: Returns the number of months between two dates.
Syntax: MONTHS_BETWEEN(date1, date2)
Example: SELECT MONTHS_BETWEEN('01-JUN-2025', '01-MAR-2025') AS
months_diff FROM DUAL;
Output:
MONTHS_DIFF
------------
3
LEAST: Returns the smallest value among given values.
Syntax: LEAST(value1, value2, ...)
Example: SELECT LEAST(10, 20, 55, 30) AS min_value FROM DUAL;
Output:
MIN_VALUE
---------
10
GREATEST: Returns the largest value among given values.
Syntax: GREATEST(value1, value2, ...)
Example: SELECT GREATEST(10, 60, 5, 30) AS max_value FROM DUAL;
Output:
MAX_VALUE
---------
60
TRUNC: Truncates a date or number to a specific unit.
Syntax: TRUNC(value, unit)
Example: SELECT TRUNC(SYSDATE, 'MM') AS truncated_date FROM DUAL;
CSE Dept DBMS
Laboratory
Date: Exp No: Page
No:
Output:
TRUNCATED_DATE
-----------
01-MAR-25
ROUND: Rounds a date or number.
Syntax: ROUND(value, unit)
Example: SELECT ROUND(SYSDATE, 'MM') AS rounded_date FROM DUAL;
Output:
ROUNDED_DATE
-----------
01-MAR-25
RESULT: Hence to Implement queries using conversion functions ,
stringfunctions ,datafunction is executed successfully.

CSE Dept DBMS


Laboratory

You might also like