https://www.mssqltips.com/sqlservertip/5206/sql-server-datetime-best-practices/
how to use the GROUP BY
clause or ROW_NUMBER()
function to find duplicate values in SQL Server.
The query for finding the duplicate values in multiple columns using the GROUP BY
clause :
SELECT col1,col2,... COUNT(*) FROM table_name GROUP BY col1,col2,... HAVING COUNT(*) > 1;
IMP-
SELECT a.*
FROM Dup_Practice a
JOIN (SELECT name, id, COUNT(*)as bb
FROM [Dup_Practice]
GROUP BY name,id
HAVING count(*) > 1) B
ON a.name = B.name and a.id=b.id
Using ROW_NUMBER()
function to find duplicates in a table
The following statement uses the ROW_NUMBER()
function to find duplicate rows based on both a
and b
columns:
WITH cte AS (
SELECT
a,
b,
ROW_NUMBER() OVER (
PARTITION BY a,b
ORDER BY a,b) rownum
FROM
t1
)
SELECT
*
FROM
cte
WHERE
rownum > 1;
Here is the result:
How it works:
First, the ROW_NUMBER()
distributes rows of the t1 table into partitions by values in the a
and b
columns. The duplicate rows will have repeated values in the a
and b
columns, but different row numbers as shown in the following picture:
Second, the outer query removes the first row in each group.
Generally, This statement uses the ROW_NUMBER()
function to find the duplicate values in one column of a table:
WITH cte AS (
SELECT
col,
ROW_NUMBER() OVER (
PARTITION BY col
ORDER BY col) row_num
FROM
t1
)
SELECT * FROM cte
WHERE row_num > 1;
FUNCTIONS:
It is a predefined program which returns one value, returned value
can be of numeric, string data,
data type functions can be used for calculations
SINGLE ROW FUNCTION:
This function will process one row at a time and returns one value.
Mathematical Functions
String Functions
Date & Time Functions
Data Conversion {Type Casting Functions}
Ranking Functions {Windows Functions}
Meta Data Functions
Other Functions
MULTIPLE ROW FUNCTION: This function will process multiple rows at a time and returns one
value.
Aggregate Functions
SQL SERVER supports to work with 12 categories of Functions and
they are found at following paths
Click on Object Explorer – Data Bases
Select the Data Base - TESTDB
Check under Programmability Functions.
Check under System Functions.
MATHEMATICAL FUNCTIONS:
This function will take input as numbers and will return
output as numbers
ABS (NUMBER) -
returns unsigned value of a given number (Number - Argument or Parameter.
SELECT ABS(-890), ABS(17)
SQRT (NUMBER) - Returns square root of a given positive number.
SQUARE (NUMBER) - Returns square of a
given value
POWER ( NUMBER(Base), NUMBER(Exponent)) - It will
find the power of a given number.
SELECT POWER
(2,5)
SIGN ( NUMBER )
Returns 1 if a number is positive
Returns -1 if a number is negative
Returns 0 if a number is zero
PI() - Returns PI value
SIN (NUMBER) - By default this function will take input given in radians,
hence radians should be
converted to degrees by a standard formula is PI ()/180
SELECT SIN (30* PI()/180)
Built In Functions
Or
Predefined Functions
Table Valued
Functions
Scalar
Functions
Multiple Row Functions
Or
Group Functions
Single Row Functions
Or
Individual Functions
User Defined Functions
Or
Stored Functions
**Functions used with in other function refers to FUNCTION
CASCADING
ROUND ( NUMBER, NUMBER , [NUMBER])
Argument1, Argument2, Argument3 (optional for TRUNCATE)
By default Argument3 is ZERO
ROUND(1234.5678,2,1) --- 1234.5600
ROUND(1234.5678,2) ----- 1234.5700
ROUND(1234.5638,2) ----- 1234.5600
ROUND(1234.5678,1) ----- 1234.6000
ROUND(1234.5678,0) ----- 1235.0000
ROUND(1234.2678,0) ----- 1234.0000
ROUND(1234.5678,-2)----- 1200.0000
ROUND(5678.123,-2) ----- 5700.0000
ROUND(1234.5678,2,1) --- 1234.5600
ROUND(1234.5678,1,1) --- 1234.5000
ROUND(1234.5678,0,1) --- 1234.0000
ROUND(5/2.0,0) --- 3.00
ROUND(5/2.0,0,1) --- 2
This function is used to round a given number with respect to
Integer value or Decimal value based
on user required number of digits. If 3rd argument is specified
other than zero it works as TRUNCATE.
CEILING(NUMBER) – This function will increment a given number to its
nearest integer. Based on
any digit in decimal points is greater than zero.
CEILING (123.000) ---- 123
CEILING (123.010) ---- 124
CEILING (123.456) ---- 124
FLOOR (NUMBER) – It decreases a nearest integer
FLOOR (-123.456) ---- {-124}
STRING FUNCTIONS: This
are used to perform different operations on STRING DATA TYPE.
LEN(TEXT) - Returns number of characters.
SELECT ENAME, LEN(ENAME) FROM
EMP WHERE LEN(ENAME) > 5
LOWER(STRING) – Converts characters to Lower case.
UPPER(STRING) – Converts characters to Upper case.
ASCII(STRING) – returns ASCII code of the given character
ASCII('A')----65
ASCII('P')----80
UNICODE( STRING ) – Returns UNICODE of a given string.
CHAR ( NUMBER ) – Returns character of a given ASCII
code
CHAR (65) –- A { Only
0-255 characters are available}
NCHAR(NUMBER)
NCHAR(256) {1-65535
Characters are available}
LEFT(STRING,NUMBER) –
Extracts number of characters from left side of a string
LEFT('COMPUTER',3) ----
COM
RIGHT( STRING, NUMBER) –
Extracts number of characters from right side of a string
RIGHT('COMPUTER',3)-----TER
SUBSTRING (STRING, STARTPOSITION, NUMBER OF CHAR’S) – It
extracts required string
from a given string based on start position and number of
characters.
SUBSTRING ('COMPUTER',4,3)—PUT
LTRIM(STRING) - Removes blanks spaces from left side of a string.
RTRIM(STRING)- Removes blank spaces from right side of a string.
REPLICATE(STRING, NUMBER) - Displays a given string for n times.
REPLICATE('COMM',2)
REVERSE(STRING) - It will reverse a given string.
SELECT REVERSE('COMM')---
MMOC
REPLACE (STRING1, STRING2, STRING3)
String1 ---- given string, String2 ---- search string,
String3 ---- replace string
REPLACE ('COMPUTER','UT','IR')
It will search for String2 in String1 and replaces with String3 at
all occurrences of String 2 in String1
STUFF(STRING1, NUMBER1, NUMBER2, STRING2)
String1 --- Given String, Number 1--- Start Position, Number2 ---
Number of Characters
String2 --- Replace
STUFF('COMPUTER',5,2,'IL') -- COMPILER
CHARINDEX(STRING1, STRING2, [NUMBER])
String1 --- Search String, String2 --- Given String, Number ---
Position
It will search for string1 in string2 and returns position of
string1, if it exists else returns zero, by
default it will search from first character. It also supports to
search for character/string after a
specific position
SELECT CHARINDEX('R','COMPUTER',7)
SELECT REPLICATE
('*', GRADE) FROM SALGRADE
Q) Display all the employees from the EMP table with half of the
string in upper case and next string
in lower case
SELECT LEFT
(ENAME, CEILING (LEN
(ENAME)/2.0)) +
LOWER(RIGHT (ENAME, CEILING (LEN (ENAME)/2))) FROM EMP
Q) Display all Employees whose name contains 3rd Character
as ‘L’.
SELECT ENAME
FROM EMP WHERE SUBSTRING (ENAME, 3,1)= 'L'
SELECT ENAME
FROM EMP WHERE CHARINDEX ('L', ENAME, 3) = 3
Q) Display all Employees whose name contains A at second
occurance.
SELECT ENAME
FROM EMP
WHERE CHARINDEX
('A', ENAME, CHARINDEX ('A', ENAME) +1 !=0
DATE & TIME FUNCTIONS:
These functions are used to perform operations on date, time data
type. When date type data is
retrieved it will be in the following format.
CENTURY: YEAR: MONTH: DATE: HOURS: MINUTES: SECONDS
GETDATE(): It returns current system DATE & TIME of the Server.
SELECT GETDATE()
ARITHMETIC OPERATIONS on data & time data type “+”, “-“ are the operations which can
be used
for performing operations on date type data.
DATE + NUMBER = DATE
DATE – NUMBER = DATE
DATE – DATE = NUMBER [Number of days]
SELECT HIREDATE, HIREDATE+15, HIREDATE-28 FROM EMP
DAY (DATE) -------- extracts days from date
MONTH (DATE) ----- extracts months from date
YEAR (DATE) ------ extracts year from date
SELECT DAY(GETDATE())
SELECT MONTH(GETDATE())
SELECT YEAR(GETDATE())
DATEADD(DATEPART , NUMBER , DATE) - It is used to add
number of days, months, years to a
given date.
DATEPART can be specified with this format - DD: MM: YY:
HH: MI: SS: DW
SELECT DATEADD(DAY,10,GETDATE())
SELECT DATEADD(DD,10,GETDATE())
SELECT DATEADD(MONTH,10,GETDATE())
SELECT DATEADD(MM,10,GETDATE())
SELECT DATEADD(YEARS,10,GETDATE())
SELECT DATEADD(YY,10,GETDATE())
DATEDIFF( DATEPART, STARTDATE, ENDDATE) - It
returns difference between 2 dates in
terms of days, months & years.
SELECT ENAME, DATEDIFF(DD,HIREDATE,GETDATE()) DAYS
FROM EMP
DATEPART(DATEPART,DATE)- It extracts
individual parts of a table.
DATEPART(DD,GETDATE()) – MM: YY:
HH: MI: SS: DW
DATENAME(DATEPART,DATE) - In this function
month name, day name will be extracted other
date parts providing same output.
DATENAME(MM,GETDATE()) ---- JUNE(Based
on the current server date)
DATENAME(DW,GETDATE()) ----
MON
Q) Display all those Employees data that have been hired on
Sunday.
SELECT ENAME, HIREDATE
FROM EMP WHERE DATENAME(DW,HIREDATE) = 'SUNDAY'
Q) Display all those Employees who have been hired in the month of
December.
SELECT ENAME,HIREDATE
FROM EMP WHERE DATENAME(MM,HIREDATE)= 'DECEMBER'
Q) Display all those Employees who have been hired in second half
of the week.
SELECT ENAME, HIREDATE
FROM EMP
WHERE DATEPART (DW, HIREDATE) > = ROUND(7/2.0,0)
DATA CONVERSION:
This function will support to convert the data stored with one
type to the other type.
SQL SERVER will convert the data with the support of following two
functions.
CAST(SOURCE_DATA AS TARGET_DATA_TYPE)
CONVERT(TARGET_DATA_TYPE, SOURCE_DATA
[NUMBER])
SELECT ENAME
+ ' WORKING AS ' + JOB + ' IN DEPT ' + CAST(DEPTNO AS
VARCHAR(3)) FROM EMP
** String and String can only be concatenated.
** String and Integer cannot be concatenated.
SELECT 5/ CAST(2 AS FLOAT)
SELECT 5/ CONVERT(FLOAT,2)
SELECT CONVERT(VARCHAR(30), GETDATE(),0)
SELECT CONVERT(VARCHAR(30), GETDATE(),8) for
time
** 0 stands for Date formats, there are more than 100 Date
formats.
** 8 & 108 are particularly assigned for time format
RANKING OR WINDOW FUNCTIONS
These functions have been introduced from SQL 2005.
This are used to calculate ranks on any type of data.
These functions require a support of OVER clause, which requires a
specification of ORDER
BY clause, followed by ORDER type.
This function cannot be used at WHERE clause.
SQL SERVER will support to work with following Rank
functions
ROW_NUMBER() – Provides unique row number for each row
RANK() – It calculates ranks with gaps
DENSE_RANK() – It calculates ranks with out gaps
NTILE(INT) – Provides the data in to groups / blocks. It will group
the data based on the user
specified number and number of rows available in a table.
SELECT EMPNO, ENAME, SAL, ROW_NUMBER() OVER
( ORDER BY EMPNO ASC) RN
FROM EMP
SELECT EMPNO, ENAME, SAL, RANK() OVER(ORDER
BY SAL DESC) RNK FROM
EMP
SELECT EMPNO, ENAME, SAL, DENSE_RANK() OVER(ORDER
BY SAL DESC) RNK
FROM EMP
SELECT EMPNO, ENAME, SAL, NTILE(4) OVER( ORDER
BY EMPNO) NT FROM EMP
**The data will be grouped into four groups based on given NTILE
number.
OTHER FUNCTIONS
ISNULL(EXPRESSION1, EXPRESSION2)
This Function will search for NULL values in Expression1 and
Substitutes Expression2 at all the rows
of Expression1 where NULL values are found, Expression2 is
depended on data type of Expression1.
SELECT ENAME, SAL, COMM, ISNULL(COMM,0) RS FROM EMP
SELECT ENAME, SAL, COMM, ISNULL(ENAME,'UNKNOWN') UN FROM EMP
SELECT ENAME ,SAL, COMM, ISNULL
( CAST(COMM AS
VARCHAR(4),'NC') RS
FROM EMP
SELECT ENAME,SAL,COMM,SAL+ISNULL(COMM,0) RS FROM EMP
COALESCE(EXPRESSION1,EXPRESSION2……EXPRESSIONN) - It will
search for NULL values and
Substitutes Expression2 at all rows of Expression1 where NULL
values are found. It Substitutes
Expression3 if Expression2 contains NULL values so on it can have
any number of expressions.
SELECT EMPNO,ENAME,MGR,SAL,COMM
COALESCE(COMM,SAL,MGR,EMPNO,25) RS
FROM EMP
NULLIF( EXPRESSION1, EXPRESSION2) - It is used to compare two expressions of any data
type. If equal it returns NULL, if not equal returns value of
Expression1
SELECT NULLIF(10,10) -----NULL
SELECT NULLIF(10,90) -----10
SELECT NULLIF(‘X’,’Y’)---
X
SELECT ENAME,LEN(ENAME)L1,JOB,LEN(JOB)L2 NULLIF(LEN(ENAME),LEN(JOB))RES
FROM EMP
CASE EXPRESSION
It supports to specify multiple conditions provided with their
respective results. If no condition is
satisfied then it will provide default result.
Syntax:
CASE EXPRESSION
WHEN CONDITION1
THEN RESULT1
[ WHEN CONDITION2 THEN
RESULT2 ]
ELSE
DEFAULT_RESULT
END [ALIAS_NAME]
Q) Display ENAME, SAL and INCREMENT the salary with difference %’s
based on category of JOB.
Manager – 18%, Clerk – 15%, Others – 12%
SELECT ENAME,SAL,JOB,
CASE JOB
WHEN 'MANAGER' THEN SAL*18/100
WHEN 'CLERK' THEN SAL
* 15/100
ELSE
SAL*12/100
END INCR
FROM EMP
Q) Display ENAME, DEPTNO, SAL and INCREMENT the Salary with
different %’s on category of Dept
No 10 – 20%, Dept no 20 – 18%, Dept no 30 – 15%
SELECT ENAME, DEPTNO, SAL,
CASE DEPTNO
WHEN 10 THEN SAL* 20/100
WHEN 20 THEN SAL
* 18/100
WHEN 30 THEN SAL*15/100
END INCR
FROM EMP
MULTIROW FUNCTIONS OR GROUP FUNCTIONS
AGGREGATE FUNCTIONS:
This function will process multiple rows at a time and returns one
value.
SQL SERVER supports to work with following functions
SUM (EXPRESSION) - finds the sum of values in given expression.
AVG (EXPRESSION) - first finds the sum and then divide with number
of values in the
expression.
MAX (EXPRESSION) - finds the maximum value in the given
expression.
MIN (EXPRESSION) - finds the minimum value in the given
expression.
COUNT (EXPRESSION) --- returns number of values in a expression
including duplicates.
COUNT (DISTINCT (EXPRESSION) - returns number of values in an
expression excluding
duplicates.
COIUNT (*) - returns number of rows.
COUNT_BIG (EXPRESSION) - returns number of values.
GROUPING (EXPRESSION) - returns zero or one.
Returns ZERO if there is no group
Returns ONE if there is a group data
POINTS TO BE REMEMBERED
Aggregate Function will exclude NULL values.
When a SELECT statement is enclosed with Aggregate Functions,
along with them writing
expressions that returns multiple rows is invalid.
Aggregate functions cannot be used in where clause.
In SQL SERVER Aggregate Functions cannot be cascaded.
SELECT SUM(SAL) FROM
EMP
SELECT AVG(SAL) FROM
EMP
SELECT SUM(COMM) R1, AVG(COMM) R2, COUNT(COMM)R3 FROM EMP
SELECT SUM(SAL), MAX(SAL) FROM
EMP WHERE DEPTNO = 30
SELECT COUNT(SAL) FROM
EMP
SELECT COUNT(DISTINCT(SAL) FROM
EMP
SELECT COUNT(*) FROM
EMP
To Count the Records
SP_SPACEUSED EMP
SELECT @@ROWCOUNT
SELECT SUM(SAL) , COUNT(*) FROM
EMP WHERE JOB = 'SALESMAN'
SELECT DEPTNO,SUM(SAL),COUNT(*) FROM
EMP GROUP BY DEPTNO
SELECT DEPTNO, JOB,SUM(SAL), COUNT(*) FROM
EMP GROUP BY JOB, DEPTNO
GROUP BY: This
clause performs two tasks
Eliminates duplicates and always arranges the data in ascending
order.
The column used in group by clause, the same column can be used
for displaying the output.
When multiple columns are used it will eliminate if all column
contains duplicates.
SELECT SUM(SAL), COUNT(*) FROM
EMP GROUP BY DEPTNO
SELECT DEPTNO, SUM(SAL), COUNT(*) FROM
EMP GROUP BY DEPTNO
SELECT JOB, SUM(SAL), COUNT(*) FROM
EMP GROUP BY JOB
SELECT MGR, COUNT(*) FROM
EMP GROUP BY MGR
SELECT DEPTNO, JOB, SUM(SAL), COUNT(*) FROM
EMP GROUP BY JOB , DEPTNO
Q) Display DEPTNO, total salary and number of employee’s related
to Dept No 20.
SELECT DEPTNO, SUM(SAL), COUNT(*) FROM
EMP
WHERE DEPTNO
= 20 GROUP BY DEPTNO
ROLLUP AND CUBE OPERATORS
ROLLUP:
This operator should be used only at GROUP BY clause.
It will calculate individual totals, group totals, and additional
row is generated for grand
totals.
SELECT DEPTNO, SUM(SAL), COUNT(*) FROM
EMP GROUP BY DEPTNO WITH ROLLUP
SELECT DEPTNO, JOB, SUM(SAL), COUNT(*) FROM
EMP
GROUP BY DEPTNO, JOB WITH
ROLLUP
SELECT DEPTNO, JOB, SUM(SAL),COUNT(*) , GROUPING(JOB) FROM
EMP
GROUP BY DEPTNO, JOB
WITH ROLLUP
SELECT DEPTNO ,
CASE GROUPING(JOB)
WHEN 0 THEN JOB
WHEN 1 THEN “ALL JOBS”
-- Replaces NULLS With The Value
END DEP, SUM(SAL), COUNT(*)
FROM EMP
GROUP BY DEPTNO, JOB WITH
ROLLUP
CUBE:
This operator is also used only at GROUP BY clause.
It will support to perform individual totals, group totals,
regroup totals and additional row is
generated for grand totals.
SELECT DEPTNO, JOB, SUM(SAL), COUNT(*) FROM
EMP
GROUP BY DEPTNO, JOB WITH
CUBE
Q) Display total salaries of individual departments in a single
row.
SELECT
SUM (CASE DEPTNO
WHEN 10 THEN SAL END) “D10”,
SUM (CASE DEPTNO
WHEN 20 THEN SAL END) “D20”,
SUM (CASE DEPTNO
WHEN 30 THEN SAL END) “D30”
FROM EMP
SELECT DISTINCT JOB,
SUM (CASE DEPTNO
WHEN 10 THEN SAL END) “D10”,
SUM (CASE DEPTNO
WHEN 20 THEN SAL END) “D20”,
SUM (CASE DEPTNO
WHEN 30 THEN SAL END) “D30”,
SUM (SAL) “TOTAL SAL”
FROM EMP GROUP BY JOB
Best sql question for interview
Q #1) What is SQL?
Answer: Structured Query Language SQL is a database tool that is used to create and access the database to support software applications.
Q #2) What are tables in SQL?
Answer: The table is a collection of record and its information at a single view.
Q #3) What are the different types of statements supported by SQL?
Answer:
There are 3 types of SQL statements:
a) DDL (Data Definition Language): It is used to define the database structure such as tables. It includes three statements such as CREATE, ALTER, and DROP.
Some of the DDL Commands are listed below:
CREATE: It is used for creating the table.
CREATE TABLE table_name column_name1 data_type( size ), column_name2 data_type( size ), column_name3 data_type( size ), |
ALTER: The ALTER table is used for modifying the existing table object in the database.
ALTER TABLE table_name ADD column_name datatype |
OR
ALTER TABLE table_name DROP COLUMN column_name |
b) DML (Data Manipulation Language): These statements are used to manipulate the data in records. Commonly used DML statements are INSERT, UPDATE, and DELETE.
The SELECT statement is used as a partial DML statement, used to select all or relevant records in the table.
c) DCL (Data Control Language): These statements are used to set privileges such as GRANT and REVOKE database access permission to the specific user.
Q #4) How do we use the DISTINCT statement? What is its use?
Answer: The DISTINCT statement is used with the SELECT statement. If the record contains duplicate values then the DISTINCT statement is used to select different values among duplicate records.
Syntax:
SELECT DISTINCT column_name(s) FROM table_name; |
Q #5) What are different Clauses used in SQL?
Answer:
WHERE Clause: This clause is used to define the condition, extract and display only those records which fulfill the given condition.
Syntax:
SELECT column_name(s) FROM table_name WHERE condition; |
GROUP BY Clause: It is used with SELECT statement to group the result of the executed query using the value specified in it. It matches the value with the column name in tables and groups the end result accordingly.
Syntax:
SELECT column_name(s) FROM table_name GROUP BY column_name; |
HAVING clause: This clause is used in association with the GROUP BY clause. It is applied to each group of results or the entire result as a single group. It is much similar as WHERE clause but the only difference is you cannot use it without GROUP BY clause
Syntax:
SELECT column_name(s) FROM table_name GROUP BY column_name HAVING condition; |
ORDER BY clause: This clause is used to define the order of the query output either in ascending (ASC) or in descending (DESC). Ascending (ASC) is set as the default one but descending (DESC) is set explicitly.
Syntax:
SELECT column_name(s) FROM table_name WHERE condition ORDER BY column_name ASC | DESC ; |
USING clause: USING clause comes in use while working with SQL JOIN. It is used to check equality based on columns when tables are joined. It can be used instead of the ON clause in JOIN.
Syntax:
SELECT column_name(s) FROM table_name JOIN table_name USING (column_name); |
Q #6) Why do we use SQL constraints? Which constraints we can use while creating a database in SQL?
Answer: Constraints are used to set the rules for all records in the table. If any constraints get violated then it can abort the action that caused it.
Constraints are defined while creating the database itself with the CREATE TABLE statement or even after the table is created once with the ALTER TABLE statement.
There are 5 major constraints are used in SQL, such as
- NOT NULL: That indicates that the column must have some value and cannot be left NULL.
- UNIQUE: This constraint is used to ensure that each row and column has a unique value and no value is being repeated in any other row or column.
- PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE constraints such as on one or the combination of more than one column to identify the particular record with a unique identity.
- FOREIGN KEY: It is used to ensure the referential integrity of data in the table. It matches the value in one table with another using the PRIMARY KEY.
- CHECK: It ensures whether the value in columns fulfills the specified condition.
Q #7) What are different JOINS used in SQL?
Answer:
4 major types of Joins are used while working on multiple tables in SQL databases:
INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables when it has at least one matching column.
Syntax:
SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON column_name1=column_name2; |
For Example,
In this example, we have a table Employee with the following data:
The second table's name is Joining.
Enter the following SQL statement:
SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee INNER JOIN Joining ON Employee.Emp_id = Joining.Emp_id ORDER BY Employee.Emp_id; |
There will be 4 records selected. Results are:
Employee and Orders tables have a matching customer_id value.
LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from the LEFT table and its matched rows from a RIGHT table.
Syntax:
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON column_name1=column_name2; |
For Example,
In this example, we have a table Employee with the following data:
The second table's name is Joining.
Enter the following SQL statement:
SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee LEFT OUTER JOIN Joining ON Employee.Emp_id = Joining.Emp_id ORDER BY Employee.Emp_id; |
There will be 4 records selected. You will see the following results:
RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT table and its matched rows from the LEFT table.
Syntax:
SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON column_name1=column_name2; |
For Example,
In this example, we have a table Employee with the following data:
The second table's name is Joining.
Enter the following SQL statement:
SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee RIGHT JOIN Joining ON Employee.Emp_id = Joining.Emp_id ORDER BY Employee.Emp_id; |
Output:
Emp_id | Joining_Date |
---|---|
E0012 | 2016/04/18 |
E0013 | 2016/04/19 |
E0014 | 2016/05/01 |
FULL JOIN (FULL OUTER JOIN): This joins returns all results when there is a match either in the RIGHT table or in the LEFT table.
Syntax:
SELECT column_name(s) FROM table_name1 FULL OUTER JOIN table_name2 ON column_name1=column_name2; |
For Example,
In this example, we have a table Employee with the following data:
The second table's name is Joining.
Enter the following SQL statement:
SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee FULL OUTER JOIN Joining ON Employee.Emp_id = Joining.Emp_id ORDER BY Employee.Emp_id; |
There will be 8 records selected. These are the results that you should see.
Q #8) What are transactions and their controls?
Answer: A transaction can be defined as the sequence task that is performed on databases in a logical manner to gain certain results. Operations like Creating, updating, deleting records performed in the database come from transactions.
In simple words, we can say that a transaction means a group of SQL queries executed on database records.
There are 4 transaction controls such as
- COMMIT: It is used to save all changes made through the transaction.
- ROLLBACK: It is used to roll back the transaction. All changes made by the transaction are reverted back and the database remains as before.
- SET TRANSACTION: Set the name of the transaction.
- SAVEPOINT: It is used to set the point where the transaction is to be rolled back.
Q #9) What are the properties of the transaction?
Answer: Properties of the transaction are known as ACID properties. These are:
- Atomicity: Ensures the completeness of all transactions performed. Checks whether every transaction is completed successfully or not. If not, then the transaction is aborted at the failure point and the previous transaction is rolled back to its initial state as changes are undone.
- Consistency: Ensures that all changes made through successful transactions are reflected properly on the database.
- Isolation: Ensures that all transactions are performed independently and changes made by one transaction are not reflected on others.
- Durability: Ensures that the changes made in the database with committed transactions persist as it is even after a system failure.
Q #10) How many Aggregate functions are available in SQL?
Answer: SQL Aggregate functions determine and calculate values from multiple columns in a table and return a single value.
There are 7 aggregate functions in SQL:
- AVG(): Returns the average value from specified columns.
- COUNT(): Returns number of table rows.
- MAX(): Returns the 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.
Q #11) What are Scalar functions in SQL?
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 the upper case.
- LCASE(): Converts the specified field in lower case.
- MID(): Extracts and returns character from the text field.
- FORMAT(): Specifies the display format.
- LEN(): Specifies the length of the text field.
- ROUND(): Rounds up the decimal field value to a number.
Q #12) What are triggers?
Answer: 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.
Syntax:
CREATE TRIGGER name {BEFORE| AFTER } (event [ OR ..]} ON table_name [ FOR [EACH] {ROW|STATEMENT}] EXECUTE PROCEDURE functionname {arguments} |
Q #13) What is View in SQL?
Answer: A View can be defined as a virtual table that contains rows and columns with fields from one or more tables.
Syntax:
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition |
Q #14) How we can update the view?
Answer: SQL CREATE and REPLACE can be used for updating the view.
Execute the below query to update the created view.
Syntax:
CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition |
Q #15) Explain the working of SQL Privileges?
Answer: SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user environments. The administrator of the database can grant or revoke privileges to or from users of database objects by using commands like SELECT, INSERT, UPDATE, DELETE, ALL, etc.
GRANT Command: This command is used to provide database access to users other than the administrator.
Syntax:
GRANT privilege_name ON object_name TO {user_name| PUBLIC |role_name} [ WITH GRANT OPTION ]; |
In the above syntax, the GRANT option indicates that the user can grant access to another user too.
REVOKE command: This command is used to provide database deny or remove access to database objects.
Syntax:
REVOKE privilege_name ON object_name FROM {user_name| PUBLIC |role_name}; |
Q #16) How many types of Privileges are available in SQL?
Answer: There are two types of privileges used in SQL, such as
- System privilege: System privilege deals with the object of a particular type and provides users the right to perform one or more actions on it. These actions include performing administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.
- Object privilege: This allows to perform actions on an object or object of another user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE, INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.
Q #17) What is SQL Injection?
Answer: SQL Injection is a type of database attack technique where malicious SQL statements are inserted into an entry field of database in a way that once it is executed, the database is exposed to an attacker for the attack. This technique is usually used for attacking data-driven applications to have access to sensitive data and perform administrative tasks on databases.
For Example,
SELECT column_name(s) FROM table_name WHERE condition; |
Q #18) What is SQL Sandbox in SQL Server?
Answer: SQL Sandbox is a safe place in the SQL server environment where untrusted scripts are executed. There are 3 types of SQL sandbox:
- Safe Access Sandbox: Here a user can perform SQL operations such as creating stored procedures, triggers etc. but cannot have access to the memory as well as cannot create files.
- External Access Sandbox: Users can access files without having the right to manipulate the memory allocation.
- Unsafe Access Sandbox: This contains untrusted codes where a user can have access to memory.
Q #19) What is the difference between SQL and PL/SQL?
Answer: SQL is a Structured Query Language to create and access databases whereas PL/SQL comes with procedural concepts of programming languages.
Q #20) What is the difference between SQL and MySQL?
Answer: SQL is a Structured Query Language that is used for manipulating and accessing the relational database. On the other hand, MySQL itself is a relational database that uses SQL as the standard database language.
Q #21) What is the use of the NVL function?
Answer: NVL function is used to convert the null value to its actual value.
Q #22) What is the Cartesian product of the table?
Answer: The output of Cross Join is called 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.
Q #23) What do you mean by Subquery?
Answer: 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.
Q #24) How many row comparison operators are used while working with a subquery?
Answer: There are 3-row comparison operators that are used in subqueries such as IN, ANY and ALL.
Q #25) What is the difference between clustered and non-clustered indexes?
Answer: The differences between the two are as follows:
- One table can have only one clustered index but multiple non-clustered indexes.
- Clustered indexes can be read rapidly rather than non-clustered indexes.
- Clustered indexes store data physically in the table or view whereas, non-clustered indexes do not store data in the table as it has separate structure from the data row.
Q #26) What is the difference between DELETE and TRUNCATE?
Answer: The differences are:
- The basic difference in both is DELETE command is DML command and the TRUNCATE command is DDL.
- DELETE command is used to delete a specific row from the table whereas the TRUNCATE command is used to remove all rows from the table.
- We can use the DELETE command with WHERE clause but cannot use the TRUNCATE command with it.
Q #27) What is the difference between DROP and TRUNCATE?
Answer: TRUNCATE removes all rows from the table which cannot be retrieved back, DROP removes the entire table from the database and it also cannot be retrieved back.
Q #28) How to write a query to show the details of a student from Students table whose
name start with K?
Answer: Query:
SELECT * FROM Student WHERE Student_Name like ‘K%’; |
Here ‘like’ operator is used to perform pattern matching.
Q #29) What is the difference between Nested Subquery and Correlated Subquery?
Answer: Subquery within another subquery is called Nested Subquery. If the output of a subquery depends on column values of the parent query table then the query is called Correlated Subquery.
SELECT adminid(SELEC Firstname+ ' ' +Lastname FROM Employee WHERE empid=emp. adminid) AS EmpAdminId FROM Employee; |
The result of the query is the details of an employee from the Employee table.
Q #30) What is Normalization? How many Normalization forms are there?
Answer: Normalization is used to organize the data in such a manner that data redundancy will never occur in the database and avoid insert, update and delete anomalies.
There are 5 forms of Normalization:
- First Normal Form (1NF): It removes all duplicate columns from the table. It creates a table for related data and identifies unique column values.
- First Normal Form (2NF): Follows 1NF and creates and places data subsets in an individual table and defines the relationship between tables using the primary key.
- Third Normal Form (3NF): Follows 2NF and removes those columns which are not related through the primary key.
- Fourth Normal Form (4NF): Follows 3NF and does not define multi-valued dependencies. 4NF is also known as BCNF.
Q #31) What is a Relationship? How many types of Relationships are there?
Answer: The relationship can be defined as the connection between more than one table in the database.
There are 4 types of relationships:
- One to One Relationship
- Many to One Relationship
- Many to Many Relationship
- One to Many Relationship
Q #32) What do you mean by Stored Procedures? How do we use it?
Answer: A stored procedure is a collection of SQL statements that can be used as a function to access the database. We can create these stored procedures earlier before using it and can execute them wherever required by applying some conditional logic to it. Stored procedures are also used to reduce network traffic and improve performance.
Syntax:
CREATE Procedure Procedure_Name ( //Parameters ) AS BEGIN SQL statements in stored procedures to update /retrieve records END |
Q #33) State some properties of Relational databases?
Answer: Properties are as follows:
- In relational databases, each column should have a unique name.
- The sequence of rows and columns in relational databases is insignificant.
- All values are atomic and each row is unique.
Q #34) What are Nested Triggers?
Answer: Triggers may implement data modification logic by using INSERT, UPDATE, and DELETE statements. These triggers that contain data modification logic and find other triggers for data modification are called Nested Triggers.
Q #35) What is a Cursor?
Answer: A cursor is a database object which is used to manipulate data in a row-to-row manner.
Cursor follows steps as given below:
- Declare Cursor
- Open Cursor
- Retrieve row from the Cursor
- Process the row
- Close Cursor
- Deallocate Cursor
Q #36) What is Collation?
Answer: Collation is a set of rules that check how the data is sorted by comparing it. Such as character data is stored using correct character sequence along with case sensitivity, type, and accent.
Q #37) What do we need to check in Database Testing?
Answer: In Database testing, the following thing is required to be tested:
- Database connectivity
- Constraint check
- Required application field and its size
- Data Retrieval and processing with DML operations
- Stored Procedures
- Functional flow
Q #38) What is Database White Box Testing?
Answer: Database White Box testing involves:
- Database Consistency and ACID properties
- Database triggers and logical views
- Decision Coverage, Condition Coverage, and Statement Coverage
- Database Tables, Data Model, and Database Schema
- Referential integrity rules
Q #39) What is Database Black Box Testing?
Answer: Database Black Box testing involves:
- Data Mapping
- Data stored and retrieved
- Use of Black Box testing techniques such as Equivalence Partitioning and Boundary Value Analysis (BVA)
Q #40) What are Indexes in SQL?
Answer: The index can be defined as the way to retrieve the data more quickly. We can define indexes using CREATE statements.
Syntax:
CREATE INDEX index_name ON table_name (column_name) |
Further, we can also create a Unique Index using the following syntax:
CREATE UNIQUE INDEX index_name ON table_name (column_name) |
UPDATE: We have added few more short questions for practice.
Q #41) What does SQL stand for?
Answer: SQL stands for Structured Query Language.
Q #42) How to select all records from the table?
Answer: To select all the records from the table we need to use the following syntax:
Select * from table_name; |
Q #43) Define join and name different types of joins?
Answer: Join keyword is used to fetch data from two or more related 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.
Q #44) What is the syntax to add a record to a table?
Answer: To add a record in a table INSERT syntax is used.
For Example,
INSERT into table_name VALUES (value1, value2..); |
Q #45) How do you add a column to a table?
Answer: To add another column in the table, use the following command:
ALTER TABLE table_name ADD (column_name); |
Q #46) Define the SQL DELETE statement.
Answer: DELETE is used to delete a row or rows from a table based on the specified condition.
The basic syntax is as follows:
DELETE FROM table_name WHERE <Condition> |
Q #47) Define COMMIT?
Answer: COMMIT saves all changes made by DML statements.
Q #48) What is the Primary key?
Answer: A Primary key is a column whose values uniquely identify every row in a table. Primary key values can never be reused.
Q #49) What are Foreign keys?
Answer: When a table’s primary key field is added to related tables in order to create the common field which relates the two tables, it called a foreign key in other tables. Foreign key constraints enforce referential integrity.
Q #50) What is CHECK Constraint?
Answer: A CHECK constraint is used to limit the values or type of data that can be stored in a column. They are used to enforce domain integrity.
Q #51) Is it possible for a table to have more than one foreign key?
Answer: Yes, a table can have many foreign keys but only one primary key.
Q #52) What are the possible values for the BOOLEAN data field?
Answer: For a BOOLEAN data field, two values are possible: -1(true) and 0(false).
Q #53) What is a stored procedure?
Answer: A stored procedure is a set of SQL queries that can take input and send back output.
Q #54) What is identity in SQL?
Answer: An identity column in where SQL automatically generates numeric values. We can define a start and increment value of the identity column.
Q #55) What is Normalization?
Answer: 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 the relationship between them.
Q #56) What is a Trigger?
Answer: The Trigger allows us to execute a batch of SQL code when table event occurs (INSERT, UPDATE or DELETE commands are executed against a specific table).
Q #57) How to select random rows from a table?
Answer: Using a SAMPLE clause we can select random rows.
For Example,
SELECT * FROM table_name SAMPLE(10); |
Q #58) Which TCP/IP port does SQL Server run?
Answer: By default SQL Server runs on port 1433.
Q #59) Write a SQL SELECT query that only returns each name only once from a table?
Answer: To get the result as each name only once, we need to use the DISTINCT keyword.
SELECT DISTINCT name FROM table_name; |
Q #60) Explain DML and DDL?
Answer: DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are DML statements.
DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL statements.
Q #61) Can we rename a column in the output of the SQL query?
Answer: Yes, using the following syntax we can do this.
SELECT column_name AS new_name FROM table_name; |
Q #62) Give the order of SQL SELECT?
Answer: Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. Only the SELECT and FROM clauses are mandatory.
Q #63) Suppose a Student column has two columns, Name and Marks. How to get names and marks of the top three students.
Answer: SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM Students s2 WHERE s1.marks = s2.marks)
Q #64) What is SQL comments?
Answer: SQL comments can be inserted by adding two consecutive hyphens (–).
Q #65) Difference between TRUNCATE, DELETE and DROP commands?
Answer:
- DELETE removes some or all rows from a table based on the condition. It can be rolled back.
- TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The operation cannot be rolled back
- DROP command removes a table from the database completely.
Q #66) What are the properties of a transaction?
Answer: Generally, these properties are referred to as ACID properties. They are:
- Atomicity
- Consistency
- Isolation
- Durability.
Q #67) What do you mean by ROWID?
Answer: It’s an 18 character long pseudo column attached with each row of a table.
Q #68) Define UNION, MINUS, UNION ALL, INTERSECT?
Answer:
- 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.
Q #69) What is a transaction?
Answer: A transaction is a sequence of code that runs against a database. It takes the database from one consistent state to another.
Q #70) What is the difference between UNIQUE and PRIMARY KEY constraints?
Answer: The differences are as follows:
- A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys.
- The primary key cannot contain Null values whereas the Unique key can contain Null values.
Q #71) What is a composite primary key?
Answer: The primary key created on more than one column is called composite primary key.
Q #72) What is an Index?
Answer: An Index is a special structure associated with a table to speed up the performance of queries. The index can be created on one or more columns of a table.
Q #73) What is the Subquery?
Answer: A Subquery is a subset of select statements whose return values are used in filtering conditions of the main query.
Q #74) What do you mean by query optimization?
Answer: Query optimization is a process in which a database system compares different query strategies and select the query with the least cost.
Q #75) What is Collation?
Answer: Set of rules that define how data is stored, how case-sensitivity and Kana character can be treated etc.
Q #76) What is Referential Integrity?
Answer: 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.
Q #77) What is the Case function?
Answer: Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions and returns one of the multiple possible result expressions.
Q #78) Define a temp table?
Answer: A temp table is a temporary storage structure to store the data temporarily.
Q #79) How can we avoid duplicating records in a query?
Answer: By using the DISTINCT keyword, duplication of records in a query can be avoided.
Q #80) Explain the difference between Rename and Alias?
Answer: Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column.
Q #81) What is a View?
Answer: A view is a virtual table that contains data from one or more tables. Views restrict data access of the table by selecting only required values and make complex queries easy.
Q #82) What are the advantages of Views?
Answer: Advantages of Views are:
- 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.
Q #83) List the various privileges that a user can grant to another user?
Answer: SELECT, CONNECT, RESOURCES.
Q #84) What is schema?
Answer: A schema is a collection of database objects of a User.
Q #85) What is a Table?
Answer: A table is the basic unit of data storage in the database management system. Table data is stored in rows and columns.
Q #86) Does View contain Data?
Answer: No, Views are virtual structures.
Q #87) Can a View based on another View?
Answer: Yes, A View is based on another View.
Q #88) What is the difference between the HAVING clause and WHERE clause?
Answer: Both specify a search condition but Having clause is used only with the SELECT statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaved like WHERE clause only.
Q #89) What is the difference between Local and Global temporary tables?
Answer: If defined inside a compound statement a local temporary table exists only for the duration of that statement but a global temporary table exists permanently in the DB but its rows disappear when the connection is closed.
Q #90) What is CTE?
Answer: A CTE or common table expression is an expression that contains temporary result set which is defined in a SQL statement.
No comments:
Post a Comment