0% found this document useful (0 votes)
272 views

Dummy

1. The document provides answers to frequently asked questions about SQL. It covers SQL basics like what SQL stands for, how to extract data from a table, and different types of constraints. 2. It also discusses key SQL concepts like primary keys, foreign keys, unique keys, indexes, and differences between DROP, TRUNCATE, DELETE commands. 3. Examples are given for creating tables with different constraints and performing DML operations like SELECT, INSERT, UPDATE, DELETE on tables.

Uploaded by

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

Dummy

1. The document provides answers to frequently asked questions about SQL. It covers SQL basics like what SQL stands for, how to extract data from a table, and different types of constraints. 2. It also discusses key SQL concepts like primary keys, foreign keys, unique keys, indexes, and differences between DROP, TRUNCATE, DELETE commands. 3. Examples are given for creating tables with different constraints and performing DML operations like SELECT, INSERT, UPDATE, DELETE on tables.

Uploaded by

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

SQL FAQ :

=========
Basics :

1. SQL stands for ?


Ans : Structured Query Language

2. How to extract the data from a table ?


Ans : Using Select statement

select * from table_name; # all the rows and all the columns from ur table.

3. What is a constraint ?

Ans : Constraints are the rules enforced on the data columns of a table. These are
used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the database.

4. What are the constraints available ?


Ans : Some of the constraints in SQL are – Primary Key, Foreign Key, Unique Key,
SQL Not Null, Default, Check and Index constraint.

5. What is a Primary Key ?


Ans : A PRIMARY KEY constraint uniquely identifies each record in a database table.

All columns participating in a primary key constraint must not contain NULL values.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);

6. Can we have multiple keys for primary key ?


Yes we can define primary key constraint on multiple keys

eg.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME)
);

7. Unique Key ?
Ans : A unique constraint is used to ensure that there are no duplication values in
the field/column.It can allow null values.

eg.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

8. Foregin Key ?
Ans : A FOREIGN KEY is a key used to link two tables together. A FOREIGN KEY in a
table is linked with the PRIMARY KEY of another table.

Table 0 : order_place
key : id2, name
Table1 : Person ( id is the primary key)
col : id,id1 firstname, lastname, age

Table2 : orders
col : orderid,ordername,id,id1,id2 (order id is primary key, id is foregin key)

eg.

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

9. Can a table contain multiple FOREIGN KEY’s?


Ans : Table can have many foregin keys

10. What is SQL NOT NULL constraint?


Ans: NOT NULL constraint is used to ensure that the value in the filed cannot be a
NULL

eg.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

11. What is a CHECK constraint?


Ans : A CHECK constraint is used to limit the value that is accepted by one or more
columns.

eg.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
E.g. ‘Age’ field should contain only the value greater than 18.

12. What is a DEFAULT constraint?


Ans: DEFAULT constraint is used to include a default value in a column when no
value is supplied at the time of inserting a record.

eg.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

13. What is the difference between NULL value, Zero, and Blank space?
Ans : Null value is a field with no value.
Zero is a number 0
Blank space is the value we provide. The ASCII value of space is CHAR(32).

14. Composite key ?

composite key , is a combination of two or more columns in a table that can be


used to
uniquely identify each row in the table. Uniqueness is only guaranteed when the
columns are combined; when taken individually the columns do not guarantee
uniqueness.

CREATE TABLE SAMPLE_TABLE


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

15. Index ?
Ans ;
Indexes are used to retrieve data from the database very fast.
The users cannot see the indexes, they are just used to speed up searches/queries.

CREATE INDEX idx_lastname


ON Persons (LastName);

## syntax to drop an indexes


DROP INDEX index_name ON table_name;

16. AUTO INCREMENT Field


Ans: Auto-increment allows a unique number to be generated automatically when a new
record is inserted into a table.
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.

