0% found this document useful (0 votes)
3 views23 pages

SQL theory & Query

The document provides an extensive overview of databases, including definitions of key concepts such as DBMS, RDBMS, and data warehouses. It covers various SQL commands, data types, constraints, keys, joins, indexes, and differences between operations like DELETE, DROP, and TRUNCATE. Additionally, it explains normalization, data integrity, and the differences between OLAP and OLTP systems.

Uploaded by

Satyajit Ligade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views23 pages

SQL theory & Query

The document provides an extensive overview of databases, including definitions of key concepts such as DBMS, RDBMS, and data warehouses. It covers various SQL commands, data types, constraints, keys, joins, indexes, and differences between operations like DELETE, DROP, and TRUNCATE. Additionally, it explains normalization, data integrity, and the differences between OLAP and OLTP systems.

Uploaded by

Satyajit Ligade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

1. What is Database?

2. What Do You Mean By DBMS? What Are Its Different Types?


3. DBMS vs RDMS vs Data Warehouse ?
4. What are Tables and Fields?
5. DDL, DQL, DML, DCL and TCL Commands ?
6. What Is The Difference Between CHAR And VARCHAR2 Datatype In SQL?
7. What are Constraints in SQL?
8. What is a Primary Key?
9. What is a Foreign Key?
10. What is a Surrogate Key?
11. What is a Composite Key?
12.What Is The Main Disadvantage Of Deleting Data From An Existing Table Using The DROP TABLE
Command?
13. Difference between Delete vs Drop vs Truncate?
14. What is a Join? List its different types.
15. What is a Self-Join and Cross join ?
16. What Is An Index? Explain Different Types Of Indexes In SQL?
17. What is the difference between Clustered and Non-clustered index?
18. What is Data Integrity?
19. What is a Query?
20. What is a Subquery? What are its types?
21. Difference between Subquery and Co-related query?
22. What is the SELECT statement?
23. What are some common clauses used with SELECT query in SQL?
24. Difference between HAVING & WHERE clause?
25. What are UNION, MINUS and INTERSECT commands?
26. What is Cursor? How to use a Cursor?
27. What is an Alias in SQL?
28. What is a View ?
29. View vs Complex View ?
30. What is Materialized View ?
31. View vs Materialized View ?
32. What is Roll up?
33. Is A Blank Space or Zero Same As A NULL Value?
34. What is CTE?
35. What is Trigger?
36. Which Function Is Used To Return Remainder In A Division Operator In SQL?
37. What Is The Difference Between NOW() And CURRENT_DATE()?
38. What is windows function?
39. What are Aggregate functions?
40. What is the Diffrance between Aggregate function and windows function?
41. What Are Scalar Functions?
42. What Are The Difference Between OLAP And OLTP ?
43. What Are The ACID Properties In A Database?
44. What is Normalization and Demoralization?
45. SCD type 0,1,2,3 using set operators and Joins?
1. What is Database?
⦁ Databse is an organized collection of data, stored and retrieved digitally from a remote or local computer
system.
⦁ This is also known as structured form of data which can be accessed in many ways.
⦁ It is also the collection of schemas, tables, queries, views, etc
⦁ Example: School Management Database, Bank Management Database.
⦁ common features of a database:
❖ Manages large amounts of data
❖ Easy to update
❖ Easy to research data.

2. What Do You Mean By DBMS? What Are Its Different Types?


⦁ A Database Management System (DBMS) is a structured collection of data.
⦁ DBMS is a system software responsible for the creation, retrieval, updation, and management of the
database.
⦁ There are two types of DBMS :
1. Relational Database Management System: The data is stored in relations (tables). Example – MySQL,
PostGres etc
2. Non-Relational Database Management System: There is no concept of relations, tuples and attributes.
Example – MongoDB.

3. DBMS vs RDMS vs Data Warehouse ?


⦁ Database Management System (DBMS) is a software that is used to define, create and maintain a
database and provides controlled access to the data.
⦁ Relational Database Management System (RDBMS) is an advanced version of a DBMS.

DBMS RDMS
DBMS stores data as file RDBMS stores data in tabular form.
Is is software that is used to delete, create It is used to store and manage only the data that are
and maintain a database and provides in the form of tables
controlled access to data.
Normalization is not present. Normalization is present.
It is used for small organization and deal with It is used to handle large amount of data.
small data.
It supports single user. It supports multiple users.
Examples: XML, Window Registry, etc. Examples: MySQL, PostgreSQL, SQL Server, Oracle,
Microsoft Access etc.
Low software and hardware necessities. Higher software and hardware necessities.

Database System [DBMS / RDMS] Data Warehouse


Database System is used in traditional way of Data Warehouse is the place where huge amount of
storing and retrieving data. data is stored.
It supports operational processes. It supports analysis and performance reporting.
Capture and maintain the data. Multiple years of history.
Current data. Normalization is present.
Flat relational. ER based. Multidimensional , Star/Snowflake.
Application oriented. Subject oriented.
100 MB to GB 100 GB to TB.
4. What are Tables and Fields?
⦁ A table is an organized collection of data stored in the form of rows and columns.
⦁ Columns can be categorized as vertical and rows as horizontal.
⦁ The columns in a table are called fields while the rows can be referred to as records.

