Dummy
Dummy
=========
Basics :
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.
All columns participating in a primary key constraint must not contain NULL values.
eg.
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.
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.
eg.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
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.
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).
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 a table
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
0 rows
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;
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'.
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)
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 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
Ans :
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 :
51. Query to select all the students from table stud whose name begins with 'S'
Ans :
SELECT *
FROM stud
WHERE name LIKE 'S%';
53. Query the record from table emp where the age is between 18 till 58
Ans:
-------
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";
56. Query to filter the records excludes the give fields alone
Ans:
57.Write a query to exact all the record for which payment_detail col is null for
the table payment_detail
Ans:
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
59. select top 5 highest paid salary from emp for country india
Ans:
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 ;
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;
69. Write a query to extract data using below two tables for these columns alone
and order the
data data based on city
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 :
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 :
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 |
+------+----------+--------+---------------------+
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;
# output :
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
Ans :
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
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
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:
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).
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
Ans :
In above query GROUP BY 1 refers to the first column in select statement which is
account_id.
eg.
SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1;
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. 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:
88. How do you get the last id without the max function?
In MySQL:
In SQL Server:
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.
Ans :
90. Find the SQL statement below that is equal to the following:
Ans :
SELECT name FROM customer WHERE state IN ('VA');
Ans :
SELECT name, COUNT(email)
FROM users
GROUP BY email
HAVING COUNT(email) > 1
Ans :
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 :
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;
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.
99. Write a SQL query to fetch all employee records from EmployeeDetails table
who have a salary record in EmployeeSalary table.
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.
or
Answer : intersect
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
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)-
Ans :
Ans :
Scalar Functions are used to return a single value based on the input values.
Scalar Functions are as follows
Action and Event are two main components of SQL triggers when certain actions are
performed the event occurs in response to that action.
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.
Ans. To add another column in the table following command has been used.
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)
Atomicity
Consistency
Isolation
Durability.
UNION ALL – returns all rows selected by either query, including all duplicates.
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.
select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from
Employee );
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%';
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
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;
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.
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.
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:
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 :
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′;