CREATE TABLE Persons (


ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
17. Create table

-- create a table
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

18. create a table 1 similar to table 2 without create statement


Ans :

CREATE TABLE TestTable AS


SELECT customername, contactname
FROM customers;

19. Drop table


Drop table Persons;

20. Truncate table

Truncate table will delete all the data in the table


TRUNCATE TABLE table_name;

select * from table_name;

0 rows

21. Difference between drop and truncate ?


Ans : Drop will delete the data and drop the structure of the table.
Truncate will only delete the data and not the structure of the table

22. difference between truncate and delete ?


Ans : Delete can delete all the data or specific data form the table.
delete from emp where id = 100 ;
or
delete from emp ; # delete all the data

where as truncate cannot delete specific records but the whole


TRUNCATE TABLE emp;

23. How do you restrict the data at columns level ?


Ans :

sepecify the field names

select id , last_nm, salary from emp;


eg.

select * from emp; # display all the fields and rows


select id,city,sal from emp; display all the rows but only 3 columns

24. write a query f_name and l_name fields from table emp and allow a space in
between the 2 columns
Ans :
select f_nm + ' ' +l_nm from emp;

eg Ann Grace

25. Write a query to rename the column name id as emp_id, name as emp_name for the
table emp;
Ans :
select id as emp_id, name as emp_name from emp;

ax_1, ax_2, ax_3

select ax1_ emp_id, ax2 name , ax3 dept from emp

26. select * from dual, what is the dual mean and what is the default data types ?
Ans :
Dual is a inbuilt table which returns only one row.
Owner of this table is sys, but it can be used by any user

desc dual;

The table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'.

select * from dual

Dummy
-----
X

desc dual;
VARCHAR2(1)

27. how do you get the current system date using dual table ?
Ans :
select sysdate from dual;

28. How to get the details about the structure of the table ?
Ans :
desc dual;
Name Null? Type
--------------------------- ------
DUMMY VARCHAR2(1)

select * from dual;


DUMMY
----------
X

29. Query to get the number of records from a table emp


Ans :
select count(*) from emp;

30. Difference between count(*) and count(id) ?


Ans:
COUNT(*) will count the number of rows,
COUNT(column) will count all non-null values in column.

31. What is DDL ? DDL commands ?


Ans :
Data Definition Language actually consists of the SQL commands that can be used to
define the database schema.
It simply deals with descriptions of the database schema and is used to create and
modify the
structure of database objects in database.

eg. create, drop,alter, truncate, comment and rename

32. DML and examples ?


Ans :
Data Manipulation Language is a SQL commands that deals with the manipulation of
data present in database belong
to DML or Data Manipulation Language and this includes most of the SQL statements.

eg. update, select, insert and delete

id , nm, contact , start date , end date


1 anne 999 1/jan/16 12/feb/19
1 anne 900 13/feb/19 ----

## update should happen first, followed insert

33. DCL ?
Ans :
Data Control Language, includes commands such as GRANT and REVOKE which mainly
deals with the rights, permissions and other controls of the database system.
eg.
GRANT-gives user’s access privileges to database.
REVOKE-withdraw user’s access privileges given by using the GRANT command.

34. TCL ?
Ans :
transaction Control Language, deals with the transaction within the database.

eg.
COMMIT– commits a Transaction.
ROLLBACK– rollbacks a transaction in case of any error occurs.
SAVEPOINT–sets a savepoint within a transaction.
SET TRANSACTION–specify characteristics for the transaction.

35. How to get only the delhi records from emp table, and handle all types of case
sensitive issues

Delhi
delhi
DELHI
DELhi

Ans :

select * from emp where city = "delhi"; -- will not work


select * from emp where lower(city) = "delhi"; -- right code

select * from emp where lower(city) = "delhi" and lower(city) = "blore"; -- right
code

36. query to change the format of the date to (YYYY-MON-DD) in dual table ?
Ans : ## type casting
SELECT TO_CHAR (Sysdate, 'YYYY-MON-DD') AS System_date_time FROM Dual

## note : YYYY-MON-DD HH24:MI:SS

37. How to remove duplicate in the col from a table ?


Ans : DISTINCT command helps to remove the duplicates

SELECT DISTINCT agent_code


FROM orders;

38.Query to find count of unique id in the retail_shopping table

Ans :

select count(ditinct id) from retail_shopping;

39. Query to select only the id, name, city,country and phone from the table
customer and
restrict the record only to india

Ans :
SELECT Id, FirstName, LastName, City, Country, Phone
FROM Customer
WHERE Country = 'india'

40. query to update the table emp, where the city name is Madras to chennai
Ans:
UPDATE emp
SET City = 'chennai'
WHERE Name = 'Madras'

50. Query to remove record whos salary is great than or equal to 50000 and city is
chennai
Ann :

delete from emp


where salary >= 5000 and city = "chennai"

51. Query to select all the students from table stud whose name begins with 'S'

Ans :
SELECT *
FROM stud
WHERE name LIKE 'S%';

52 . Query to display all the names with 'a' second character


Ans :
SELECT first_name, last_name
FROM stud
WHERE first_name LIKE '_a%';

53. Query the record from table emp where the age is between 18 till 58
Ans:

select * from emp


where age > 18 and < 58
select * from emp
where age >= 18 and age <= 58 -- not to use or condition only and should be used

select * from emp


where gender = "f" or age >=18;

-------
54. Select all the record for which gender is female or age > 18
Ans : where clause
select * from emp
where age > 18 or gender = "F";

55. Query to filter the records based on give fields alone


Ans:

SELECT first_name, last_name, subject


FROM student_details
WHERE subject IN ('Maths', 'Science');

56. Query to filter the records excludes the give fields alone
Ans:

SELECT first_name, last_name, subject


FROM student_details
WHERE subject NOT IN ('Maths', 'Science');

57.Write a query to exact all the record for which payment_detail col is null for
the table payment_detail
Ans:

select * from payment


where payment_detail IS NULL;

58. query to get the top 5 salary from the table emp

Ans :
SELECT name, salary FROM employee
ORDER BY salary
where ROWNUM <= 5;

or

SELECT TOP 5 name, salary FROM employee


ORDER BY salary

59. select top 5 highest paid salary from emp for country india
Ans:

SELECT name, salary FROM employee


ORDER BY salary
where country = "india" and
ROWNUM <= 5 ;

60. Query the records from emp where order is descending for name and ascending
for salary
Ans:
SELECT name, salary
FROM employee
ORDER BY name DESC, salary ;

61. query to get the count of student department wise


Ans :
select dept, count(id)
from student
group by dept;

62. query total amount of salary spent on each department


Ans:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;

63. Query to get the total salary by department and location


Ans:
SELECT location, dept, SUM (salary)
FROM employee
GROUP BY location, dept;

64. get the highest and lowest paid salary from each dept
Ans :
select dept, max(salary), min(salary)
from emp group by dept;

65.Query the department that has total salary paid for its employees more than
25000
Ans :
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000

66. get the count of emp who got promotion more than 3 times department wise
Ans:
SELECT dept, count(promotion)
from emp
group by dept
having count(promotion) > 3;

67. Find suppliers with products over $100.


Ans :
SELECT CompanyName
FROM Supplier
WHERE EXISTS
(SELECT ProductName
FROM Product
WHERE SupplierId = Supplier.Id
AND UnitPrice > 100)

68. List products with order quantities greater than 100.


Ans :
SELECT ProductName
FROM Product
WHERE Id IN (SELECT ProductId
FROM OrderItem
WHERE Quantity > 100)

69. Write a query to extract data using below two tables for these columns alone
and order the
data data based on city

desired output : id | name |salary | city_name

Table : emp
Col : id | name | salary | department | city_id

Table : city
col :
id | city_name

Note : number of records in city table is 10 and number of records in emp tables is
10,000

Ans :

select e.id, e.name , e.salary ,c.city_name


from emp e left join city c
on e.city_id = c.id
order by c.city_name

70. Query to sort the result in an ascending order by NAME and SALARY.

Customer
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Ans :

SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY;

result :
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+

71.

Table 1 - Customer

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Table 2 - Orders

+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

required output :

+------+----------+--------+---------------------+
| ID | NAME | AMOUNT | DATE |
+------+----------+--------+---------------------+
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+------+----------+--------+---------------------+

72. What is a view ?


Ans :
Database views are created using the CREATE VIEW statement.
Views can be created from a single table, multiple tables or another view.

To create a view, a user must have the appropriate system privilege according to
the specific implementation.

eg .

customer
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

query :
CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;

CREATE VIEW COUNTRY_CHN AS


SELECT name, age
FROM country where city = 'chennai' ;

SELECT * FROM CUSTOMERS_VIEW;

# output :

+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+

73. What is the difference between union and union all ?


Ans :
UNION merges the contents of two structurally-compatible tables into a single
combined table.
The difference between UNION and UNION ALL is that UNION will omit duplicate
records whereas
UNION ALL will include duplicate records.

74. What is the out of this below query ?

SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM races)