5. DDL, DQL, DML, DCL and TCL Commands ?

DDL DML TCL DQL DCL


Data Data Transaction Data Data
Definition Manipulation Control Query Control
Language. Language. Language. Language Language
1. Create Insert Commit Select Grant
2. Drop Update Savepoint - Revoke
3. Alter Delete Rollback - -
4.Truncate - - - -

6. What Is The Difference Between CHAR And VARCHAR2 Datatype In SQL?


CHAR VARCHAR
CHAR datatype is used to store VARCHAR datatype is used to store
character string of fixed length character string of variable length
In CHAR, If the length of string is less In VARCHAR, If the length of string is less
than set or fixed length then it is padded than set or fixed length then it will store as it
with extra memory space. is without padded with extra memory spaces
CHAR stands for “Character” VARCHAR stands for “Variable Character”
We should use CHAR datatype when we We should use VARCHAR datatype when we
expect the data values in a column are of expect the data values in a column are of
same length. variable length.
Better performance. Performance is not good.

7. What are Constraints in SQL?


⦁ constraints are used to specify rules for data in a table.
⦁ Constraints can be column level or table level.
⦁ Column level constraints apply to a column, and table level constraints apply to the whole table.
1. NOT NULL - Ensures that a column cannot have a NULL value
2. UNIQUE - Ensures that all values in a column are different, helps identify each row uniquely. similar like
PRIMARY KEY.
3. PRIMARY KEY - A combination of a NOT NULL + UNIQUE.
4. FOREIGN KEY - Prevents actions that would destroy links between tables
5. CHECK - Ensures that the values in a column satisfies a specific condition
6. DEFAULT - Sets a default value for a column if no value is specified
7. CREATE INDEX - Used to create and retrieve data from the database very quickly.

8. What is a Primary Key?


⦁ The PRIMARY KEY constraint uniquely identifies each row in a table.
⦁ It must contain UNIQUE values and cannot contain NULL values.
⦁ A table can have only ONE primary key. and consist of single or multiple columns (fields).
Primary key on create table :
CREATE TABLE Customers ( Customer _ID int NOTNULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255) ) ;
Primary key on Alter table :
To create a PRIMARY KEY constraint on "ID" for defining a PRIMARY KEY constraint on
column when the table is already created, multiple columns,
ALTER TABLE Customers ALTER TABLE Customers
ADD ADD
PRIMARY KEY (Customer _ID) CONSTRAINT PK_Customers PRIMARY KEY
(Customer _ID, LastName);
DROP a PRIMARY KEY Constraint :
ALTER TABLE Customers
DROP CONSTRAINT PK_Customers;

9. What is a Foreign Key?


⦁ A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.
⦁ Foreign key constraint ensures referential integrity in the relation between two tables.
⦁ The table with the foreign key is called the child table, and the table with the primary key is called the
referenced or parent table.
Foreign key on create table :
CREATE TABLE Orders ( Order_ID int NOTNULL PRIMARY KEY,
Order_Number int NOT NULL,
Customer _ID int Foreign key refrerences Customers (Customer
_ID) ) ;
Foreign key on Alter table :
ALTER TABLE Orders ALTER TABLE Orders
ADD Foreign KEY (Customer _ID) ADD CONSTRAINT FK_CustomerOrder
refrerences Persons(Customer _ID) Foreign KEY (Customer _ID) refrerences Customers
(Customer _ID);
DROP a PRIMARY KEY Constraint :
ALTER TABLE Orders
DROP CONSTRAINT PK_CustomerOrder ;

10. What is a Surrogate Key?


⦁ Surrogate key also called a synthetic primary key.
⦁ It is generated when a new record is inserted into a table automatically by a database that can be
declared as the primary key of that table.
⦁ It is the sequential number outside of the database. but is not visible to the user.
⦁ Features of the surrogate key :
1. It is automatically generated by the system.
2. It holds anonymous integer.
3. It contains unique value for all records of the table.

11. What is a Composite Key?


⦁ A composite key is made by the combination of two or more columns in a table.
⦁ these columns are used to identify all the rows that are involved uniquely.
⦁ A composite key can also be made by the combination of more than one candidate key.
⦁ A composite key cannot be null.

12.What Is The Main Disadvantage Of Deleting Data From An Existing Table Using The DROP TABLE
Command?
⦁ DROP TABLE command deletes complete data from the table along with removing the complete table
structure too.
⦁ In case our requirement was only just remove the data, then we would need to recreate the table to store
data in it.
⦁ In such cases, it is advised to use the TRUNCATE command.

13. Difference between Delete vs Drop vs Truncate?


