Sunteți pe pagina 1din 57

SQL Cheat Sheet

Background: What is SQL? Why do we need it?


SQL is a database language used to query and manipulate the data in the database.
Main objectives:

 To provide an efficient and convenient environment


 Manage information about users who interact with the DBMS

The SQL statements can be categorized as

Data Definition Language(DDL) Commands:

 CREATE: creates a new database object, such as a table.


 ALTER: used to modify the database object
 DROP: used to delete the objects.

Data Manipulation Language(DML) Commands:

 INSERT: used to insert a new data row record in a table.


 UPDATE: used to modify an existing record in a table.
 DELETE: used delete a record from the table.

Data Control Language(DCL) Commands:

 GRANT: used to assign permission to users to access database objects.


 REVOKE: used to deny permission to users to access database objects.

Data Query Language(DQL) Commands:

 SELECT: it is the DQL command to select data from the database.

Data Transfer Language(DTL) Commands:

 COMMIT: used to save any transaction into the database permanently.


 ROLLBACK: restores the database to the last committed state.

Identifying Data Types


Data types specify the type of data that an object can contain, such as integer data or character data. We need to
specify the data type according to the data to be stored.
Following are some of the essential data types:

Data Type Used to Store

int Integer data

smallint Integer data


tinyint Integer data

bigint Integer data

decimal Numeric data type with a fixed precision and scale.

numeric numeric data type with a fixed precision and scale.

float floating precision data

money monetary data

datetime data and time data

char(n) fixed length character data

varchar(n) variable length character data

text character string

bit integer data with 0 or 1

image variable length binary data to store images

real floating precision number

binary fixed length binary data

cursor cursor reference

sql_variant different data types

unique number in the database that is updated every time in a row that contains
timestamp
timestamp is inserted or updated.

table temporary set of rows returned as a result set of a table-valued function.

xml store and return xml values

Managing Tables
Create Table
Table can be created using the CREATE TABLE statement. The syntax is as follows:

CREATE TABLE table_name

( col_name1 datatype,
col_name2 datatype,

col_name3 datatype,

);

Example: Create a table named EmployeeLeave in Human Resource schema with the following attributes:

Columns Data Type Checks

EmployeeID int NOT NULL

LeaveStartDate date NOT NULL

LeaveEndDate date NOT NULL

LeaveReason varchar(100) NOT NULL

LeaveType char(2) NOT NULL

CREATE TABLE HumanResources.EmployeeLeave

EmployeeID int NOT NULL,

LeaveStartDate datetime NOT NULL,

LeaveEndDate datetime NOT NULL,

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:

CREATE TABLE statement

ALTER TABLE statement

CREATE TABLE table_name

column_name CONSTRAINT constraint_name constraint_type

Types of Constraints:

Constraint Description Syntax

CREATE TABLE table_name

Primary Columns or columns that uniquely identify ( col_name [CONSTRAINT


key all rows in the table. constraint_name PRIMARY KEY]
(col_name(s))
)

CREATE TABLE table_name