sql> SELECT * FROM runners;


+----+--------------+
| id | name |
+----+--------------+
| 1 | John Doe |
| 2 | Jane Doe |
| 3 | Alice Jones |
| 4 | Bobby Louis |
| 5 | Lisa Romero |
+----+--------------+

sql> SELECT * FROM races;


+----+----------------+-----------+
| id | event | winner_id |
+----+----------------+-----------+
| 1 | 100 meter dash | 2 |
| 2 | 500 meter dash | 3 |
| 3 | cross-country | 2 |
| 4 | triathalon | NULL |
+----+----------------+-----------+

Ans :

Result of this query will be an empty set.


The reason for this is as follows: If the set being evaluated by the SQL NOT IN
condition contains any values that are null, then the outer query here will return
an empty set, even if there are many runner ids that match winner_ids in the races
table.

75. What is the desired out of this below query for the given table
Quert : SELECT Name FROM Customers WHERE ReferredBy <> 2;

Customers
Id Name ReferredBy
1 John Doe NULL
2 Jane Smith NULL
3 Anne Jenkins 2
4 Eric Branford NULL
5 Pat Richards 1
6 Alice Barnes 2

Ans :
Although there are 4 customers not referred by Jane Smith (including Jane Smith
herself), the query will only return one: Pat Richards.