DELETE DROP TRUNCATE
It is Data Manipulation DROP command is Data TRUNCATE command is a Data
Language Command. Definition Language Command. Definition Language Command.
The DELETE command is used to DROP Command drops the TRUNCATE command is used to
delete specified rows(one or complete table from the delete all the rows from a existing
more). database table.
We can restore any deleted row We cannot get the complete We cannot restore all the deleted
or multiple rows from the table deleted from database rows from the database using the
database using the ROLLBACK using ROLLBACK command. ROLLBACK command.
command.
The DELETE command performs The DROP Command has faster The TRUNCATE command works
slower than the DROP performance than DELETE faster than the DROP command
command Command but not as compared and DELETE
and TRUNCATE. to the Truncate Command
- DROP command does remove TRUNCATE command does not
the structure of the table. remove the structure of the table.
Syntax: Syntax : Syntax:
DELETE FROM TableName DROP TABLE table_name; TRUNCATE TABLE TableName;
WHERE condition;

14. What is a Join? List its different types.


⦁ Join clause : is used to combine records (rows) from two or more tables , based on a related column
between them.
⦁ four different types of JOINs in SQL:
1. INNER JOIN : Returns records that have matching values in both tables
2. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right
table.
3. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the
left table
4. FULL (OUTER) JOIN : Returns all records when there is a match in either left or right table
INNER JOIN LEFT JOIN RIGHT JOIN FULL JOIN
SELECT * SELECT * SELECT * SELECT *
FROM Table_A FROM Table_A A FROM Table_A A FROM Table_A A
JOIN Table_B; LEFT JOIN Table_B B RIGHT JOIN Table_B B FULL JOIN Table_B B
SELECT * ON A.col = B.col; ON A.col = B.col; ON A.col = B.col;
FROM Table_A
INNER JOIN Table_B;

15. What is a Self-Join and Cross join ?


Self-Join :
⦁ A self JOIN is a case of regular join where a table is joined to itself based on some relation between its
own column(s).
⦁ Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign different names
to the table within the query.
Cross join :
⦁ Cross join can be defined as a cartesian product of the two tables included in the join.
⦁ The table after join contains the same number of rows as in the cross-product of the number of rows in
the two tables.
⦁ If a WHERE clause is used in cross join then the query will work like an INNER JOIN.
Self-Join Cross-Join
SELECT A . emp_id AS "Emp_ID", SELECT stu . name,
A . emp_name AS "Employee", sub.subject
B . emp_id AS "Sup_ID", FROM
B . emp_name AS "Supervisor" students AS stu
FROM employee A, employee B CROSS JOIN
WHERE subjects AS sub;
A.emp_sup = B.emp_id;

16. What Is An Index? Explain Different Types Of Indexes In SQL?


⦁ Index is a data structure that provides a quick lookup of data in a column or columns of a table.
⦁ It also has a unique value meaning that the index cannot be duplicated.
⦁ It is used to increase the performance and allow faster retrieval of records from the table.
⦁ Indexes help speed up searching in the database.
CREATE INDEX index_name /* Create Index
*/
ON table_name (column_1, column_2);

DROP INDEX index_name; /* Drop Index */

⦁ There are different types of indexes :


1. Unique and Non-Unique Index
2. Clustered and Non-Clustered Index:
3. Filtered Index.
4. Hash Index.

Unique and Non-Unique Index:


a. Unique indexes :
⦁ Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a
table have identical key values.
⦁ Once a unique index has been defined for a table, uniqueness is enforced whenever keys are added or
changed within the index.

CREATE UNIQUE INDEX


myIndex
ON students (enroll_no);

b. Non-unique indexes :
⦁ Non-unique indexes on the other hand, are not used to enforce constraints on the tables with which they
are associated.
⦁ Instead, non-unique indexes are used solely to improve query performance by maintaining a sorted order
of data values that are used frequently.

Clustered and Non-Clustered Index:


Clustered Index:
⦁ Clustered indexes sort and store the data rows in the table or view based on their key values.
⦁ it is same as dictionary where the data is arranged by alphabetical order.
⦁ example : If you apply primary key to any column, then automatically it will become clustered index.
⦁ Clustering indexes can improve the performance of most query operations because they provide a linear-
access path to data stored in the database.
Non-Clustered Index :
⦁ The indexes other than PRIMARY indexes (clustered indexes) are called non-clustered indexes.
⦁ The non-clustered indexes are also known as secondary indexes.
⦁ It has a structure separate from the data row.

Filtered Index :
⦁ A filtered index is an optimized disk-based rowstore nonclustered index especially suited to cover
queries that select from a well-defined subset of data.
⦁ It uses a filter predicate to index a portion of rows in the table.

17. What is the difference between Clustered and Non-clustered index?

Clustered Index Non-Clustered Index


Clustered index is faster. Non-clustered index is slower.
Clustered index requires less memory Non-Clustered index requires more
for operations. memory for operations.
In clustered index, index is the main In Non-Clustered index, index is the
data. copy of data.
A table can have only one clustered A table can have multiple non-clustered
index. index.
a table can have a single clustered index it can have multiple non-clustered indexes.

18. What is Data Integrity?


⦁ Data integrity refers to the overall accuracy, completeness, and reliability of data.
⦁ It is maintained by a collection of processes, rules, and standards implemented during the design phase.
⦁ Data Integrity is used to maintain the accuracy and consistency of data in a table.

19. What is a Query?


⦁ A query is a request for data or information from a database table or combination of tables.
⦁ A database query can be either a select query or an action query.

SELECT fname, lname /* select query */