Unique Enforces uniqueness on non primary key ( col_name [CONSTRAINT constraint_name


key columns. UNIQUE KEY] (col_name(s))

CREATE TABLE table_name

( col_name [CONSTRAINT constraint_name


Is used to remove the inconsistency in two FOREIGN KEY] (col_name)
Foreign
tables when the data depends on other
key
tables. REFERENCES table_name (col_name)

Enforce domain integrity by restricting the


Check CREATE TABLE table_name
values to be inserted in the column.
( col_name [CONSTRAINT constraint_name]
CHECK (expression) (col_name(s)) )

expression:

IN, LIKE, BETWEEN

3.2 Modifying Tables


Modify table using ALTER TABLE statement when:

1. Adding column
2. Altering data type
3. Adding or removing constraints

Syntax of ALTER TABLE:

ALTER TABLE table_name

ADD column_name;

ALTER TABLE table_name

DROP COLUMN column_name;

ALTER TABLE table_name

ALTER COLUMN column_name data_type;

Renaming a Table
A table can be renamed whenever required using RENAME TABLE statement:
RENAME TABLE old_table_name TO new_table_name;

Dropping a Table versus Truncate Table


A table can be dropped or deleted when no longer required using DROP TABLE statement:

DROP TABLE table_name;

The contents of the table can be deleted when no longer required without deleting the table itself using TRUNCATE
TABLE statement:

TRUNCATE TABLE table_name;

Manipulating Data
Storing Data in a Table
Syntax:

INSERT INTO table_name (col_name1, col_name2, col_name3…)

VALUES (value1, value2, value3…);


Example: Inserting data into Student table.

INSERT INTO Student (StudentID, FirstName,LastName,Marks)

VALUES (‘101’,’John’,’Ray’,’78’);

Example: Inserting multiple data into Student table.

INSERT INTO Student

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

Copying Data from one table to another:

INSERT INTO table_name2

SELECT * FROM table_name1

WHERE [condition]

Updating Data in a Table


Data can be updated in the table using UPDATE DML statement:

SELECT table_name

SET col_name1 = value1 , col_name2 = value2…

WHERE condition

Example update marks of Andy to 85

SELECT table_name

SET Marks = 85

WHERE FirstName = ‘Andy’

Deleting Data from a Table


A row can be deleted when no longer required using DELETE DML statement.
Syntax:
DELETE FROM table_name

WHERE condition

DELETE FROM Student

WHERE StudentID = ‘103’

Deleting all records from a table:

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:

SELECT [ALL | DISTINCT] select_column_list

[INTO [new_table_name]]

[FROM [table_name | view_name]]

[WHERE search condition]

Consider the following Student table:

StudentID FirstName LastName Marks

101 John Ray 78

102 Steve Jobs 89

103 Ben Matt 77

104 Ron Neil 65

105 Andy Clifton 65

106 Park Jin 90

Retrieving Selected Rows


To retrieve selected rows from a table use WHERE clause in the SELECT statement.

SELECT *

FROM Student
WHERE StudentID = 104;

HAVING Clause is used instead of WHERE for aggregate functions.

Comparison Operators
Comparison operators test for the similarity between two expressions.
Syntax:

SELECT column_list

FROM table_name

WHERE expression1 comparison_operatore expression2

Example of some comparison operators:

SELECT StudentID,Marks

FROM Student

WHERE Marks = 90;

SELECT StudentID,Marks

FROM Student

WHERE StudentID > 101;

SELECT StudentID,Marks

FROM Student

WHERE Marks != 89;

SELECT StudentID,Marks

FROM Student

WHERE Marks >= 50;

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

WHERE conditional_expression1 {AND/OR} [NOT]

conditional_expression2
Types of Logical Operators:
OR Operator

SELECT StudentID,Marks,

FROM Student

WHERE Marks= 40 OR Marks=56 OR Marks = 65;

AND Operator

SELECT StudentID,Marks,

FROM Student

WHERE Marks= 89 AND Marks=56 AND Marks = 65;

NOT Operator

SELECT StudentID,Marks,

FROM Student

WHERE NOT LastName = “Jobs”;

Range Operator
Range operator retrieves data based on range.
Syntax:

SELECT column_name1, col_name2….

FROM table_name

WHERE expression1 range_operator expression2 AND expression3

Types of Range operators:


BETWEEN

SELECT StudentID,Marks

FROM Student

WHERE Marks BETWEEN 40 AND 70;

NOT BETWEEN

SELECT FirstName,Marks,

FROM Student
WHERE Marks NOT BETWEEN 40 AND 50;

Retrieve Records That Match a Pattern


Data from the table can be retrieved that match a specific pattern.
The LIKE keyword matches the given character string with a specific pattern.

SELECT *

FROM Student

WHERE FirstName LIKE ‘Ro%’

SELECT *

FROM Student

WHERE FirstName LIKE ‘_e%’

Displaying in a Sequence
Use ORDER BY clause to display the data retrieved in a specific order.

SELECT StudentID, LastName,

FROM Student

ORDER BY Marks DESC;

Displaying without Duplication


The DISTINCT keyword is used to eliminate rows with duplicate values in a column.
Syntax:

SELECT [ALL | DISTINCT] col_names

FROM table_name

WHERE search_condition

SELECT DISTINCT Marks

FROM Student

WHERE LastName LIKE ‘o%’;

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

1001 Ron Brent Developer

1002 Alex Matt Manager

1003 Ray Maxi Tester

1004 August Berg Quality

EmployeeID (FK) Department Salary

1001 Application 65000

1002 Digital Marketing 75000

1003 Web 45000

1004 Software Tools 68000

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, …

FROM table1 INNER JOIN table2

ON table1.column_name = table2.column_name

Example:

SELECT e.LastName, e.Title, es.salary,

FROM e.Employees INNER JOIN es.EmployeeSalary

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, …

FROM table1 [LEFT|RIGHT|FULL]OUTER JOIN table2


ON table1.column_name = table2.column_name

Types of Outer Join


LEFT OUTER JOIN: In left outer join all rows from the table on the left side of the LEFT OUTER JOIN keyword is
returned, and the matching rows from the table specified on the right side are returned the result set.
Example:

SELECT e.LastName, e.Title, es.salary,

FROM e.Employees LEFT OUTER JOIN es.EmployeeSalary

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:

SELECT e.LastName, e.Title, es.salary,

FROM e.Employees LEFT OUTER JOIN es.EmployeeSalary

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:

SELECT e.LastName, e.Title, es.salary,

FROM e.Employees FULL OUTER JOIN es.EmployeeSalary

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:

SELECT column_name1,colomn_name2,column_name1 + column_name2 AS new_column_name

FROM table1 CROSS JOIN table2

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:

SELECT t1.c1,t1.c2 AS column1,t2.c3,t2.c4 AS column2

FROM table1 t1 JOIN table2 t2

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.

 Outer Query: Query that represents the parent query.


 Inner Query: Query that represents the subquery.

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:

SELECT column, column

FROM table_name

WHERE column [NOT] IN

(SELECT column

FROM table_name [WHERE conditional_expression] )

Using EXISTS Keyword


EXISTS clause is used with subquery to check if a set of records exists.
TRUE value is returned by the subquery in case if the subquery returns any row.
Syntax:

SELECT column, column

FROM table_name

WHERE EXISTS

(SELECT column_name FROM table_name WHERE condition)

Using Nested Subqueries


A subquery can contain more than one subqueries. Subqueries are used when the condition of a query is dependent
on the result of another query, which is, in turn, is dependent on the result of another subquery.
Syntax:
SELECT column, column

FROM table_name

WHERE column_name expression_operator

(SELECT column_list FROM table_name

WHERE column_name expression_operator

(SELECT column_list 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.

Using Functions to Customize ResultSet


Various in-built functions can be used to customize the result set.
Syntax:

SELECT function_name (parameters)

Using String Functions


String values in the result set can be manipulated by using string functions.
They are used with char and varchar data types.
Following are the commonly used string functions are:

Function Name Example

SELECT left
left
(‘RICHARD’ ,4)

SELECT len
len
(‘RICHARD’)

SELECT lower
lower
(‘RICHARD’)

SELECT reverse

reverse

(‘ACTION’)

SELECT right

right

(‘RICHARD’ ,4)

space SELECT ‘RICHARD’ + space(2) + ‘HILL’

str SELECT str (123.45,6,2)

substring SELECT substring (‘Weather’ ,2,2)

SELECT upper
upper
(‘RICHARD’)

Using Date Functions


Date functions are used to manipulate date time values or to parse the date values.
Date parsing includes extracting components, such as day, month, and year from a date value.
Some of the commonly used date functions are:

Function Name Parameters Description

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.

getdate 0 Returns current date and time

day (date) Returns an integer, which represents the day.

month (date) Returns an integer, which represents the month.

year (date) Returns an integer, which represents the year.

Using Mathematical Functions


Numeric values in a result set can be manipulated in using mathematical functions.
The following table lists the mathematical functions:

Function
Parameters Description
Name

abs (numeric_expression) Returns an absolute value

acts,asin,atan (float_expression) Returns an angle in radians

cos, sin, Returns the cosine, sine, cotangent, or tangent of the


(float_expression)
cot,tan angle in radians.

Returns the smallest integer greater than or equal to


degrees (numeric_expression)
specifies value.

exp (float_expression) Returns the exponential value of the specified value.

Returns the largest integer less than or equal to the


floor (numeric_expression)
specified value.

log (float_expression) Returns the natural logarithm of the specified value.

pi 0 Returns the constant value of 3.141592653589793

Returns the value of numeric expression to the value


power (numeric_expression,y)
of y

radians (numeric_expression) Converts from degrees to radians.

rand ([seed]) Returns a random float number between 0 and 1.


Returns a numeric expression rounded off to the
round (numeric_expression,length)
length specified as an integer expression.

sign (numeric_expression) Returns positive, negative or zero.

sqrt (float_expression) Returns the square root of the specified value.

Using Ranking Functions


Ranking functions are used to generate sequential numbers for each row to give a rank based on specific criteria.
Ranking functions return a ranking value for each row. Following functions are used to rank the records:

 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.

Using Aggregate Functions


The aggregate functions, on execution, summarize the values for a column or group of columns and produce a single
value.
Syntax:

SELECT aggrgate_function ([ALL | DISTINCT] expression)

FROM table_name

Following are the aggregate functions:

Function Name Description

avg returns the average of values in a numeric expression, either all or distinct.

count returns the number of values in an expression, either all or distinct.

min returns the lowest value in an expression.

max returns the highest value in an expression.

sum returns the total of values in an 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

[GROUP BY [ALL] expression]

[HAVING search_condition]

COMPUTE and COMPUTE BY Clause


This COMPUTE clause, with the SELECT statement, is used to generate summary rows by using aggregate
functions in the query result.
The COMPUTE BY clause can be used to calculate summary values of the result set on a group of data.
Syntax:

SELECT column_list

FROM table_name

ORDER BY column_name

COMPUTE aggregate_function (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

PIVOT (aggregate function (value_column)

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:

DDL (Data Definition Language)


Data Definition Language or DDL commands are used for changing the structure of a
table. In other words, DDL commands are capable of creating, deleting, and modifying
data.
All DDL commands are auto-committed which means that changes made by them are
automatically saved in the database. Following are the various DDL commands:

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

ALTER TABLE Student ADD (Address varchar2(20));

ALTER TABLE Student ADD (Age number(2), Marks number(3));

For modifying an existing column in the table:


General Syntax:

ALTER TABLE table_name MODIFY (column_name new_data_type(new_size));

Example:

ALTER TABLE Student MODIFY (Name varchar2(20));

The ALTER command can also be used for dropping a column from the table:
General Syntax:

ALTER TABLE table_name DROP COLUMN column_name;

Example:

ALTER TABLE Student DROP COLUMN Age;

</pre.

Note: - It is not possible to do the following using the ALTER command:


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:

CREATE TABLE table_name (column_name1 data_type(size), column_name2


data_type(size),…., column_nameN data_type(size));

Example:

CREATE TABLE Employee(Name varchar2(20), D.O.B. date, Salary number(6);

DROP
Used for deleting an entire table from the database and all the data stored in it.
General Syntax:

DROP TABLE table_name;

Example:

DROP TABLE Student;

RENAME
Used for renaming a table.
General Syntax:

RENAME old_table_name TO new_table_name

Example:

RENAME Student TO Student_Details

TRUNCATE
Used for deleting all rows from a table and free the space containing the table.
General Syntax:
TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE Student;

DML (Data Manipulation Language)


The DML or Data Manipulation Language commands help in modifying a relational
database. These commands are not auto-committed, which simply means that all
changes made to the database using DML commands aren’t automatically saved.
It is possible to rollback DML commands. Various DML commands are:

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:

DELETE FROM Student;

DELETE FROM Student WHERE Name = “Akhil”;

INSERT
Used for inserting data into the row of a table.
General Syntax:

INSERT INTO table_name (column_name1, column_name2,….,column_nameN) VALUES (value1,


value2,….,valueN);

OR

INSERT INTO table_name VALUES (value1, value2,….,valueN);

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:

INSERT INTO table_name1 SELECT column_name1, column_name2,….,column_nameN FROM


table_name2;

Example:

INSERT INTO Student SELECT Id, Stream FROM Student_Subject_Details

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:

UPDATE table_name SET column_name1 = value1, column_name2 = value2,….,column_nameN =


valueN (for updating all rows)

UPDATE table_name SET column_name1 = value1, column_name2 = value2,….,column_nameN =


valueN [WHERE CONDITION] (for updating particular rows)

Example:
UPDATE Student SET Name = “Akhil” WHERE Id = 22;

DCL (Data Control Language)


In order to protect the information in a table from unauthorized access, DCL commands
are used. A DCL command can either enable or disable a user from accessing
information from a database. List of user access privileges:

 ALTER
 DELETE
 INDEX
 INSERT
 SELECT
 UPDATE
GRANT
Used for granting user access privileges to a database.
General Syntax:

GRANT object_privileges ON table_name TO user_name1, user_name2,….,user_nameN;

GRANT object_privileges ON table_name TO user_name1, user_name2,….,user_nameN WITH


GRANT OPTION; (allows the grantee to grant user access privileges to others)

Example:

GRANT SELECT, UPDATE ON Student TO Akhil Bhadwal

This will allow the user to run only SELECT and UPDATE operations on the Student
table.

GRANT ALL ON Student TO Akhil Bhadwal WITH GRANT OPTION

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:

REVOKE object_privileges ON table_name FROM user1, user2,… userN;

Example:

REVOKE UPDATE ON Student FROM Akhil;

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.

TCL (Transaction Control Language)


Transaction Control Language commands can only be used with DML commands. As
these operations are auto-committed in the database, they can’t be used while creating
or dropping tables. Various TCL commands are:

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:

DELETE FROM Student WHERE Age = 25;

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:

DELETE FROM Student WHERE Age = 25;

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.

DQL (Data Query Language)


DQL commands are used for fetching data from a relational database. There is only one
command, which is the SELECT command.
Equivalent to the projection operation in relational algebra, SELECT command selects
the attribute based on the condition described by the WHERE clause.
General Syntax:

SELECT expressions

FROM table_name

WHERE condition1, condition2,…., conditionN;

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

WHERE age < 18;

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:

SELECT DISTINCT column_name1, column_name2,…., column_nameN FROM table_name;

Example:

SELECT DISTINCT Name, Age FROM Student;


This command will scan through entire rows and will eliminate rows that are identical.
Rows retrieved using the SELECT command can be sorted in either ascending or
descending order.
General Syntax:

SELECT column_name1, column_name2,…., column_nameN FROM table_name ORDER BY


column_name; (gives results in ascending order)

SELECT column_name1, column_name2,…., column_nameN FROM table_name ORDER BY


column_name DESC; (gives results in descending order)

Example:

SELECT Name, Age FROM Student ORDER BY Name;

SELECT Name, Age FROM Student ORDER BY Name DESC;

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!

SQL Interview Questions


Here we have listed SQL interview questions which are frequently asked by the interviewer.

Question: What is the difference between DBMS and RDBMS?


Answer: DBMSs are software applications that help you build and maintain databases. RDBMS is a subset of
DBMS, and it is a database management system based on the relational model of the DBMS.

Question: Can we embed Pl/SQL in SQL? Justify your answers


Answer: PL/SQL is a procedural language, and it has one or more SQL statements in it. So SQL can be embedded
in a PL/SQL block; however, PL/SQL cannot be embedded in a SQL as SQL executes a single query at a time.

DECLARE /* this is a PL/SQL block */


qty_on_hand NUMBER(5);
BEGIN
SELECT quantity INTO qty_on_hand FROM inventory /* this is the SQL statement embedded in the PL/SQL block
*/
WHERE product = 'TENNIS RACKET';
END;

Question: What do you mean by data manipulation language - DML?


Answer: DML includes most common SQL statements to store, modify, delete, and retrieve data. They are SELECT,
UPDATE, INSERT and DELETE.

INSERT INTO table_name /* Insert is a DML statement */


VALUES (value, value, value …)
INSERT INTO customers /* data being inserted in the table customers */
VALUES (‘George’ , 'Washington' , 'Connecticut')

Question: What is a join in SQL? What are the types of joins?


Answer: A join is used to query data from multiple tables based on the relationship between the fields.
There are four types of joins.

 Inner Join

Rows are returned when there is at least one match of rows between the tables.

select first_name, last_name, order_date, order_amount


from customers c
inner join orders o
on c.customer_id = o.customer_id
/* customers and orders are two tables. Data will be displayed from the two tables where the customer_id from
customer table matches
The customer_id from the orders table. */

 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.

select first_name, last_name, order_date, order_amount


from customers c
left join orders o
on c.customer_id = o.customer_id
/* customers and orders are two tables. All rows from the Orders table is returned with matching rows from
the Customers table if any */

 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.

select first_name, last_name, order_date, order_amount


from customers c
left join orders o
on c.customer_id = o.customer_id
/* customers and orders are two tables. All rows from the customers table is returned with matching rows from
the orders table if any */

 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.

select first_name, last_name, order_date, order_amount


from customers c
full join orders o
on c.customer_id = o.customer_id
/* customers and orders are two tables. All rows from the Orders table and customer table are returned */

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

Question: What is a trigger?


Answer: Triggers are stored programs that get automatically executed when an event such as INSERT, DELETE,
UPDATE(DML) statement occurs. Triggers can also be evoked in response to Data definition statements(DDL) and
database operations, for example, SERVER ERROR, LOGON.

create trigger dbtrigger


on database
for
create_table,alter_table,drop_table
as
print'you can not create ,drop and alter table in this database'
rollback;
create trigger emptrigger
on emp
for
insert,update,delete
as
print'you can not insert,update and delete this table i'
rollback;
Question: What are ACID properties in a transaction
Answer: In order to maintain consistency in a database ‘before and after’ transactions, certain properties are
followed. They are

 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

Question: What is SAVEPOINT in a transaction control


Answer: A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without
rolling back the entire transaction.

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: What are the scalar functions in SQL? Give an example


Answer: Scalar Functions are used to return a single value based on the input values. Scalar Functions are as
follows:

 UCASE(): Converts the specified field in upper case

SELECT UCASE("SQL Tutorial is FUN!") AS UppercaseText;


UppercaseText
SQL TUTORIAL IS FUN!

 LCASE(): Converts the specified field in lower case

Question: What is a cursor, and when do you use it?


Answer: A cursor is a database object which is used to manipulate data by traversing row by row in a result set. A
cursor is used when you need to retrieve data, one row at a time from a result set and when you need to update
records one row at a time.
DECLARE @CustomerId INT
,@Name VARCHAR(100)
,@Country VARCHAR(100)
--DECLARE AND SET COUNTER.
DECLARE @Counter INT
SET @Counter = 1
--DECLARE THE CURSOR FOR A QUERY.
DECLARE PrintCustomers CURSOR READ_ONLY
FOR
SELECT CustomerId, Name, Country
FROM Customers
--OPEN CURSOR.
OPEN PrintCustomers
--FETCH THE RECORD INTO THE VARIABLES.
FETCH NEXT FROM PrintCustomers INTO
@CustomerId, @Name, @Country
--LOOP UNTIL RECORDS ARE AVAILABLE.
WHILE @@FETCH_STATUS = 0
BEGIN
IF @Counter = 1
BEGIN
PRINT 'CustomerID' + CHAR(9) + 'Name' + CHAR(9) + CHAR(9) + CHAR(9) + 'Country'
PRINT '------------------------------------'
END
--PRINT CURRENT RECORD.
PRINT CAST(@CustomerId AS VARCHAR(10)) + CHAR(9) + CHAR(9) + CHAR(9) + @Name + CHAR(9) + @Country
--INCREMENT COUNTER.
SET @Counter = @Counter + 1
--FETCH THE NEXT RECORD INTO THE VARIABLES.
FETCH NEXT FROM PrintCustomers INTO
@CustomerId, @Name, @Country
END
--CLOSE THE CURSOR.
CLOSE PrintCustomers
DEALLOCATE PrintCustomers

Question: What is a set-based solution?


Answer: Cursors operate on individual rows, and in case of a set, it works on a resultant set of data, which could be
a table/view or a join of both. The resultant set is an output of a SQL query.

Question: What is a forward cursor?


Answer: Forward cursors support fetching of rows from start to end from a result set. You cannot go to the previous
row in the result set.

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

StudiD Name Phonenum


-----------------------
1 John 9176612345,9176645698
2 Susie 9176645789
3 Jim 9176696325

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

StudiD Name Phonenum

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

StudiD Name /* student table */


1. John
2 Susie
3. Jim

StudiD Phonenum /* studentphonenumber table */


------------------
1 9176612345
1 9176645698
2 9176645789
3 9176696325

 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.

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY

222 Harry 201010 CT Monroe


333 Stephan 02228 TX Dallas

444 Lan 060007 IL Chicago

The above table is split into 2 tables and now the tables are in the third normal form.
EMPLOYEE table:

EMP_ID EMP_NAME EMP_ZIP

222 Harry 201010

333 Stephan 02228

444 Lan 060007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY

201010 CT Monroe

02228 TX Dallas

060007 IL Chicago

Question: What is de-normalization, and when do you go for it?


Answer: De-normalization is a technique sometimes used to improve performance so the table design allows
redundant data to avoid complex joins. If the application involves heavy read operations, then de-normalization is
used at the expense of the write operations performance.

Question: What is a primary key, a foreign key, and unique key


Answer:

 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.

EMP_ID EMP_NAME Government_ID

222 Harry 111-203-987

333 Stephan 789-456-123

444 Lan 745-562-321

#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.

Question: What are clustered indices and non-clustered indices?


Answer: A table can have only one clustered index. In this type of index, it reorders the table based on the key
values and physically stores them in that order.
The non-clustered index does not have the physical ordering of the data in the table it has a logical order.

CREATE CLUSTERED INDEX IX_tblStudent_Gender_Score


ON student(gender ASC, total_score DESC)

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.

CREATE NONCLUSTERED INDEX IX_tblStudent_Name


ON student(name ASC)

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: What is T-SQL?


Answer: It is an extension of SQL(Structured Query Language) developed by Sybase and used by Microsoft.

Question: What are system functions and give one example


Answer: System functions are operations performed on the database server, and values are returned accordingly.
Example @@ERROR - Returns 0 if the previous Transact-SQL statement encountered no errors. Otherwise returns
an error number.

@@ERROR - Returns 0 if the previous Transact-SQL statement encountered no errors.

Otherwise returns an error number.

Question: What is a transaction log?


Answer: A log is an audit trail file where the history of actions executed by the DBMS is stored.

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.

CREATE TABLE products


( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);
CREATE TABLE inventory
( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
ON DELETE CASCADE
);
The Products table is the parent table and the inventory table is the child table. If a productid is deleted from the
parent table all the inventory records for that productid will be deleted from the child table

Question: What is the difference between SQL and MySQL


Answer: SQL is a structured query language used to access the DBMS whereas MYSQL is an Open Source
Relational DBMS.

Question: Can we use TRUNCATE with a WHERE clause?


Answer: No, we cannot use TRUNCATE with the WHERE clause.

Question: Define COMMIT


Answer: When a COMMIT is used in a transaction all changes made in the transaction are written into the database
permanently.

BEGIN TRANSACTION;
DELETE FROM HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION;

The above example deletes a job candidate in a SQL server.

Question: What does CHECK CONSTRAINT do?


Answer: Check Constraint limits the values that can enter a column in a database table. It is used as an integrity
constraint check.
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The
CHECK constraint ensures that you can not have any person below 18 years:
The syntax below is in MySQL.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

Question: What is a schema?


Answer: A schema is a collection of database objects in a database for a particular user/owner. Objects can be
tables, views, indices and so on.
Question: How can you create an empty table from an existing table?
Answer:

CREATE TABLE NEW_TABLE_NAME AS SELECT [column1, column2 ……column]

FROM EXISTING_TABLE_NAME [WHERE ]

Question: What is a composite key?


Answer: When more than one column is used to define the primary key, it is called a composite key.
Here is a SQL syntax to create a composite key in MySQL

CREATE TABLE SAMPLE_TABLE


(COL1 integer,
COL2 varchar(30),
COL3 varchar(50),
PRIMARY KEY (COL1, COL2));

Question: How do you sort records in a table?


Answer: The ORDER BY Clause is used to sort records in a table.

SELECT * FROM Emp ORDER BY salary;


By default, the records are returned in ascending order.

Question: What is a shared lock?


Answer: When two transactions are granted read access to the same data, they are given a shared lock. This
enables reading the same data, and data is not updated until the shared lock is released.

Question: What is a deadlock?


Answer: It is an unwanted situation where two or more transactions are waiting indefinitely for one another to release
the locks.
Below is an example of a deadlock situation

Question: What is lock escalation?


Answer: Lock escalation is a process of converting row or page locks into table locks. It is an optimization technique
used by RDBMS like SQL Server dynamically.

Question: What is SQL injection?


Answer: SQL injection is a code injection technique used to hack data-driven applications.

Question: What are views, and why are they used?


Answer: SQL views are virtual tables created from one or more tables. Views are a subset of data; hence, it can limit
the degree of exposure of data from the tables.
The following SQL creates a view that shows all customers from Brazil:

CREATE VIEW Brazil_Customers_view AS


SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";

You can query the view above as follows:

SELECT * FROM Brazil_Customers_view;

Question: How do we avoid getting duplicate entries in a query?


Answer: The Select DISTINCT is used to get distinct data from tables using a query
The following SQL statement selects only the DISTINCT values from the "Country" column in the "Customers" table:

SELECT DISTINCT Country FROM Customers;

Question: Give an example of a comparison operator in SQL


Answer: EQUAL TO written as = is used to compare data values

Question: What is a Subquery?


Answer: A subQuery is a SQL query nested into a larger Query.

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.

Question: What is a Non-correlated subquery


Answer: A Non-Correlated subquery is an independent query, and the output of subquery is substituted in the main
query.

Question: What is a SYSTEM Privilege?


Answer: Rights are given to a user, usually by the DBA, to perform a particular action on the database schema
objects like creating tablespaces.
The following are examples of system privileges that can be granted to users:

 CREATE TABLE allows a grantee to create tables in the grantee's schema.


 CREATE USER allows a grantee to create users in the database.
 CREATE SESSION allows a grantee to connect to an Oracle database to create a user session.

Question: What are Object Privileges?


Answer: An object-level privilege is a permission granted to a database user account or role to perform some action
on a database object. These object privileges include SELECT, INSERT, UPDATE, DELETE, ALTER, INDEX on
tables, and so on.
The following examples are object privileges that can be granted to users:

 SELECT ON hr.employees TO myuser


 INSERT ON hr.employees TO myuser

Question: What does the BCP command do?


Answer: The BCP (Bulk Copy) is a utility or a tool that exports/imports data from a table into a file and vice versa

Question: What is a NULL Value field?


Answer: A NULL value is a field with No Value.
Question: What does the VARIANCE function do?
Answer: This function returns the VARIANCE of a set of numbers:

CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,


ENAME VARCHAR2(10),
JOB VARCHAR2(9),
SAL NUMBER(7, 2),
DEPTNO NUMBER(2));
INSERT INTO EMP VALUES (1, 'SMITH', 'CLERK', 800, 20);
INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1600, 30);
INSERT INTO EMP VALUES (3, 'WARD', 'SALESMAN', 1250, 30);
INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER', 2975, 20);
INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250, 30);
INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER', 2850, 30);
INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER', 2850, 10);
INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST', 3000, 20);
INSERT INTO EMP VALUES (9, 'KING', 'PRESIDENT',3000, 10);
INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500, 30);
INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK', 1500, 20);
SQL> SELECT VARIANCE(sal)
2 FROM emp;
VARIANCE(SAL)
-------------
759056.818

Question: What is the role of GRANT and REVOKE commands?


Answer: The GRANT command enables privileges on the database objects and the REVOKE command removes
them. They are DCL commands

GRANT CREATE ANY TABLE TO username


GRANT sysdba TO username
GRANT DROP ANY TABLE TO username
REVOKE CREATE TABLE FROM username

Question: What is a UNION operator?


Answer: The UNION operator combines the results of two or more Select statements by removing duplicate rows.
The columns and the data types must be the same in the SELECT statements.

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDER BY City;

Question: Where are stored procedures stored in the database?


Answer: Stored Procedures are stored in the Data Dictionary of the Database.

Question: Can we call Stored Procedure inside Stored Procedure?


Answer: Yes, we can call a stored procedure from another stored procedure. For example, Procedure2 is the
procedure which is called Procedure1. Both Procedure1 and Procedure2 can have business logic implemented in it.

Create PROCEDURE Procedure1

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.

Question: Can a Stored Procedure contain a return value?


Answer: Procedures may or may not return values.

Question: Can a View be active if the Base table is dropped?


Ans: No, the view cannot be active in the parent table is dropped.

Question: What is a One-Many Relationship in SQL?


Answer: In a One-Many relationship, a record in One Table can be associated or related to Many records in another
table.

Question: What is a Natural Join?


Answer: A Natural join by default is an Inner Join that creates an implicit join based on the common columns in the
two tables being joined:
A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a RIGHT OUTER join. The default is INNER join.
If the tables COUNTRIES and CITIES have two common columns named COUNTRY and COUNTRY_ISO_CODE,
the following two SELECT statements are equivalent:

SELECT * FROM COUNTRIES NATURAL JOIN CITIES

SELECT * FROM COUNTRIES JOIN CITIES


USING (COUNTRY, COUNTRY_ISO_CODE)

Question: What is a Cross Join?


Answer: In a SQL cross join, a combination of every row from the two tables is included in the result set. This is also
called Cross Product Join. For example, if table A has ten rows and table B has 20 rows, the result set will have 10 *
20 = 200 rows provided there is NOWHERE clause in the SQL statement.
Question: What are the subsets of SQL?
Answer:
The following are the subsets of SQL

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.

Question: Distinguish between a table and a field in SQL.


Answer: The collection of data organized in the form of columns and rows refers to the table. The number of columns
in a table refers to the field.

Table: Employee_Details
Fields: Emp_id, Emp_name, Emp_dept, Emp_salary

Question: Explain SQL constraints?


Answer: Constraints are used to specify the rules of data type in a table.
They can be specified while creating and altering the table.
The following are the constraints in SQL:

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

Question: What are entities and relationship


Answer:

 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.

Question: Write the SQL query to get the current date.


Answer:

SELECT CURDATE();

Question: What is the TRUNCATE command? How is it different from the DELETE command?
Answer:

DELETE TRUNCATE

DML command DDL command

We can use WHERE clause We cannot use WHERE clause

Deletes a row from the table. Deletes all rows from the table.

We can rollback. We cannot rollback.

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.

Question: What are case manipulation functions?


Answer: Case manipulation functions converts the existing data in the table to lower, upper or mixed case
characters.

Question: What are the different case manipulation functions in SQL?


Answer:

1. LOWER: converts all the characters to lowercase.


2. UPPER: converts all the characters to uppercase.
3. INITCAP: converts initial character of each word to uppercase

Question: What are the character manipulation functions?


Answer: Character manipulation functions alter, extract and change the character string.

Question: What are the different character manipulation functions?


Answer:

1. CONCAT: joins two or more string values.


2. SUBSTR: extracts string of a specific length.
3. LENGTH: returns the length of the string
4. INSTR: returns the position of the specific character.
5. LPAD: padding of the left-side character value for right-justified value.
6. RPAD: padding of right-side character value for left-justified value.
7. TRIM: removes the defined character from beginning and end or both.
8. REPLACE: replaces a specific sequence of characters with another sequence of characters.

Question: Define inconsistent dependency.


Answer: The difficulty of accessing data as the path may be broken or missing defines inconsistent dependency.
Inconsistent dependency enables users to search for data in the wrong different table which afterward results in an
error as an output.

Question: What are the different operators in SQL?


Answer:

1. Arithmetic
2. Comparison
3. Logical

Question: What are GROUP functions? Why do we need them?


Answer: Group functions work on a set of rows and return a single result per group. The popularly used group
functions are AVG, MAX, MIN, SUM, VARIANCE, COUNT

Question: Distinguish between BETWEEN and IN conditional operators.


Answer: BETWEEN- Displays the rows based on range of values
IN- Checks for values contained in a specific set of values.
Example:

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;


SELECT * FROM students where ROLL_NO IN (8,15,25);

Question: What is the MERGE statement?


Answer: The statement enables conditional updates or inserts into the table. It updates the row if it exists or inserts
the row if it does not exist.
Question: Explain recursive stored procedure.
Answer: Stored procedure calling itself until it reaches some boundary condition is a recursive stored procedure. It
enables the programmers to use a set of code n number of times.

Question: How can dynamic SQL be executed?


Answer: It can be executed by the following ways:

 By executing the query with parameters.


 By using EXEC
 By using sp_executesql

Question: Define Cursor


Answer: Cursor is a control that allows traversal over the rows and records of the table. It acts as a pointer to a row
in a set of rows. It is used for traversing like retrieval, addition, and removal of database records.

Question: What is the stored procedure?


Answer: It is a function consisting of many SQL statements to access the database system. Several SQL statements
are consolidated into a stored procedure and are executed wherever and whenever required.

Question: What do you understand by Auto Increment?


Answer: This keyword allows a new unique number to be generated whenever a new record is inserted into the
table. It can be used where we need the PRIMARY KEY.

Question: What is a Data warehouse?


Answer: Data from multiple sources of information is stored in a central repository called Data warehouse. Data
warehouses have subsets of data called data marts. The data stored is transformed and used for online mining and
processing.

Question: What are user-defined functions?


Answer: Functions written to use the specific logic whenever required are user-defined functions. It avoids
redundancy by avoiding writing the same logic again.

Question: Mention the types user-defined functions?


Answer: There are three types of user-defined functions:

 Scalar functions
 Inline Table-valued functions
 Multi statement valued functions

Question: What is ALIAS command?


Answer: This command provides another name to a table or a column. It can be used in WHERE clause of a SQL
query using the as keyword.
Example:

SELECT S.StudentID, E.Result from student S, Exam as E where S.StudentID = E.StudentID

S and E are alias names for student table and exam table respectively.

Question: What is Collation?


Answer: Collation is defined as the set of rules that determines how to store and compare data.

Question: Mention the different types of collation sensitivity.


Answer: The following are the types of collation sensitivity:

1. Case
2. Kana
3. Width
4. Accent

Question: What are STUFF and REPLACE functions?


Answer:
STUFF: overwriteS existing character or inserts a string into another string.
Syntax:

STUFF(string_expression,start, length, replacement_characters)

REPLACE: replaces the existing characters of all the occurrences.


Syntax:

REPLACE (string_expression, search_string, replacement_string)

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.

PL-SQL Interview Questions & Answers


Below are some common basic and advanced interview questions and answers –
Question: What is PL/SQL?
Answer: A procedural language where code can be executed in blocks. It is an extension to SQL.
Question: What are the differences between PL/SQL and SQL?
Answer:

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.

Can perform complex tasks like a high-level


Supports only simple queries that can
programming language, for example, while loop, if-else
perform insert, update, delete on tables.
statements, etc…

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.

No provision for error handling. Customized error handling is possible.

Question: What is the basic structure of PL/SQL?


Answer:

[DECLARE]

--declaration statements (optional)

BEGIN

--execution statements

[EXCEPTION]

--exception handling statements


END;

Question: Define cursor and its use.


Answer: A cursor is a pointer to a memory area assigned by Oracle to process SQL statements. The cursor is used
to hold records returned by the SQL query. There are 2 types of cursors – implicit and explicit.
Question: Why do we use database triggers? Give the syntax of a trigger.
Answer: The trigger is a stored procedure that is automatically invoked when an event happens. The event could be:
insert, update, delete, etc… Syntax –

create trigger [trigger_name]

[before | after]

on [table_name]

[for each row]

[trigger_body]

Question: How do you compile PL/SQL code?


Answer: Firstly, syntax check is performed. When the developer corrects any syntax errors, Oracle binds all the
variables holding data with a storage address. Finally, the p-code generation process takes place.
Question: Explain exception handling in PL/SQL.
Answer: PL/SQL offers customized exception handling. When an error occurs, an error handling code is included in
the program itself. There are 3 types of exceptions –

 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.

Question: Tell about a few data types in PL/SQL.


Answer: There are many data types –

 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

The attribute that declares a variable of type RECORD


The attribute that declares a variable
having the same structure as a table row. The row is the
of the same data type as of a table
RECORD that contains fields having the same data
column.
types and names as the columns of a table or view.

Example – Example –
DECLARE
DECLARE
studentId
stud_rec
students.student_id%TYPE;
students.%ROWTYPE;

Question: What constitutes a PL/SQL package?


Answer: Packages are schema objects that place functions, procedures, variables, etc… in one place. Packages
should have –

 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

The function is compiled every time


Procedures are pre-compiled and saved. They
it is called for execution. execute the pre-compiled code whenever called.

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.

Can return multiple values using other


Can return multiple values
methods, otherwise, return only a single value.

Returns scalar data types. Returns an int by default.

A stored procedure can not be called from a


The procedure can call any function
function

Functions can be embedded in a select Inside a select statement, a procedure cannot be


statement called.

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.

Can have parameters Doesn’t have parameters


Cannot be inactive Can be enabled or disabled on need basis

Creation – CREATE PROCEDURE Creation – CREATE TRIGGER

Question: What are the different types of cursors in PL/SQL?


Answer: There are two types of cursors –

 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 ;

Question: What are the different types of constraints?


Answer:

 Not NULL
 Unique
 Primary key
 Foreign key
 Check

Question: What are the differences between triggers and constraints?


Answer:

TRIGGERS CONSTRAINTS

A constraint on a table is stored along with the


Stored as separate objects
table definition

Triggers are fired upon an event; hence they are Constraints are fired as soon as the
fired after constraints
the table is used.

Perform table to table Performs memory location to table the


comparison, hence faster comparison which is slow leading to low
performance.

Trigger is for the entire table The constraint is for a column of the table

They are just stored procedures that get


automatically executed, hence don’t check for Prevent duplicate and invalid data entries
data integrity.
Question: Explain different types of PL/SQL blocks.
Answer: Block is any group of PL/SQL code like SQL statements, loops, variables, constants etc… There are 2
types of blocks –
 Anonymous blocks – these do not have a header or name.
 Named blocks – these blocks have header or label. They can be stored procedures, functions, triggers or
packages.

Question: Explain PL/SQL Records.


Answer: Records contain a set of data of various data types that can be related to each other as fields. Three types
of records that are supported in PL/SQL are table-based records, programmer-based records, and cursor-based
records.
Question: Explain the difference between commit and savepoint.
Answer:
COMMIT – is used to make the database changes permanent. All the save points are erased and the transaction
ends. Once committed, a transaction cannot be rolled back.
SAVEPOINT – is used to set points during a transaction to which a programmer can roll-back later. it is helpful when
there is a series of transactions that can be divided into groups having savepoint.
Question: What is the difference between actual and formal parameters?
Answer: The parameters that are used to call a procedure are called as actual parameters. Example –

get_student_details(stud_name, dob); -- here stud_name and dob are actual parameters.

The variables declared in a procedure header used in the body are called formal parameters. Example –

PROCEDURE get_student_details (dob DATE) IS – here stud_name is a formal parameter.

Question: How is a DECLARE statement used?


Answer: DECLARE is used as the first statement for stand-alone files that consist of anonymous block of code which
are not stored procedures, functions or triggers. Example –

DECLARE

num1 NUMBER(2);

num2 NUMBER(3);

BEGIN

-- logic goes here

END;

Question: Tell us about SQLCODE and SQLERRM.


Answer: SQLCODE and SQLERRM are used to trace exceptions that are not explicitly handled in the program.
These are globally defined variables. SQLCODE returns the error code while SQLERRM returns the corresponding
error message.
Question: What is rollback? How is it different from rollback to statement?
Answer: Rollback erases all the database changes including all the savepoints. It ends a transaction.
‘Rollback to’ rollbacks the changes up to the savepoint mentioned in the code. The transaction will still be active.
Question: What is IN OUT parameter?
Answer: IN OUT parameter mode passes a value to a subprogram and returns an updated value.
Question: Is it possible to accept user inputs during runtime? How?
Answer: Yes, it is possible. Use ACCEPT keyword to take inputs from the user. Example –
ACCEPT age number prompt ‘Enter your age:’
Question: Give a simple way to run a query faster.
Answer: By using ROWID. It is not a physical column but the logical address of a row. It contains the block number,
file number and row number thereby reducing I/O time hence making query execution faster.
Question: What are some of the pre-defined exceptions in PL/SQL?
Answer: ZERO_DIVIDE, NO_DATA_FOUND, TOO_MANY_ROWS, INVALID_CURSOR, DUP_VAL_ON_INDEX
etc…
Question: How do you trace the PL/SQL code?
Question: You can trace through DBMS_* methods like

 DBMS_APPLICATION_INFO
 DBMS_TRACE
 DBMS_SESSION and DBMS_MONITOR

Question: How to restrict string length in PL/SQL?


Answer: Use CHAR (NUMBER) to get fixed length for a variable. Example – CHAR (10). If the length of the string is
less than the specified number, it will be padded with white spaces.
Question: What is the purpose of the UTL_FILE package in PL/SQL?
Answer: By using this package, developers can get the code read and write files to and from the computer. For doing
this, the developer will need access grant from DBA user.
Question: What are DBMS_OUTPUT and DBMS_DEBUG?
Answer: Both can be used for debugging the code. DBMS_OUTPUT prints the output to console whereas
DBMS_DEBUG prints it to a log file.
Question: List some cursor attributes in PL/SQL.
Answer:

 %ISOPEN: Check if the cursor is open


 %ROWCOUNT: Get the number of rows that are updated, deleted or fetched.
 %FOUND: Checks if the cursor has fetched any row, returns Boolean.
 %NOT FOUND: Checks if the cursor has fetched any row. Returns Boolean.

Question: What is the purpose of NVL?


Answer: NVL lets the programmer substitute a value for a NULL value. Example –

NVL (occupation, ‘default’)

Question: On a table, how many triggers can be applied?


Answer: 12 is the maximum number.
Question: How can we achieve consistency using PL/SQL?
Answer: We can achieve consistency by setting the appropriate isolation level. For example, to give read
consistency, the isolation level can be set to READ COMMITTED.
Question: Write a simple procedure to select some records from the database using some parameters.
Answer: Example code –

CREATE PROCEDURE get_customer_details @age nvarchar(30), @city nvarchar(10)

AS

BEGIN
SELECT * FROM customers WHERE age = @age AND city = @city;

END;

Question: Explain the error ORA-03113.


Answer: The error end-of-file on communication channel ORA-03113 means that there is a broken connection
between the client and server channels. It could be a timeout because of which the connection was lost. You can
troubleshoot by pinging the server and checking the connectivity.
Question: Can you use IF statement inside a SELECT statement? How?
Answer: Yes, we can do so using the DECODE keyword in versions 9 and above. Example –

SELECT day_of_week,

DECODE (number, 0, 'Sunday',

1, 'Monday',

2, 'Tuesday',

3, 'Wednesday',

4, 'Thursday',

5, 'Friday',

6, 'Saturday',

'No match') result FROM weekdays;

Question: What is SYS.ALL_DEPENDENCIES?


Answer: SYS.ALL_DEPENDENCIES describes all the dependencies between packages, procedures, functions,
triggers accessible to the current user. It shows columns like name, type, dependency_type, referenced_owner, etc…

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

DBMS Interview Questions


Question: Define a DBMS (Database Management System) and what is it used for?
Answer: DBMS are software applications that help you build and maintain logically related data also known as the
database. Here are a few advantages of using a DBMS:

 Data Redundancy is controlled.


 Unauthorized access is restricted.
 Enforces integrity constraints.
 Data availability and sharing
 Data protection and storage

Question: What is a Hierarchical database Model?


Answer: In a hierarchical database model, data is organized into nodes in a tree-like structure. A node is connected
to only one parent node above it. Hence data in this model has a one-to-many relationship. An example of this model
is the Document Object Model (DOM) often used in web browsers.

Question: What is a Network Model?


Answer: The network database model is a refined version of a hierarchical model. Here too, data is organized in a
tree-like structure. However, one child node can be connected to multiple parent nodes. This gives rise to a many-to-
many relationship between data nodes. IDMS (Integrated Database Management System), Integrated Data Store
(IDS) are examples of Network Databases.

Question: What is an RDBMS?


Answer: A relational database is organized into tables, records, and column and there is a well-defined relationship
between database tables. A relational database management system (RDBMS) is an application that allows you to
create, update, and administer a relational database. Tables communicate and share the information which enables
data search, data organization, and reporting. An RDBMS is a subset of a DBMS.

Question: What is an Object-Oriented Database Model?


Answer: In an object-oriented database model, data is represented by objects. For example, a multimedia file or
record in a relational database is stored as a data object as opposed to an alphanumeric value.

Question: What is SQL?


Answer: SQL (Structured Query Language) is a programming language used to communicate with data stored in
databases. SQL language is relatively easy to write, read, and interpret.

Question: What are DDL, DML and DCL statements in SQL?


Answer:

 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.

Click here to know more about SQL Command.

Question: What do you mean by Index hunting?


Answer: A database index is a data structure that improves the speed of data retrieval operations on a database.
The procedure of boosting the collection of indexes is named as Index hunting. It is done by using methods like query
optimization and query distribution.

Question: What is a distributed database?


Answer: A distributed database is a collection of multiple interconnected databases that are spread physically across
various locations. The databases can be on the same network or on multiple networks. A DDBMS (Distributed –
DBMS) integrates data logically so to the user it appears as one single database.

Question: What is a database partitioning?


Answer: Database partitioning is a process where a logical database is divided into distinct independent parts. The
database objects like tables, indexes are subdivided and managed and accessed at the granular level.

Question: Explain the importance of database partitioning?


Answer: Partitioning is a powerful functionality that increases performance with decreased cost. It enhances the
manageability and improves the availability of data.

Question: What is a static SQL?


Answer: In a static SQL, the SQL statements are embedded or hard-coded in the application and they do not change
at runtime. How data is to be accessed is predetermined hence it is more swift and efficient. The SQL statements are
compiled at compile time

Question: What is dynamic SQL?


Answer: In a dynamic SQL, SQL statements are constructed at runtime, for example, the application can allow the
user to create the queries. Basically, you can build your query at runtime. It is comparatively slower than the static
SQL as the query is compiled at runtime.

Question: Define Data Warehousing.


Answer: Data Warehousing is a technique that aggregates a large amount of data from one or more sources. Data
analysis is performed on the data to make strategic business decisions for organizations.

Question: Name one open-source RDBMS.


Answer: MySQL is an open-source relational database management system, which stores data in tables and
maintains a relationship between the data. It uses the most powerful query language SQL (Structured Query
Language) for database access and has a very powerful syntax to create simple and complex queries to retrieve and
structure data. Data in MySQL is organized and conforms to a certain format, and hence it is the most popular
structured database today. Its ‘free’ source code is available for study, modification, and distribution.

Question: What is MongoDB?


Answer: MongoDB is a non-relational unstructured open-source database. This document-oriented database stores
your data in collections made out of individual documents. In MongoDB, a document is a big JSON object with no
particular format or schema. MongoDB represents JSON documents in a binary-encoded format named as BSON

 Read the difference between MongoDB vs MySQL

Question: What is BI (Business Intelligence)?


Answer: Business intelligence (BI) is a technology-driven process for analyzing data and presenting information to
help executives, managers, and other corporate end-users make business decisions. There are many tools available
like SAP Business Intelligence, MicroStrategy, Sisense and so on. The tools are user-friendly that helps you gather
data from varied sources for analysis.

Question: What is the role of a DBA in DBMS?


Answer: The Database Administrator (DBA) plays some important roles in an organization. They are as follows:

 Installing and configuring databases


 Performance Monitoring
 Security planning and implementation
 Data backup and recovery
 Troubleshooting
 Data migration

Question: What is an ER diagram in DBMS?


Answer: An entity-relationship model or an entity-relationship diagram is a visual representation of data which is
represented as entities, attributes and relationships are set between entities.

Question: What is an Entity in an ER diagram?


Answer: An entity can be a real-world object, which can be easily identifiable. For example, in a library database,
books, publishers and members can be considered entities. All these entities have some attributes or properties that
give them their identity. In an ER model, the entities are related to each other.

Question: What is Data Mining?


Answer: Data mining is a process of sorting through a large amount of data to identify patterns and trends. It uses
complex mathematical and statistical algorithms to segment data for the prediction of likely outcomes. There are
many tools for Data Mining like RapidMiner, Orange, Weka and so on.

Question: What is meant by query optimization?


Answer: Query optimization is an important feature when it comes to the performance of a database. Identifying an
efficient execution plan for evaluating and executing a query that has the least estimated cost and time is referred to
as query optimization.

Question: What is a Catalog?


Answer: A catalog is a table that contains the information such as the structure of each file, the type, and storage
format of each data item and various constraints on the data. The information stored in the catalog is called
Metadata.

Question: How many types of relationship exist in database designing?


Answer: There are three major relationship models in database design:-
One-to-one – A row in one table (A) is related to only one row in another table (B)
One-to-many – A row in a table (A) is linked to many rows in another table (B). But a row in table (B) is linked to only
one row in table (A).
Many-to-many – A row in the table (A) is linked to many rows in the table (B) and vice-versa

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.

Question: What is cardinality in context to a database?


Answer: In SQL (Structured Query Language), the term cardinality refers to the uniqueness of data values contained
in a particular column (attribute) of a database table. The lower the cardinality, the more are the duplicated values in
a column.

Question: What is SQL SERVER?


Answer: SQL Server is an RDBMS developed by Microsoft. It is very stable and robust hence popular. The latest
version of SQL Server is SQL Server 2017.

Question: Under what conditions should we use indexes?


Answer: Indexes can be created to enforce uniqueness, to facilitate sorting, and to enable fast retrieval by column
values. When a column is frequently used it is a good candidate for an index to be used with suitable conditions in
WHERE clauses.

Question: What is a hashing technique in a database?


Answer: Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that
represents the original string. Hashing is used to index and retrieve items in a database because it is faster to find the
item using the shorter hashed key than to find it using the original value.

Question: Describe concurrency control?


Answer: Concurrency control is the process of managing simultaneous operations on a database so that database
integrity is not compromised. There are two approaches to concurrency control.
They are Locking (controlling access to data items using locks) and Versioning (using Multi-Version Concurrency
Control) respectively.
So, all the very best! Do let us know the DBMS questions you faced in the interview that are not covered here in this
article so that we can add those here for the benefit of the DBMS community.

S-ar putea să vă placă și