ReferredBy = 2 and ReferredBy <> 2, you would expect one of them to be true and one
of them to be false, given the same value of ReferredBy. In SQL Server, however, if
ReferredBy is NULL, neither of them are true and neither of them are false.
Anything compared to NULL evaluates to the third value in three-valued logic:
UNKNOWN.

76. Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name).
If there are 10 records in the Emp table and 5 records in the Dept table, how many
rows will be displayed in the result of the following SQL query

Query : Select * From Emp, Dept

Ans:

The query will result in 50 rows as a “cartesian product” or “cross join”, which is
the default whenever the ‘where’ clause is omitted.

77. Given a table TBL with a field Nmbr that has rows with the following values:

1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1
Write a query to add 2 where Nmbr is 0 and add 3 where Nmbr is 1.

Ans :
update TBL set Nmbr = case when Nmbr = 0 then Nmbr+2 else Nmbr+3 end;

78. Write a SQL query to find the 10th highest employee salary from an Employee
table. Explain your answer.

(Note: You may assume that there are at least 10 records in the Employee table.)

Ans :
SELECT TOP (1) Salary FROM
(
SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC
) AS Emp ORDER BY Salary

if the table has 100 records. Inner query will get the highest 10 salary.
Outter query will take only the first highest

or

SELECT Salary FROM


(
SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 10
) AS Emp ORDER BY Salary LIMIT 1;