FROM myDb.students
WHERE student_id = 1;
UPDATE myDB.students /* action query */
SET fname = 'Captain', lname = 'America'
WHERE student_id = 1;

20. What is a Subquery? What are its types?


⦁ A subquery is a query within another query, also known as a nested query or inner query.
⦁ It is used to restrict or enhance the data to be queried by the main query, thus restricting or enhancing
the output of the main query respectively.
⦁ For example
SELECT * FROM Customers
WHERE age = ( SELECT MIN(age)
FROM Customers);

There are two types of subquery - Correlated and Non-Correlated.

⦁ A correlated subquery : cannot be considered as an independent query, but it can refer to the column in a
table listed in the FROM of the main query.

⦁ A non-correlated subquery :can be considered as an independent query and the output of the subquery is
substituted in the main query.

21. Difference between Subquery and Co-related query?


Subquery Co-related Subquery
When a query is included inside another A correlated subquery is one way of reading
query, the Outer query is known as Main every row in a table and comparing values in
Query, and Inner query is known as each row against related data.
Subquery.
The inner query is executed only once. So the inner query will get executed as many
times as number of rows in result of the
outer query.
The inner query will get executed first The outer query will get executed first and
and the output of the inner query used by outer query output can use the inner query
the outer query. output for comparison.
The inner query is not dependent on outer Inner query and outer query dependent on
query. each other.
SELECT Employee_name, dept_no FROM Employee
FROM Employee WHERE Employee_name IN (SELECT
WHERE Employee_name IN Employee_name FROM dept WHERE
(SELECT Employee_name FROM Employee.dept_id=dept.dept_id);
Customer);
22. What is the SELECT statement?
⦁ SELECT operator in SQL is used to select data from a database / table.
⦁ The data returned is stored in a result table, called the result-set.
SELECT * FROM students;

23. What are some common clauses used with SELECT query in SQL?
1. WHERE clause it is used to filter records that are necessary, based on specific conditions.
2. ORDER BY clause it is used to sort the records based on some field(s) in ascending (ASC) or descending
order (DESC).
3. GROUP BY clause it is used to group records with identical data and can be used in conjunction with some
aggregation functions to produce summarized results from the database.
4. HAVING clause it is used to filter records in combination with the GROUP BY clause. It is different
from WHERE, since the WHERE clause cannot filter aggregated records.
WHERE , ORDER BY clause GROUP BY ,HAVING clause
SELECT * SELECT COUNT(studentId), country
FROM students FROM students
WHERE graduation_year = 2019 WHERE country != "INDIA"
ORDER BY studentID DESC; GROUP BY country
HAVING COUNT(studentID) > 5;

24. Difference between HAVING & WHERE clause?


⦁ HAVING Clause is used to filter the records from the groups based on the given condition in the
⦁ HAVING Clause. HAVING Clause can only be used with SELECT statement.
⦁ WHERE Clause is used to filter the records from the table or used while joining more than one
⦁ table.
⦁ It can be used with SELECT, UPDATE, DELETE statements

25. What are UNION, MINUS and INTERSECT commands?


UNION UNION ALL
The UNION operator combines the results This operator is similar to the Union
of two or more Select statements by operator, but it does not remove the
removing duplicate rows.The columns and the duplicate rows from the output of
data types must be the same in the SELECT the SELECT statements.
statements.
SELECT columns FROM table1 SELECT columns FROM table1
UNION UNION ALL
SELECT columns FROM table2; SELECT columns FROM table2;

Minus Intersect
The MINUS operator is used to remove combines the result-set fetched by
duplicates from the result-set obtained by the the two SELECT statements ,
second SELECT query from the result-set where records from one match the
obtained by the first SELECT query . other and then returns this
then return the filtered results from the first. intersection of result-sets.
SELECT columns FROM table1 SELECT columns FROM table1
MINUS INTERSECT
SELECT columns FROM table2; SELECT columns FROM table2;
SELECT name FROM Students SELECT name FROM Students
MINUS INTERSECT
SELECT name FROM Contacts; SELECT name FROM Contacts;

26. What is Cursor? How to use a Cursor?


⦁ A database cursor is a control structure that allows for the traversal of records in a database.
⦁ Cursors, in addition, facilitates processing after traversal, such as retrieval, addition, and deletion of
database records.
⦁ They can be viewed as a pointer to one row in a set of rows.
⦁ Working with SQL Cursor:
1. Declare Cursor after any variable declaration. The cursor declaration must always be associated with a
SELECT Statement.
2. Open cursor to initialize the result set. The OPEN statement must be called before fetching rows from
the result set.
3. FETCH statement to retrieve and move to the next row in the result set.
4. Call the CLOSE statement to deactivate the cursor.
5. Finally use the DEALLOCATE statement to delete the cursor definition and release the associated
resources.
DECLARE @name VARCHAR(50) /* Declare All Required Variables */
DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/
SELECT name
FROM myDB.students
WHERE parent_name IN ('Sara', 'Ansh')
OPEN db_cursor /* Open cursor and Fetch data into @name */
FETCH next
FROM db_cursor
INTO @name
CLOSE db_cursor /* Close the cursor and deallocate the resources */
DEALLOCATE db_cursor

27. What is an Alias in SQL?


