Documente Academic
Documente Profesional
Documente Cultură
unique number in the database that is updated every time in a row that contains
timestamp
timestamp is inserted or updated.
Managing Tables
Create Table
Table can be created using the CREATE TABLE statement. The syntax is as follows:
( col_name1 datatype,
col_name2 datatype,
col_name3 datatype,
);
Example: Create a table named EmployeeLeave in Human Resource schema with the following attributes:
LeaveReason varchar(100),
LeaveType char(2) NOT NULL );
Constraints in SQL
Constraints define rules that must be followed to maintain consistency and correctness of data. A constraint can be
created by using either of the following statements:
Types of Constraints:
expression:
1. Adding column
2. Altering data type
3. Adding or removing constraints
ADD column_name;
Renaming a Table
A table can be renamed whenever required using RENAME TABLE statement:
RENAME TABLE old_table_name TO new_table_name;
The contents of the table can be deleted when no longer required without deleting the table itself using TRUNCATE
TABLE statement:
Manipulating Data
Storing Data in a Table
Syntax:
VALUES (‘101’,’John’,’Ray’,’78’);
VALUES (101,’John’,’Ray’,78),
(102,‘Steve’,’Jobs’,89),
(103,‘Ben’,’Matt’,77),
(104,‘Ron’,’Neil’,65),
(105,‘Andy’,’Clifton’,65),
(106,‘Park’,’Jin’,90);
WHERE [condition]
SELECT table_name
WHERE condition
SELECT table_name
SET Marks = 85
WHERE condition
DELETE table_name
Retrieving Attributes
One or more column can be displayed while retrieving data from the table.
One may want to view all the details of the Employee table or might want to view few columns.
Required data can be retrieved data from the database tables by using the SELECT statement.
The syntax of SELECT statement is:
[INTO [new_table_name]]
SELECT *
FROM Student
WHERE StudentID = 104;
Comparison Operators
Comparison operators test for the similarity between two expressions.
Syntax:
SELECT column_list
FROM table_name
SELECT StudentID,Marks
FROM Student
SELECT StudentID,Marks
FROM Student
SELECT StudentID,Marks
FROM Student
SELECT StudentID,Marks
FROM Student
Logical Operators
Logical operators are used to SELECT statement to retrieve records based on one or more conditions. More than one
logical operator can be combined to apply multiple search conditions.
Syntax:
SELECT column_list
FROM table_name
conditional_expression2
Types of Logical Operators:
OR Operator
SELECT StudentID,Marks,
FROM Student
AND Operator
SELECT StudentID,Marks,
FROM Student
NOT Operator
SELECT StudentID,Marks,
FROM Student
Range Operator
Range operator retrieves data based on range.
Syntax:
FROM table_name
SELECT StudentID,Marks
FROM Student
NOT BETWEEN
SELECT FirstName,Marks,
FROM Student
WHERE Marks NOT BETWEEN 40 AND 50;
SELECT *
FROM Student
SELECT *
FROM Student
Displaying in a Sequence
Use ORDER BY clause to display the data retrieved in a specific order.
FROM Student
FROM table_name
WHERE search_condition
FROM Student
JOINS
Joins are used to retrieve data from more than one table together as a part of a single result set. Two or more tables
can be joined based on a common attribute.
Types of JOINS:
Consider two tables Employees and EmployeeSalary
EmployeeID (PK) FirstName LastName Title
INNER JOIN
An inner join retrieves records from multiple tables by using a comparison operator on a common column.
Syntax:
SELECT column_name1,colomn_name2, …
ON table1.column_name = table2.column_name
Example:
ON e.EmployeeID = es.EmployeeID
OUTER JOIN
An outer join displays the resulting set containing all the rows from one table and the matching rows from another
table.
An outer join displays NULL for the column of the related table where it does not find matching records.
Syntax:
SELECT column_name1,colomn_name2, …
ON e.EmployeeID = es.EmployeeID
RIGHT OUTER JOIN: In right outer join all rows from the table on the right side of the RIGHT OUTER JOIN keyword
are returned, and the matching rows from the table specified on the left side are returned is the result set.
Example:
ON e.EmployeeID = es.EmployeeID
FULL OUTER JOIN: It is a combination of left outer join and right outer join. This outer join returns all the matching
and non-matching rows from both tables. Whilst, the matching records are displayed only once.
Example:
ON e.EmployeeID = es.EmployeeID
CROSS JOIN
Also known as the Cartesian Product between two tables joins each row from one table with each row of another
table. The rows in the result set is the count of rows in the first table times the count of rows in the second table.
Syntax:
EQUI JOIN
An Equi join is the same as inner join and joins tables with the help of foreign key except this join is used to display all
columns from both tables.
SELF JOIN
In self join, a table is joined with itself. As a result, one row is in a table correlates with other rows in the same table.
In this join, a table name is mentioned twice in the query. Hence, to differentiate the two instances of a single table,
the table is given two aliases. Syntax:
WHERE condition
Subqueries
An SQL statement that is used inside another SQL statement is termed as a subquery.
They are nested inside WHERE or HAVING clause of SELECT, INSERT, UPDATE and DELETE statements.
Using IN Keyword
If a subquery returns more than one value, we might execute the outer query if the values within the columns
specified in the condition match any value in the result set of the subquery.
Syntax:
FROM table_name
(SELECT column
FROM table_name
WHERE EXISTS
FROM table_name
WHERE [condition] ) )
Correlated Subquery
A correlated subquery can be defined as a query that depends on the outer query for its evaluation.
SELECT left
left
(‘RICHARD’ ,4)
SELECT len
len
(‘RICHARD’)
SELECT lower
lower
(‘RICHARD’)
SELECT reverse
reverse
(‘ACTION’)
SELECT right
right
(‘RICHARD’ ,4)
SELECT upper
upper
(‘RICHARD’)
dateadd (date part, number, date) Adds the number of date parts to the date.
datediff (date part, date1, date2) Calculates the number of date parts between two dates.
Datename (date part, date) Returns date part from the listed as a character value.
datepart (date part, date) Returns date part from the listed as an integer.
Function
Parameters Description
Name
row_number Function: This function returns the sequential numbers, starting at 1, for the rows in a result set
based on a column.
rank Function: This function returns the rank of each row in a result set based on specified criteria.
dense_rank Function: The dense_rank() function is used where consecutive ranking values need to be given
based on specified criteria.
These functions use the OVER clause that determines the ascending or descending sequence in which rows are
assigned a rank.
FROM table_name
avg returns the average of values in a numeric expression, either all or distinct.
GROUPING DATA
Grouping data means to view data that match a specific criteria to be displayed together in the result set.
Data can be grouped by using GROUP BY, COMPUTE,COMPUTE BY and PIVOT clause in the SELECT statement.
GROUP BY Clause
Summarizes the result set into groups as defined in the query by using aggregate functions.
Syntax:
SELECT column_list
FROM table_name
WHERE condition
[HAVING search_condition]
SELECT column_list
FROM table_name
ORDER BY column_name
[BY column_name]
PIVOT Clause
The PIVOT operator is used to transform a set of columns into values, PIVOT rotates a table-valued expression by
turning the unique values from one column in the expression into multiple columns in the output.
Syntax:
SELECT *
FROM table_name
FOR pivot_column
IN (column_list)
) table_alias
Sequential Query Language or SQL is the most widely used programming language for
managing data in a relational database management system. It is also used for stream
processing in a relational data stream management system.
Oracle Database, MySQL, Microsoft SQL Server, PostgreSQL, and MariaDB are some
of the most popular relational database management systems.
SQL commands are used for communicating with the database. Everything ranging
from creating a table and adding data to modifying a table and setting user permissions
is accomplished using SQL commands.
SQL Commands
So, learning SQL commands is the first step towards learning SQL. There are a total of
5 types of SQL commands, as described below:
ALTER
Used for altering the structure of a database. Typically, the ALTER command is used
either to add a new attribute or modify the characteristics of some existing attribute.
For adding new columns to the table:
General Syntax
ALTER TABLE table_name ADD (column_name1 data_type (size), column_name2 data_type
(size),….., column_nameN data_type (size));
Example
Example:
The ALTER command can also be used for dropping a column from the table:
General Syntax:
Example:
</pre.
o Change the name of a column
o Change the name of a table
o Decrease the size of a column
CREATE
Used for creating a new table in the database. General Syntax:
Example:
DROP
Used for deleting an entire table from the database and all the data stored in it.
General Syntax:
Example:
RENAME
Used for renaming a table.
General Syntax:
Example:
TRUNCATE
Used for deleting all rows from a table and free the space containing the table.
General Syntax:
TRUNCATE TABLE table_name;
Example:
DELETE
Used for removing one or more rows from a table.
General Syntax:
DELETE FROM table_name; (deletes all rows from a table)
DELETE FROM table_name WHERE some_condition; (delete only the row(s) where
the condition is true)
Example:
INSERT
Used for inserting data into the row of a table.
General Syntax:
OR
Example:
INSERT INTO Student (Name, Age) VALUES (“Vijay”, “25”);
Insert command can also be used for inserting data into a table from another table.
General Syntax:
Example:
UPDATE
Used to modify or update the value of a column in a table. It can update all rows or
some selective rows in the table.
General Syntax:
Example:
UPDATE Student SET Name = “Akhil” WHERE Id = 22;
ALTER
DELETE
INDEX
INSERT
SELECT
UPDATE
GRANT
Used for granting user access privileges to a database.
General Syntax:
Example:
This will allow the user to run only SELECT and UPDATE operations on the Student
table.
Allows the user to run all commands on the table as well as grant access privileges to
other users.
REVOKE
Used for taking back permission given to a user.
General Syntax:
Example:
Note: - A user who is not the owner of a table but has been given the privilege to grant
permissions to other users can also revoke permissions.
COMMIT
Used for saving all transactions made to a database. Ends the current transaction and
makes all changes permanent that were made during the transaction. Releases all
transaction locks acquired on tables.
General Syntax:
COMMIT;
Example:
COMMIT;
ROLLBACK
Used to undo transactions that aren’t yet saved in the database. Ends the transaction
and undoes all changes made during the transaction. Releases all transaction locks
acquired on tables.
General Syntax:
ROLLBACK;
Example:
ROLLBACK;
SAVEPOINT
Used for rolling back to a certain state known as the savepoint. Savepoints need to be
created first so that they can be used for rollbacking transactions partially.
General Syntax:
SAVEPOINT savepoint_name;
Note: - An active savepoint is one that has been specified since the last COMMIT or
ROLLBACK command.
SELECT expressions
FROM table_name
Example:
Suppose we have a relational table called Student that has all the information regarding
a student, such as name, roll no., stream, age, address, etc. and we need to fetch data
regarding all student names who are less than 18 years of age, then we can use the
SELECT command as follows:
SELECT student_name
FROM student
The result will be a list of all the student names who are less than 18 years of age.
The SELECT command can also be used for eliminating duplicates from a table.
General Syntax:
Example:
Example:
Conclusion
Acquiring knowledge of commonly used commands is the first step to be able to
understand and work with SQL databases. Mastering SQL commands demands a good
amount of practice and we hope this article will help you get started on your journey!
Inner Join
Rows are returned when there is at least one match of rows between the tables.
Right Join
Right, join returns all rows from the right table and those which are shared between the tables. If there are no
matching rows in the left table, it will still return all the rows from the right table.
Left Join
Left join returns all rows from the Left table and those which are shared between the tables. If there are no matching
rows in the right table, it will still return all the rows from the left table.
Full Join
Full join return rows when there are matching rows in any one of the tables. This means it returns all the rows from
the left-hand side table and all the rows from the right-hand side table.
Question: What is the difference between CHAR and VARCHAR2 datatype in SQL?
Answer: CHAR is used to store fixed-length character strings, and VARCHAR2 is used to store variable-length
character strings.
For example, suppose you store the string ‘Database’ in a CHAR(20) field and a VARCHAR2(20) field.
The CHAR field will use 22 bytes (2 bytes for leading length).
The VARCHAR2 field will use 10 bytes only (8 for the string, 2 bytes for leading length).
Atomicity: This means the transaction must happen fully and cannot be left midway.
Consistency: To maintain integrity constraints hence valid data enters the database
Isolation: Controls Concurrency
Durability: Once a transaction is committed it remains committed
SQL> SAVEPOINT A
SQL> INSERT INTO TEST VALUES (1,'Savepoint A');
1 row inserted.
SQL> SAVEPOINT B
SQL> INSERT INTO TEST VALUES (2,'Savepoint B');
1 row inserted.
SQL> ROLLBACK TO B;
Rollback complete.
SQL> SELECT * FROM TEST;
ID MSG
-------- -----------
1 Savepoint A
Question: State one situation where the set-based solution is advantageous over the cursor-
based solution
Answer: Set-based solutions provide better performance as they work on a result set and not on one row at a time.
They are concise and more readable.
Question: What is normalization and what are the normal forms
Answer: Normalization is a process in database design to minimize data redundancy and dependency. The
database is divided into two or more tables, and relationships are defined between them.
First Normal Form: Every record is unique in a table and is identified by a primary or a composite key
In the above table the field ‘phonenum’ is a multi-valued attribute, so it is not in 1NF.
Below Table is in 1NF as there is no multi-valued attribute
------------------
1 John 9176612345
1 John 9176645698
2 Susie 9176645789
3 Jim 9176696325
Second Normal Form: The table must be in First Normal Form, and it should have a single column as its
primary key.
2NF tries to reduce the redundant data getting stored in memory. To bring the above table in 2NF we split
the table into two tables
Third Normal Form: The table must be in Second Normal Form and must have no transitive functional
dependencies. I.e., a non-key column must not be dependent on another non-key column within the same
table.'
Consider the EMPLOYEE_DETAIL table: This table is not in the third normal form because the fields emp_state
and emp_city depend on emp_zip and not on the primary key emp_id.
The above table is split into 2 tables and now the tables are in the third normal form.
EMPLOYEE table:
EMPLOYEE_ZIP table:
201010 CT Monroe
02228 TX Dallas
060007 IL Chicago
The primary key is a field in the table which uniquely identifies a row. It cannot be NULL
A foreign key is a field in one table, which is a primary key in another table. A relationship is created
between the two tables by referencing the foreign key of one table with the primary key of another table.
In the example below, the employee_id_ref in the salary table is the foreign key.
Unique Key uniquely identifies a record in a table. There can be many unique key constraints defined on a
table.
#BBD0E0 »
In the table above Emp_id is the primary key however Government_id is the unique key. You may want the
Government_id to be unique for every employee. Since the data belongs to the government, you may not want it to
be the primary key.
The above script creates a clustered index named “IX_tblStudent_Gender_Score” on the student table. This index is
created on the “gender” and “total_score” columns. An index that is created on more than one column is called the
“composite index”.
A non-clustered index doesn’t sort the physical data inside the table. A non-clustered index is stored in one place,
and table data is stored in another place. This allows for more than one non-clustered index per table.
The above script creates a non-clustered index on the “name” column of the student table — the index sorts by name
in ascending order. The table data and index will be stored in different places.
Question: How do you maintain database integrity where deletions from one table will
automatically cause deletions in another table?
Answer: ON DELETE CASCADE is a command that is used when deletions happen in the parent table, and all child
records are automatically deleted, and the child table is referenced by the foreign key in the parent table.
BEGIN TRANSACTION;
DELETE FROM HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION;
SELECT
employee_id, first_name, last_name
FROM
employees
WHERE
department_id IN (SELECT
department_id
FROM
departments
WHERE
location_id = 1700)
ORDER BY first_name , last_name;
The query placed within the parentheses is called a subquery. It is also known as an inner query or inner select. The
query that contains the subquery is called an outer query or an outer select.
AS BEGIN
Exec Procedure2
END
Question: Does the data stored in the stored procedure increase access time or execution
time? Explain
Answer: Data stored in stored procedures can be retrieved much faster than the data stored in the SQL database.
Data can be precompiled and stored in stored procedures. This reduces the time gap between query and compiling
as the data has been pre-compiled and stored in the procedure.
1. DDL(Data Definition Language): Includes SQL commands like CREATE, ALTER, and DELETE.
2. DML(Data Manipulation Language): Accesses and manipulates data Uses INSERT, UPDATE commands
3. DCL(Data Control Language): Controls access to the database. Uses commands like GRANT and
REVOKE.
Table: Employee_Details
Fields: Emp_id, Emp_name, Emp_dept, Emp_salary
1. NOT NULL
2. CHECK
3. DEFAULT
4. UNIQUE
5. PRIMARY KEY
6. FOREIGN KEY
Question: What is data integrity?
Answer: Data integrity defines the accuracy, consistency, and reliability of data that is stored in the database.
There are four kinds of data integrity:
1. Row integrity
2. Column integrity
3. Referential integrity
4. User-defined integrity
Entity: A person, place, or any real-world thing that can be represented as a table is called an entity.
Example: Employee table represents the details of an employee in an organization.
Relationship: Relationship defines the dependency that entities share amongst each other. Example:
Employee name, id, salary might belong to the same or different tables.
SELECT CURDATE();
Question: What is the TRUNCATE command? How is it different from the DELETE command?
Answer:
DELETE TRUNCATE
Deletes a row from the table. Deletes all rows from the table.
Question: What is the difference between null, zero and blank space?
Answer: NULL refers to a value that is unknown, not available, unapplicable or unassigned. While zero is a number
and blank space is treated as a character.
Question: Which function is used to return the remainder in a division operator in SQL?
Answer: The MOD function returns the remainder in the division operation.
1. Arithmetic
2. Comparison
3. Logical
Scalar functions
Inline Table-valued functions
Multi statement valued functions
S and E are alias names for student table and exam table respectively.
1. Case
2. Kana
3. Width
4. Accent
Conclusion
Structured Query Language or SQL is used to manage and manipulate data in a database. With the help of the
above-mentioned Best SQL Interview Questions, one can attempt an interview for Database Administrator, SQL
developer and even crack SQL certifications.
PL (Procedural language) is an extension to SQL (Structured Query Language) where a developer can write complex
database interactions using procedures, control structures like branching and iteration, modules and functions. It has
tight integration with SQL and supports both dynamic and static SQL.
Amongst other questions during an interview, it is also important to know how SQL and PL/SQL are different. Some
benefits of PL/SQL over SQL are:
Supports procedural processing, conditional statements, looping and other features similar to high-level
languages.
Multiple statements can be sent to the database server at once in the form of a procedure, hence saving
time and network traffic.
Customized error handling is possible.
Fully portable.
Apart from the above benefits, PL/SQL has some more attractive features like functions, procedures, triggers, cursors
that make it one of the most versatile relational databases.
A bit of background
PL/SQL 1.0 was released in 1992 with Oracle 6 as an optional extension. It was with PL/SQL 2.0 that stored
procedures, functions, user-defined record types, tables, packages and extensions like DBMS_* were introduced.
The latest PL/SQL version is 11.0, which was released with Oracle 11g and came with advanced features such as
native compilation, PL/SQL function result cache, and minute dependency tracking.
SQL PL/SQL
SQL is a query language to interact with the It is an extension of SQL which supports procedures,
database. functions and many more features.
SQL statements can be executed only one The entire block of statements is sent to the database
at a time, thereby making it a time- server at once to be executed, saving time and
consuming process. increasing efficiency.
[DECLARE]
BEGIN
--execution statements
[EXCEPTION]
[before | after]
on [table_name]
[trigger_body]
Pre-defined exceptions – common errors that are already defined. Example – NO_DATA_FOUND
Undefined exceptions – the errors that do not have predefined names.
User-defined exceptions – handled by the code written by the user.
Scalar types – primitive data types like CHAR, DATE, LONG, VARCHAR2 etc…
Composite – these are made up of other data types and can be easily updated. Example, RECORD, TABLE
etc…
Reference data types like CURSOR
Large object types – BLOB, CLOB etc…
Question: What is the difference between %TYPE and %ROWTYPE? Give an example.
Answer:
%TYPE %ROWTYPE
Example – Example –
DECLARE
DECLARE
studentId
stud_rec
students.student_id%TYPE;
students.%ROWTYPE;
Package specifications
Package body
Question: List some schema objects that are created using PL/SQL.
Answer: Database links, triggers, stored procedures, functions and packages, views, synonyms, external procedure
libraries, sequences, etc…
Check here: Basic SQL Commands Checklist
Question: Explain the difference between procedure and function.
Answer:
Function Procedure
Can be called from SQL statements. Can not be called from SQL statements.
The function has to return a value. Need not return any value.
Generally used for computation purpose. Used for executing complex business logic.
Exception handling is not possible Try/catch block can be defined inside a procedure
Question: Explain the difference between procedure and trigger.
Answer:
PROCEDURE TRIGGER
Called explicitly by a user, trigger or an Executed by the DBMS whenever an event occurs in
application the database.
Implicit cursor – PL/SQL applies implicit cursors for INSERT, UPDATE, DELETE and SELECT statements
returning a single row.
Explicit cursor – created by a programmer for queries returning more than one row. Syntax–
CURSOR is
SELECT statement;
OPEN ;
FETCH INTO ;
CLOSE ;
Not NULL
Unique
Primary key
Foreign key
Check
TRIGGERS CONSTRAINTS
Triggers are fired upon an event; hence they are Constraints are fired as soon as the
fired after constraints
the table is used.
Trigger is for the entire table The constraint is for a column of the table
The variables declared in a procedure header used in the body are called formal parameters. Example –
DECLARE
num1 NUMBER(2);
num2 NUMBER(3);
BEGIN
END;
DBMS_APPLICATION_INFO
DBMS_TRACE
DBMS_SESSION and DBMS_MONITOR
AS
BEGIN
SELECT * FROM customers WHERE age = @age AND city = @city;
END;
SELECT day_of_week,
1, 'Monday',
2, 'Tuesday',
3, 'Wednesday',
4, 'Thursday',
5, 'Friday',
6, 'Saturday',
DBMS
A database is the backbone of any IT system. As a Database Developer, I am sure you would want to prove your
expertise and knowledge in your next job interview and win a role. Here is the list of top 30 DBMS Interview questions
that will help you sail through. In addition, to enhance your skills you could go through SQL Tutorials and Top SQL
Interview Questions as SQL is an integrated and a vital feature in a DBMS (Database Management System).
DDL: The Data Definition Language is used to define the database and schema structure by using a set of
SQL Queries like CREATE, ALTER, TRUNCATE, DROP and RENAME.
DCL: The Data Control Language is used to control the access of the users to the database by using a set
of commands like GRANT and REVOKE in the SQL Query.
DML: The Data Manipulation Language is used for maintaining the data by using SQL queries like SELECT,
INSERT, DELETE and UPDATE.
Question: What are the primitive operations common to all database management systems?
Answer: Addition, deletion, and modification are the most important primitive operations common to all DBMS.