79. What is an execution plan? When would you use it? How would you view the
execution plan?
Ans :
An execution plan is basically a road map that graphically or textually shows the
data retrieval methods chosen by the SQL server’s query optimizer for a stored
procedure or ad hoc query. Execution plans are very useful for helping a developer
understand and analyze the performance characteristics of a query or stored
procedure, since the plan is used to execute the query or stored procedure.

80. How can you select all the even number records from a table? All the odd number
records?
Ans:
To select all the even number records from a table:

Select * from table where id % 2 = 0


To select all the odd number records from a table:

Select * from table where id % 2 != 0

81. What is the difference between the RANK() and DENSE_RANK() functions? Provide
an example.

Ans :
For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK()
will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas
DENSE_RANK() will return {1,1,2,3,3,4}.
82. What is the difference between the WHERE and HAVING clauses?

Ans :

The WHERE clause is used to filter records from a result. The filtering occurs
before any groupings are made.
The HAVING clause is used to filter values from a group by (i.e., to check
conditions after aggregation into groups has been performed).

83. what is the order of execution of the query ?

Ans :

order Clause
Function
1 from
select the object
2 where
filter the data record or row wise
3 group by
aggregates the data
4 having
filters the aggregated data
5 select
filters the data column wise
6 order by
sort the data asc or desc
7 limit
restrict the record count

84 . What does group by 1 or 2 refers to the below query ?

SELECT account_id, open_emp_id


FROM account
GROUP BY 1;

Ans :
In above query GROUP BY 1 refers to the first column in select statement which is
account_id.

You also can specify in ORDER BY

eg.
SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1;

it will group by SALESMAN_NAME

85. What is the difference between char and varchar2?


Ans :
When stored in a database, varchar2 uses only the allocated space. E.g. if you have
a varchar2(1999) and put 50 bytes in the table, it will use 52 bytes.

But when stored in a database, char always uses the maximum length and is blank-
padded. E.g. if you have char(1999) and put 50 bytes in the table, it will consume
2000 bytes.

86. Write an SQL query to display the text GREATWORK as:


G
R
E
A
T
W
O
R
K

86. Print the rows which have ‘Yellow’ in one of the columns C1, C2, or C3, but
without using OR.

Table is as follows:

ID C1 C2 C3
1 Red Yellow Blue
2 NULL Red Green
3 Yellow NULL Violet

Ans :
SELECT * FROM table
WHERE 'Yellow' IN (C1, C2, C3)

87. Write a query to insert/update Col2’s values to look exactly opposite to Col1’s
values

Col1 Col2
1 0
0 1
0 1
0 1
1 0
0 1
1 0
1 0

update table set col2 = case when col1 = 1 then 0 else 1 end
Or if the type is numeric:

update table set col2 = 1 - col1

88. How do you get the last id without the max function?

In MySQL:

select id from table order by id desc limit 1;

In SQL Server:

select top 1 id from table order by id desc

88. Given the table mass_table:


with the given weight, get the below table structure

weight kg gms
5.67 5 67
34.567 34 567
365.253 365 253
34 34 0

Ans :
select weight, trunc(weight) as kg, nvl(substr(weight - trunc(weight), 2), 0) as
gms
from mass_table;

# note : The NVL( ) function is available in Oracle, and not in MySQL or SQL
Server. This function is used to replace NULL value with another value. It is
similar to the IFNULL Function in MySQL and the ISNULL Function in SQL Server.

89. Consider the Employee table below.

Emp_Id Emp_name Salary Manager_Id


10 Anil 50000 18
11 Vikas 75000 16
12 Nisha 40000 18
13 Nidhi 60000 17
14 Priya 80000 18
15 Mohit 45000 18
16 Rajesh 90000 –
17 Raman 55000 16
18 Santosh 65000 17

Write a query to generate below output:

Manager_Id Manager Average_Salary_Under_Manager


16 Rajesh 65000
17 Raman 62500
18 Santosh 53750

Ans :

select b.emp_id as "Manager_Id",