⦁ It is a temporary name assigned to the table or table column for the purpose of a particular SQL
query.
⦁ aliasing can be employed as an obfuscation technique to secure the real names of database fields.
⦁ A table alias is also called a correlation name.
⦁ An alias is represented explicitly by the AS keyword.
SELECT A.emp_name AS "Employee" /* Alias using AS keyword */
B.emp_name AS "Supervisor"
FROM employee A, employee B /* Alias without AS keyword */
WHERE A.emp_sup = B.emp_id;

28. What is a View ?


⦁ A view is a virtual table based on the result-set of SQL statement.
⦁ A view contains rows and columns, just like a real table.
⦁ Views display only selected data, just like a real table. not stored permanently.
⦁ View can have data of one or more tables combined, and it is depending on the relationship.
⦁ If any changes occur in the existing table, the same changes reflected in the views.
⦁ Views are used for security purposes. because they provide encapsulation of the name of the table.

29. View vs Complex View ?


Simple views Complex View
Simple views can only contain a single base Complex views can be constructed on more than
table. one base table.
Does not contain group of data. It can contain group of data.
We cannot use group function like max(), We can use group function.
count(), etc.
We apply Insert, delete and update on simple We cannot apply Insert, delete and update on
view directly. simple view directly.
create view employee as Create view EmployeeByDepartment AS
select emp_id emp_name
SELECT e.emp_id, d.dept_id, e.emp_name FROM
from employee
Employee e, Department d WHERE
where emp_id = ‘1234’
e.dept_id=d.dept_id;

30. What is Materialized View ?


1. When the results of a view expression are stored in a database system, they are called
materialized views.
2. To update the data in a materialized view, you can use the REFRESH MATERIALIZED VIEW
statement at any time.
3. A materialized view can be either read-only, updatable, or writeable
4. Users cannot perform data manipulation language (DML) statements on read-only materialized views,
but they can perform DML on updatable and writeable materialized views.
⦁ Why Use Materialized Views?
1. Ease Network Loads
2. Create a Mass Deployment Environment
3. Enable Data Subsetting
4. Enable Disconnected Computing

⦁ Read-Only Materialized Views:


CREATE MATERIALIZED VIEW hr.employees AS
SELECT * FROM hr.employees@orc1.example.com;
⦁ Updatable Materialized Views:
CREATE MATERIALIZED VIEW hr.departments FOR UPDATE AS
SELECT * FROM hr.departments@orc1.example.com;

31. View vs Materialized View ?


View Materialized View
a virtual table based on the result-set of SQL When the results of a view expression are
statement. Views display only selected data, stored in a database system, they are called
just like a real table. not stored permanently. materialized views.
It does not have any storage cost It does have any storage cost
views are useful when the view is Materialized views are useful when the
accessed infrequently view is accessed frequently
create view employee as Read-Only Materialized Views:
select emp_id emp_name CREATE MATERIALIZED VIEW
from employee hr.employees AS
SELECT * FROM
where emp_id = ‘1234
hr.employees@orc1.example.com;

32. What is Roll up?


⦁ The ROLLUP is an extension of the GROUP BY clause.
⦁ The ROLLUP option allows you to include extra rows that represent the subtotals,
which are commonly referred to as super-aggregate rows, along with the grand total row.
⦁ By using the ROLLUP option, you can use a single query to generate multiple grouping sets.

33. Is A Blank Space or Zero Same As A NULL Value?


No. The NULL value is not the same as zero or a blank space.
The following points explain their main differences:
❏ A NULL value is a value, which is 'unavailable, unassigned, unknown or not applicable.'
It would be used in the absence of any value. We can perform arithmetic operations on it.
On the other hand, zero is a number, and a blank space is treated as a character.
❏ In SQL, zero or blank space can be compared with another zero or blank space.
whereas one null may not be equal to another null.
null means data might not be provided or there is no data.

34. What is CTE?


Ans: Common Table Expressions (CTE) is a temporary named result set that you can reference within a
SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE a view, as part
of the view’s SELECT query. In addition, you can add a CTE to the new MERGE statement.

35. What is Trigger?


Ans: A trigger is a special type of stored procedure that automatically runs when an event occurs in the
database server.

36. Which Function Is Used To Return Remainder In A Division Operator In SQL?


⦁ The MOD function returns the remainder in a division operation.
⦁ Example: SELECT MOD(27,5) AS “Value”;

37. What Is The Difference Between NOW() And CURRENT_DATE()?


1. NOW() Command will fetch the current date and time both in format ‘YYYY-MM-DD HH:MM:SS’
SELECT NOW();
2. CURRENT_DATE() Command will fetch the date of the current day in format ‘YYYY-MM-DD’.
SELECT CURRENT_DATE();
38. What is windows function?
⦁ It is defined “over” a group of rows (a window) from a query.
⦁ window functions work on a group of rows and return a total value for each row.
⦁ Window functions do not give a result to be combined into a single row.
⦁ Window functions are used to perform a calculation on aggregate value based on a set of rows and
return multiple rows for each group.
⦁ Window Functions Types :
1. Aggregate Window Functions: These functions operated on multiple rows
such functions are SUM(), MAX(), MIN(), AVG(), COUNT(), etc.
2. Ranking Window Functions: These functions ranks each row of a partition in a table.
such functions are RANK(), DENSE_RANK(), ROW_NUMBER(), etc.
3. Value Window Functions: These functions are locally represented by a power series.
such functions are LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE(), etc.

39. What are Aggregate functions?


Aggregate functions are often used with the GROUP BY and HAVING clauses of the SELECT
statement.
1. AVG() - Calculates the mean of a collection of values.
2. COUNT() - Counts the total number of records in a specific table or view.
3. MIN() - Calculates the minimum of a collection of values.
4. MAX() - Calculates the maximum of a collection of values.
5. SUM() - Calculates the sum of a collection of values.
6. FIRST() - Fetches the first element in a collection of values.
7. LAST() - Fetches the last element in a collection of values.
⦁ Note: All aggregate functions described above ignore NULL values except for the COUNT function.

40. What is the Diffrance between Aggregate function and windows function?
Aggregate Functions Window Functions

Aggregate function operates on a set of Windows function operate on set of rows


values to return a single scalar value. called windows frame. They return a single
value for each row.
It used groupBy to define set of rows It used aggregate function but they use
over () to define set of rows
Collapse rows based on the defined Do not collapse rows.
groups.
groups rows based on the same column groups rows by column value and also by
value. row’s rank, percentile, etc.
Operates on a fixed group of values Operates on a fixed or a sliding window
frame.

41. What Are Scalar Functions?


⦁ Scalar functions are the built-in functions in SQL, and whatever be the input provided to the scalar
functions, the output returned by these functions will always be a single value.
⦁ widely used SQL scalar functions:
1. LENGTH() - Calculates the total length of the given field (column).
SELECT name, LENGTH(name) FROM Department;
2. UCASE() - Converts a collection of string values to uppercase characters.
SELECT UCASE(name) FROM Department;
3. LCASE() - Converts a collection of string values to lowercase characters.
SELECT LCASE(name) FROM Department;
4. MID() - Extracts substrings from a collection of string values in a table.
SELECT MID(name,2,4) FROM Department;
5. ROUND() - Calculates the round-off integer value for a numeric field (ordecimal point values).
SELECT Round(26.837352835283528,4) as Value;
6. NOW() - Returns the current date & time.
SELECT NOW() AS Today;
7. CONCAT() - Concatenates two or more strings.
SELECT CONCAT(id, name, location) FROM Department;
8. RAND() - Generates a random collection of numbers of a given length.
9. FORMAT() - Sets the format to display a collection of values

42. What Are The Difference Between OLAP And OLTP ?

OLAP : Online Analytical Processing


⦁ OLAP is software for performing multidimensional analysis at high speeds on large volumes of data from a data
warehouse, data mart, or some other unified, centralized data store.
⦁ Used for Data Mining, Analytics, Decisions making, etc.

OLTP : Online transaction processing.


⦁ transaction-oriented applications .
⦁ the day-to-day transactions of an organization.
⦁ ATM center is an OLTP application.
⦁ It’s also used for Online banking, Online airline ticket booking, sending a text message,etc.

OLAP (ONLINE ANALYTICAL PROCESSING) OLTP (ONLINE TRANSACTION PROCESSING)


Large amount of data is stored typically in Small amount of data is stored typically in
TB, PB MB, GB
Any Datawarehouse system is an OLAP OLTP system is ATM center.
system.
Complex queries involving aggregations. Queries in this process are standardized
and simple.
Designed for analysis of business measures Designed for real time business operations.
by category and attributes.
Drawbacks: Drawbacks:
Implementation and maintenance are If OLTP system faces hardware failures,
dependent on IT professional because the then online transactions get severely
traditional OLAP tools require a affected.
complicated modeling procedure.
Only read and rarely write. Allow read/write operations.
It Consists of historical data from various It Consists only operational current data.
Databases

43. What Are The ACID Properties In A Database?


❏ The ACID properties are means for the transaction that goes through a different group
of tasks A transaction is a single logical order of data.

1. Atomicity:
⦁ It ensures that all statements or operations within the transaction unit must be executed
successfully.
⦁ Its main features are COMMIT, ROLLBACK, and AUTO-COMMIT.
2. Consistency:
⦁ This property ensures that the data must meet all validation rules.
⦁ In simple words, we can say that the database changes state only when a transaction will be committed
successfully.
⦁ It also protects data from crashes.
3. Isolation:
⦁ This property guarantees that the concurrent property of execution in the transaction unit must be
operated independently.
⦁ It also ensures that statements are transparent to each other.
⦁ The main goal of providing isolation is to control concurrency in a database.
4. Durability:
⦁ This property guarantees that once a transaction has been committed, it persists permanently
even if the system crashes, power loss, or failed.

44. What is Normalization and Demoralization?