b.emp_name as "Manager",
avg(a.salary) as "Average_Salary_Under_Manager"
from Employee a,
Employee b
where a.manager_id = b.emp_id
group by b.emp_id, b.emp_name
order by b.emp_id;

90. Find the SQL statement below that is equal to the following:

SELECT name FROM customer WHERE state = 'VA';

SELECT name IN customer WHERE state IN ('VA');


SELECT name IN customer WHERE state = 'VA';
SELECT name IN customer WHERE state = 'V';
SELECT name FROM customer WHERE state IN ('VA');

Ans :
SELECT name FROM customer WHERE state IN ('VA');

91. How to find a duplicate record?


duplicate records with one field ?

Ans :
SELECT name, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1

92. duplicate records with more than one field


Ans :
SELECT name, email, COUNT(*)
FROM users
GROUP BY name, email
HAVING COUNT(*) > 1

93. How to remove duplicates from table with out distinct

emp_name emp_address sex matial_status


uuuu eee m s
iiii iii f s
uuuu eee m s

Ans :

SELECT FirstName, LastName, MobileNo, COUNT(*) as CNT


FROM CUSTOMER
GROUP BY FirstName, LastName, MobileNo;
HAVING COUNT(*) = 1

94. Write a SQL query to fetch the count of employees working in project 'P1'.

Table - EmployeeDetails
EmpId FullName ManagerId DateOfJoining
121 John Snow 321 01/31/2014
321 Walter White 986 01/30/2015
421 Kuldeep Rana 876 27/11/2016

Table - EmployeeSalary
EmpId Project Salary
121 P1 8000
321 P2 1000
421 P1 12000

Ans :

SELECT COUNT(*) FROM EmployeeSalary WHERE Project = 'P1';

95. Write a SQL query to fetch employee names having salary greater than or equal
to 5000
and less than or equal 10000, using nested query
Ans :
SELECT FullName
FROM EmployeeDetails
WHERE EmpId IN
(SELECT EmpId FROM EmpolyeeSalary
WHERE Salary BETWEEN 5000 AND 10000);
96. Write a SQL query to fetch project-wise count of employees sorted by project's
count in descending order.

Ans :
SELECT Project, count(EmpId) EmpProjectCount
FROM EmployeeSalary
GROUP BY Project
ORDER BY EmpProjectCount DESC;

97. Write a query to fetch employee names and salary records.


Return employee details even if the salary record is not present for the employee.

Ans :
SELECT E.FullName, S.Salary
FROM EmployeeDetails E LEFT JOIN EmployeeSalary S
ON E.EmpId = S.EmpId;

98. Write a SQL query to fetch all the Employees who are also managers from
EmployeeDetails table.

Ans : use self join

SELECT DISTINCT E.FullName


FROM EmpDetails E
INNER JOIN EmpDetails M
ON E.EmpID = M.ManagerID;

99. Write a SQL query to fetch all employee records from EmployeeDetails table
who have a salary record in EmployeeSalary table.

Ans : key , use exists

SELECT * FROM EmployeeDetails E


WHERE EXISTS
(SELECT * FROM EmployeeSalary S WHERE E.EmpId = S.EmpId);

100. Write a SQL query to fetch duplicate records from a table.


Ans:
SELECT EmpId, Project, Salary, COUNT(*)
FROM EmployeeSalary
GROUP BY EmpId, Project, Salary
HAVING COUNT(*) > 1;

101. Write a SQL query to create a new table with data and structure copied from
another table.

Ans :
SELECT * INTO newTable FROM EmployeeDetails;

102 . Write a SQL query to create an empty table with same structure as some other
table.

Ans. Using SELECT INTO command with False 'WHERE' condition-

SELECT * INTO newTable FROM EmployeeDetails WHERE 1 = 0;

or

CREATE TABLE newTable LIKE EmployeeDetails;


103. Write a SQL query to fetch common records between two tables.

Answer : intersect

SELECT * FROM EmployeeSalary


INTERSECT
SELECT * FROM ManagerSalary