1. Normalization
⦁ It is process of minimizing redundancy and dependency.
1. Remove Insertion anomaly : repetitation data is their. they are removed .
2. Remove Updation anomaly.
3. Remove deletion anomaly.
⦁ (anomaly : something that is not according to standard or normal)
⦁ normalization divided the larger table into somller tables and links them using relationship.
⦁ The main aim of Normalization is to add, delete or modify field that can be made in a single table.
⦁ Some of the advantages are:
1. Reduction of redundant and duplicate data
2. Quickly find the information
3. More Tables with smaller rows
4. Better Database organization
2. Demoralization :
⦁ Denormalization is the inverse process of normalization.
⦁ Denormalization is a technique used to access the data from higher to lower normal forms of database.
⦁ The performance is improved by using redundancy and keeping the redundant data consistent.
⦁ It is an optimization strategy that takes place after the normalization process.
It adds redundant terms into the tables to avoid complex joins and many other complex operations.

⦁ Different normalization forms are:


1. First Normal Form (1NF) :
⦁ column cannot hold multiple values.
⦁ Each record needs to be unique.
⦁ It should be hold atomic values. (Atomic value means cannot be divided)
2. Second Normal Form (2NF) :
⦁ It should be in 1st normal form.
⦁ All non key attributes are fullly functional dependent on primary key.
⦁ In simple worlds should not have partial dependacy.
⦁ Non key attribute.
composite primary key.
3. Third Normal Form (3NF):
⦁ It is Second Normal Form.
⦁ There is no transitive functional dependancy.

45. SCD type 0,1,2,3 using set operators and Joins?


When organising a Data Warehouse into Kimball-style star schemas, you relate fact records to a
specific dimension record with its related attributes. But what if the information in the dimension
changes.
It is this decision that determines whether to make your dimension a slowly changing one.
There are several different types of SCD depending on how you treat incoming change.
SCD Type 0 – Fixed Dimension: No changes allowed, dimension never change
Type 1 – No History: Update record directly, there is no record of historical values, only current state
Type 2 – Row Versioning: Track changes as version records with current flag & active dates and
other metadata
Type 3 – Previous Value column: Track change to a specific attribute, add a column to show the
previous value, which is updated as further changes occur.

SQL ( QUERY )

Q.1 Write a query to calculate 6th and Nth highest salary using SQL?
or find maximum salary ?
i. using windows function like rownumber to find 6th nad nth of salary :

select * from (
select salary , rownum r
from ( select distinct salary
from employee
order by salary desc))
where r = 6;

[ # r = 6 th , 7 th , 8th etc. they show result ]

ii. using rank and dense_rank windows function :

select * from (
select employee_id,First_name,salary,
rank() over(order by salary desc )r1, >>> when duplicate record then
not used
dense_rank() over(order by salary desc )r2 >>> when duplicate record
then used it.
from employee)
where r2 = 6;

# without using windows and analaytical function :

3.using Co-related query :

select * from employee a


where 6 = (select count (distinct salary) from employee b where b.salary >= a.salary);

4. using row limting clause : is availabe for only oracle version 12.1

select distinct salary


from employee
order by salary desc
offset(n-1)row fetch first 1 row only;

# [note : (n-1) --> n = 1 then show 1st higest , n = 2 then show 2nd highest , n =
3 ... ]

Q.2. find maximum salary of employee ?


Q.3. write a sql query to find last three rows or record ?
input = A B C X Y M L K and output : M L K
1.using ronum : [ here input is column_name and table_A is table_name , <=3 less than]

select input from ( select input from table_A order by rownum desc)
where rownum <=3;

2.using row_number (analytical function ) : [ r = row_number ]

select input,r
from (
select input,row_number() over(order by rownum desc) r
from table_A)
where rownum <=3;

3.using row limiting class methode :

select input
from table_A
offset (select count(*) from table_A )-3 rows
fetch next 3 rows only ;

4.using co- related subqurey (rovid function) :

select input from table_A a


where 3 >(select count(*) from table_A b where a.rowid < b.rowid );

Q.4. Write a query to find First, last and middle record in a table?
First Record From table
SELECT TOP 1 FROM Employee;
SELECT * FROM Employee
WHERE Emp_ID = (SELECT MIN(Emp_ID) FROM Employee);
Last record From Table
SELECT * FROM Employee
WHERE Emp_ID = (SELECT MAX(Emp_ID) FROM Employee);
Middle record From Table
SELECT * FROM Employee
WHERE Emp_ID = ROUND ((SELECT MAX(Emp_ID) FROM Employee)/2);

Q.5. select level from dual connect by <=5


so output = 1 2 3 4 5 but result expected is 120 i.e. multification of records.
select xmlquery (listagg(level,' * ')returning content)
from dual
connect by level <=5;

Q.6.how check datatype current table


DESCRIBE student ;

Q.7.How to Find the Name of a Constraint in Oracle and drop constrain ?


select CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME
from USER_CONSTRAINTS
where TABLE_NAME='STUDENT';

SYS_C007376 R >>>> foreign key


SYS_C007374 p >>>> primary key
SYS_C007375 U >>>> uniqueness constraint
SYS_C007372 C >>>> constraint check

ALTER TABLE STUDENT


DROP CONSTRAINT SYS_C007511;

ALTER TABLE table_name


DISABLE CONSTRAINT constraint_name;

ALTER TABLE table_name


ENABLE CONSTRAINT constraint_name;

Q.8. Write a query to find Duplicate and delete duplicate records?