104. Write a SQL query to fetch records that are present in one table but not in
another table.
Ans. Minus
SELECT * FROM EmployeeSalary
MINUS
SELECT * FROM ManagerSalary

105. Write a SQL query to find current date-time.

Ans :

Mysql :
SELECT NOW();

SQL Server-
SELECT getdate();

Oracle-
SELECT SYSDATE FROM DUAL;

106. Write a SQL query to fetch all the Employees details from EmployeeDetails
table who joined in Year 2016.
Ans :
SELECT * FROM EmployeeDetails
WHERE DateOfJoining BETWEEN '01-01-2016' AND date '31-12-2016';

Also, we can extract year part from the joining date (using YEAR in mySQL)-

SELECT * FROM EmployeeDetails


WHERE YEAR(DateOfJoining) = '2016';

107. Write a SQL query to fetch top n records using rownum

Ans :

SELECT * FROM (SELECT * FROM EmployeeSalary ORDER BY Salary DESC)


WHERE ROWNUM <= 3;

108. How many Aggregate Functions are available there in SQL?

Ans :

There are 7 aggregate functions we use in SQL

AVG(): Returns the average value from specified columns


COUNT(): Returns number of table rows
MAX(): Returns largest value among the records
MIN(): Returns smallest value among the records
SUM(): Returns the sum of specified column values
FIRST(): Returns the first value
LAST(): Returns Last value

109. What are Scalar Functions in SQL?


Ans :

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


LCASE(): Converts the specified field in lower case
MID(): Extracts and returns character from text field
FORMAT(): Specifies the display format
LEN(): Specifies the length of text field
ROUND(): Rounds up the decimal field value to a number

110. What is a trigger ?


Triggers in SQL is kind of stored procedures used to create a response to a
specific action performed on the table such as Insert, Update or Delete. You can
invoke triggers explicitly on the table in the database.

Action and Event are two main components of SQL triggers when certain actions are
performed the event occurs in response to that action.

111. What is the Cartesian product of table?


Ans .
The output of Cross Join is called as a Cartesian product. It returns rows
combining each row from the first table with each row of the second table. For
Example, if we join two tables having 15 and 20 columns the Cartesian product of
two tables will be 15×20=300 Rows.

112. What do you mean by Subquery?


Query within another query is called as Subquery. A subquery is called inner query
which returns output that is to be used by another query.

113. What is Normalization? How many Normalization forms are there?


Ans:

The process of table design to minimize the data redundancy is called


normalization. We need to divide a database into two or more table and define
relationships between them.

types 1,2,3 and 4 normalized forms

114. Define join and name different types of joins?

Ans :
Join keyword is used to fetch data from related two or more tables. It returns rows
where there is at least one match in both the tables included in the join. Read
more here.
Type of joins are:

Right Join
Outer Join
Full Join
Cross Join
Self Join.

115. How do you add a column to a table?

Ans. To add another column in the table following command has been used.

ALTER TABLE table_name ADD (column_name);

116. Define COMMIT?


Ans. COMMIT saves all changes made by DML statements.

117. What is a stored procedure?


Ans. A stored procedure is a set of SQL queries which can take input and send back
output.

118. How to select random rows from a table?


Ans :
SELECT * FROM table_name SAMPLE(10);

119. Can we rename a column in the output of SQL query?


Ans. Yes using the following syntax we can do this.

SELECT column_name AS new_name FROM table_name;

120. Suppose a Student column has two columns, Name and Marks. How to get name and
marks of top three students.
Ans.
SELECT Name, Marks
FROM Student s1
where 3 <= (SELECT COUNT(*) FROM Students s2 WHERE s1.marks = s2.marks)

121. What are the properties of a transaction?


Ans. Generally, these properties are referred as ACID properties. They are:

Atomicity
Consistency
Isolation
Durability.

122. What do you mean by ROWID?


Ans. It’s an 18 character long pseudo column attached with each row of a table.

123. Define UNION, MINUS, UNION ALL, INTERSECT ?


Ans. MINUS – returns all distinct rows selected by the first query but not by the
second.

UNION – returns all distinct rows selected by either query

UNION ALL – returns all rows selected by either query, including all duplicates.

INTERSECT – returns all distinct rows selected by both queries.

124. What do you mean by query optimization?


Ans. Query optimization is a process in which database system compares different
query strategies and select the query with the least cost.
125. What is Referential Integrity?
Ans. Set of rules that restrict the values of one or more columns of the tables
based on the values of the primary key or unique key of the referenced table.

126. What is Case Function?


Ans. Case facilitates if-then-else type of logic in SQL. It evaluates a list of
conditions and returns one of multiple possible result expressions.

127. What are the advantages of Views?


Ans. Advantages of Views:

Views restrict access to the data because the view can display selective columns
from the table.
Views can be used to make simple queries to retrieve the results of complicated
queries. For example, views can be used to query information from multiple tables
without the user knowing.

128. Do View contain Data?


Ans. No, Views are virtual structure.

129. What is schema?


Ans. A schema is a collection of database objects of a User.

130. SQL Query to find second highest salary of Employee


Answer: There are many ways to find second highest salary of Employee in SQL,
you can either use SQL Join or Subquery to solve this problem. Here is SQL query
using Subquery:

select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from
Employee );

131. SQL Query to find Max Salary from each department.

Ans :
SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID.

132. Write an SQL Query find number of employees according to gender whose DOB is
between 01/01/1960 to 31/12/1975.

Ans :

SELECT COUNT(*), sex from Employees WHERE DOB BETWEEN '01/01/1960' AND '31/12/1975'
GROUP BY sex;

133. find all Employee records containing the word "Joe", regardless of whether it
was stored as JOE, Joe, or joe.

Ans :
SELECT * from Employees WHERE UPPER(EmpName) like '%JOE%';

134. What are Operators available in SQL?


ANS :
There are three types of Operators.

Arithmetic Operators
Comparison Operators
Logical Operators

135. What is the command used to fetch the first 5 characters of a string?
Ans :
SELECT SUBSTRING(EmpName,1,5) AS EmployeeName FROM Employee

136. What will be the result of the query below?


select case when null = null then 'True' else 'False' end as Result;

This query returns “False”. In the above question, we could see null = null is not
the proper way to compare a null value. To compare a value with null, we use IS
operator in SQL.

correct way :
select case when null is null then 'True' else 'False' end as Result;

137. What is Denormalization.

DeNormalization is a technique used to access the data from higher to lower normal
forms of database. It is also process of introducing redundancy into a table by
incorporating data from the related tables.

138. What is user defined functions?

User defined functions are the functions written to use that logic whenever
required. It is not necessary to write the same logic several times. Instead,
function can be called or executed whenever needed.

139 . Conditional Subquery

Ans.
The SQL operator EXISTS tests for the existence of records in a subquery and
returns a value TRUE if a subquery returns one or more records. Have a look at this
query with a subquery condition:

SELECT Name FROM Customers WHERE EXISTS


(SELECT Item FROM Orders
WHERE Customers.ID = Orders.ID AND Price < 50)

140. Query to find Second Highest Salary of Employee?

Ans :
Select distinct Salary from Employee e1 where 2=Select count(distinct Salary) from
Employee e2 where e1.salary<=e2.salary;

141. What is the Query to fetch last record from the table?
Ans :

Select * from Employee where Rowid= select max(Rowid) from Employee;

142. What is Query to display first 5 Records from Employee table


Ans :
Select * from Employee where Rownum <= 5;

143. Find Query to get information of Employee where Employee is not assigned to
the department
Ans :
Select * from Employee where Dept_no Not in(Select Department_no from Department);
144. How to fetch all the records from Employee whose joining year is 2017?
Ans.
select * from Employee where To_char(Joining_date,’YYYY’)=’2017′;

You might also like