Finding duplicate rows To return just the Finding duplicate records using
using the aggregate duplicate rows whose analytic function
function COUNT(*) is greater than
one using having clause.
SELECT SELECT SELECT f.*,
fruit_name, fruit_name, COUNT(*) OVER (PARTITION
color, color, BY fruit_name, color) c
COUNT(*) COUNT(*) FROM fruits f;
FROM FROM
fruits fruits
GROUP BY GROUP BY
fruit_name, fruit_name,
color; color
HAVING COUNT(*) > 1;

using with clause : use an inline view: using max function


WITH fruit_counts AS ( SELECT * FROM SELECT
SELECT f.*, (SELECT f.*, MAX(fruit_id)
COUNT(*) OVER COUNT(*) OVER FROM
( PARTITION BY (PARTITION BY fruits
fruit_name, color ) c fruit_name, color) c GROUP BY
FROM fruits f ) FROM fruits f) fruit_name,
SELECT * WHERE c > 1; color
FROM fruit_counts ORDER BY
WHERE c > 1 ; MAX(fruit_id);

# delete duplicate records :


Using MAX function Using Min function Using Rovid function
DELETE FROM DELETE FROM DELETE
fruits fruits FROM
WHERE WHERE fruits
fruit_id NOT IN fruit_id NOT IN WHERE
( SELECT (SELECT rowid NOT IN
MAX(fruit_id) MAX(fruit_id) ( SELECT
FROM FROM MIN(rowid)
fruits fruits FROM
GROUP BY GROUP BY fruits
fruit_name, fruit_name, GROUP BY
color ); color); fruit_id,
fruit_name,
color );

Q.9.Write a query to calculate the even and odd records from a table?
For Even
SELECT * FROM Employee
WHERE MOD(Emp_ID,2) = 0;
For Odd
SELECT * FROM Employee
WHERE MOD(Emp_ID,2) = 1;

Q.10 How do you copy all the rows of a table using SQL query?
CREATE TABLE Emp_Detail AS SELECT * FROM Employee

Q.11 How do you copy schema of a table or create empty table from existing table?
CREATE TABLE Emp_Detail AS
SELECT * FROM Employee
WHERE 3 = 4;

Q.12 Write a query to retrieve the list of employees working in the same department?
SELECT DISTINCT E. Emp_ID, E. Emp_name, E. Department
FROM Employee E, Employee E1
WHERE E. Department = E1. Department
AND E. Emp_ID <> E1. Emp_ID;

Q.13 Write a query to retrieve first four character of Employee name from Employee Table?
SELECT SUBSTRING(E_name,1,4) FROM Employee;

Q.14 Write a query to find number of Employees Whose DOB is between 01/06/1995 to 30/06/1998
and are grouped according to gender?
SELECT COUNT (*), Gender
FROM Employee WHERE DOB BETWEEN ‘1995/06/01’ AND ‘1998/06/30’
GROUP BY gender;

Q.15 Write a query to fetch all records from Employee table order by department in Ascending order
and salary in the descending order?
SELECT * FROM Employee
ORDER BY Department ASC, salary DESC;

Q.16 Write a query to fetch details of all Employees excluding the employees who are ‘HR’ & ‘ADMIN’
SELECT * FROM Employee
WHERE Department
NOT IN (‘HR’,’ADMIN’);

Q.17 Write a query to fetch 50% records from the Employee table?
When ID is in Proper Sequence i.e no record deleted

SELECT * FROM Employee


WHERE Emp_ID < = (SELECT COUNT(Emp_ID)/2 FROM employee);

When ID is not in Proper sequence i.e record deleted

SET @COUNT = (SELECT COUNT(Emp_ID)/2 FROM employee);


PREPARE STMT FROM ‘SELECT * FROM Employee LIMIT?’;
EXECUTE STMT USING @COUNT;

Q.18 Write a query to display total salary of each Employee after adding 10% increment in the
salary?
SELECT Emp_id, E_name, salary+(salary/10)
AS Total_salary FROM Employee;

Q.19 Write a query to retrieve two Minimum and Maximum salaries?


SELECT DISTINCT salary (Minimum)
FROM Employee E1
WHERE 2 > = (SELECT COUNT (DISTINCT salary FROM Employee E2 WHERE E1.
Salary > = E2. salary))
ORDER BY E1. Salary;

SELECT DISTINCT salary (Maximum)


FROM Employee E1
WHERE 2 > = (SELECT COUNT (DISTINCT salary FROM Employee E2 WHERE E1.
Salary < = E2. salary))
ORDER BY E1. Salary DESC;

Q.20.Write a query to fetch the Employee name and replace the space with ‘_’ ?
SELECT REPLACE (E_name,’ ‘, ’_’ )
FROM Employee;

Q.21.Write a query to fetch the Employee gender and replace the ‘M’ with ‘Male’?
SELECT *, REPLACE (gender,’M‘,’Male’)
FROM Employee;

Q.22. Write a query to fetch details of Employees whose EmpLname ends with an alphabet ‘A’ and
contains five alphabets?
SELECT * FROM Employee
WHERE EmpLname LIKE ‘____a’;

You might also like