Thursday, May 15, 2014

Security Testing of Web Applications

An approach for Security Testing of Web Applications

--------------------------------------------------------------------------------------------
Introduction
As more and more vital data is stored in web applications and the number of transactions on the web increases, proper security testing of web applications is becoming very important. Security testing is the process that determines that confidential data stays confidential (i.e. it is not exposed to individuals/ entities for which it is not meant) and users can perform only those tasks that they are authorized to perform (e.g. a user should not be able to deny the functionality of the web site to other users, a user should not be able to change the functionality of the web application in an unintended way etc.).
Some key terms used in security testing
Before we go further, it will be useful to be aware of a few terms that are frequently used in web application security testing:
What is “Vulnerability”?
This is a weakness in the web application. The cause of such a “weakness” can be bugs in the application, an injection (SQL/ script code) or the presence of viruses.

What is “URL manipulation”?
Some web applications communicate additional information between the client (browser) and the server in the URL. Changing some information in the URL may sometimes lead to unintended behavior by the server.
What is “SQL injection”?
This is the process of inserting SQL statements through the web application user interface into some query that is then executed by the server.
What is “XSS (Cross Site Scripting)”?
When a user inserts HTML/ client-side script in the user interface of a web application and this insertion is visible to other users, it is called XSS.
What is “Spoofing”?
The creation of hoax look-alike websites or emails is called spoofing.
Security testing approach:
In order to perform a useful security test of a web application, the security tester should have good knowledge of the HTTP protocol. It is important to have an understanding of how the client (browser) and the server communicate using HTTP. Additionally, the tester should at least know the basics of SQL injection and XSS. Hopefully, the number of security defects present in the web application will not be high. However, being able to accurately describe the security defects with all the required details to all concerned will definitely help.
1. Password cracking:
The security testing on a web application can be kicked off by “password cracking”. In order to log in to the private areas of the application, one can either guess a username/ password or use some password cracker tool for the same. Lists of common usernames and passwords are available along with open source password crackers. If the web application does not enforce a complex password (e.g. with alphabets, number and special characters, with at least a required number of characters), it may not take very long to crack the username and password.
If username or password is stored in cookies without encrypting, attacker can use different methods to steal the cookies and then information stored in the cookies like username and password.
For more details see article on “Website cookie testing”.
2. URL manipulation through HTTP GET methods:
The tester should check if the application passes important information in the querystring. This happens when the application uses the HTTP GET method to pass information between the client and the server. The information is passed in parameters in the querystring. The tester can modify a parameter value in the querystring to check if the server accepts it.
Via HTTP GET request user information is passed to server for authentication or fetching data. Attacker can manipulate every input variable passed from this GET request to server in order to get the required information or to corrupt the data. In such conditions any unusual behavior by application or web server is the doorway for the attacker to get into the application.
3. SQL Injection:
The next thing that should be checked is SQL injection. Entering a single quote (‘) in any textbox should be rejected by the application. Instead, if the tester encounters a database error, it means that the user input is inserted in some query which is then executed by the application. In such a case, the application is vulnerable to SQL injection.
SQL injection attacks are very critical as attacker can get vital information from server database. To check SQL injection entry points into your web application, find out code from your code base where direct MySQL queries are executed on database by accepting some user inputs.
If user input data is crafted in SQL queries to query the database, attacker can inject SQL statements or part of SQL statements as user inputs to extract vital information from database. Even if attacker is successful to crash the application, from the SQL query error shown on browser, attacker can get the information they are looking for. Special characters from user inputs should be handled/escaped properly in such cases.
4. Cross Site Scripting (XSS):
The tester should additionally check the web application for XSS (Cross site scripting). Any HTML e.g. <HTML> or any script e.g. <SCRIPT> should not be accepted by the application. If it is, the application can be prone to an attack by Cross Site Scripting.
Attacker can use this method to execute malicious script or URL on victim’s browser. Using cross-site scripting, attacker can use scripts like JavaScript to steal user cookies and information stored in the cookies.
Many web applications get some user information and pass this information in some variables from different pages.
E.g.: http://www.examplesite.com/index.php?userid=123&query=xyz
Attacker can easily pass some malicious input or <script> as a ‘&query’ parameter which can explore important user/server data on browser.
Important: During security testing, the tester should be very careful not to modify any of the following:
  •  Configuration of the application or the server
  •  Services running on the server
  •  Existing user or customer data hosted by the application
Additionally, a security test should be avoided on a production system.
The purpose of the security test is to discover the vulnerabilities of the web application so that the developers can then remove these vulnerabilities from the application and make the web application and data safe from unauthorized actions.

Recommended reading:
-------------------------

Wednesday, May 14, 2014

Top 20 Penetration Testing Tools

Top 20 Penetration Testing Tools

---------------------------------------------------------

1) Metasploit 
Metasploit pentesting tool
This is the most advanced and popular Framework that can be used to for pen-testing. It is based on the concept of ‘exploit’ which is a code that can surpass the security measures and enter a certain system. If entered, it runs a ‘payload’, a code that performs operations on a target machine, thus creating the perfect framework for penetration testing.
It can be used on web applications, networks, servers etc. It has a command-line and a GUI clickable interface, works on Linux, Apple Mac OS X and Microsoft Windows. This is a commercial product, although there might be free limited trials available.
Download link: Metasploit Download

2) Wireshark

Wireshark logo
This is basically a network protocol analyzer –popular for providing the minutest details about your network protocols, packet information, decryption etc. It can be used on Windows, Linux, OS X, Solaris, FreeBSD, NetBSD, and many other systems. The information that is retrieved via this tool can be viewed through a GUI, or the TTY-mode TShark utility.  You can get your own free version of the tool from here.
Download link: Wireshark download

3) w3af

w3af4
W3afis a Web Application Attack and Audit Framework.
Some of the features are: fast HTTP requests, integration of web and proxy servers into the code, injecting payloads into various kinds of HTTP requests etc.
It has a command-line interface, works on Linux, Apple Mac OS X and Microsoft Windows.
All versions are free of charge to download.
Download link: w3af download

4) CORE Impact

CORE Impact
CORE Impact Pro can be used to test mobile device penetration, network/network devise penetration, password identification and cracking, etc. It has a command-line and a GUI clickable interface, works Microsoft Windows. This is one of the expensive tools in this line and all the information can be found at below page.
Download link: CORE Impact download

5) Back Track

Back Track
Back Track works only on Linux Machines. The new version is called Kali Linux. This is one of the best tools available for Packet sniffing and injecting. An expertise in TCP/IP protocol and networking are key to succeed using this tool. For information and to download a free copy, visit below page.
Download link: Back Track download

6) Netsparker

Netsparker logo
Netsparker comes with a robust web application scanner that will identify vulnerabilities, suggest remedial action etc. This tool can also help exploit SQL injection and LFI (local file induction). It has a command-line and GUI interface, works only on Microsoft Windows. This is a commercial product, although there might be free limited trials available at below page.
Download link: Netsparker download

7) Nessus

Nessus logo
Nessus also is a scanner and one that needs to be watched out for. It is one of the most robust vulnerability identifier tools available. It specializes in compliance checks, Sensitive data searches, IPs scan, website scanning etc. and aids in finding the ‘weak-spots’. It works on most of the environments.
Download link: Nessus download

8) Burpsuite

Burpsuite logo
Burp suite is also essentially a scanner (with a limited “intruder” tool for attacks), although many security testing specialists swear that pen-testing without this tool is unimaginable. The tool is not free, but very cost effective. Take a look at it on below download page. It mainly works wonders with intercepting proxy, crawling content and functionality, web application scanning etc.  You can use this on Windows, Mac OS X and Linux environments.
Download link: Burp suite download

9) Cain & Abel

If cracking encrypted passwords or network keys is what you need, then Cain& Abel is the tool for you. It uses network sniffing, Dictionary, Brute-Force and Cryptanalysis attacks, cache uncovering and routing protocol analysis methods to achieve this. Check out information about this free to use tool at below page. This is exclusively for Microsoft operating systems.
Download link: Cain & Abel download

10) Zed Attack Proxy (ZAP)

Zed Attack Proxy logo
ZAP is a completely free to use, scanner and security vulnerability finder for web applications. ZAP includes Proxy intercepting aspects, variety of scanners, spiders etc. It works on most platforms and the more information can be obtained from below page.
Download link: ZAP download

11) Acunetix

Acunetix logo
Acunetix is essentially a web vulnerability scanner targeted at web applications. It provides SQL injection, cross site scripting testing, PCI compliance reports etc. along with identifying a multitude of vulnerabilities. While this is among the more ‘pricey’ tools, a limited time free trial version can be obtained at below page.
Download link: Acunetix download

12) John The Ripper

John The Ripper logo
Another password cracker in line is, John the Ripper. This tool works on most of the environments, although it’s primarily for UNIX systems. It is considered one of the fastest tools in this genre. Password hash code and strength-checking code are also made available to be integrated to your own software/code which I think is very unique. This tool comes in a pro and free form. Check out its site to obtain the software on this page.
Download link: John the Ripper download

13) Retina

Retina logo
As opposed to a certain application or a server, Retina targets the entire environment at a particular company/firm. It comes as a package called Retina Community. It is a commercial product and is more of a vulnerability management tool more than a pen-testing tool. It works on having scheduled assessments and presenting results. Check out more about this package at below page.
Download link: Retina download

14) Sqlmap

Sqlmap pen test logo
Sqlmap is again a good open source pen testing tool. This tool is mainly used for detecting and exploiting SQL injection issues in an application and hacking over of database servers. It comes with command-line interface. Platform: Linux, Apple Mac OS X and Microsoft Windows are supported platforms. All versions of this tool are free for download.
Download link: Sqlmap download

15) Canvas

Canvas pen test logo
Immunity’s CANVAS is a widely used tool that contains more than 400 exploits and multiple payload options. It renders itself useful for web applications, wireless systems, networks etc. It has a command-line and GUI interface, works on Linux, Apple Mac OS X and Microsoft Windows. It is not free of charge and can more information can be found at below page.
Download link: Canvas download

16) Social Engineer Toolkit

Social Engineer Toolkit logo
The Social-Engineer Toolkit (SET) is a unique tool in terms that the attacks are targeted at the human element than on the system element. It has features that let you send emails, java applets, etc containing the attack code. It goes without saying that this tool is to be used very carefully and only for ‘white-hat’ reasons.  It has a command-line interface, works on Linux, Apple Mac OS X and Microsoft Windows. It is open source and can be found at below page.
Download link: SET download

17) Sqlninja

Sqlninja penetration testing
Sqlninja, as the name indicates is all about taking over the DB server using SQL injection in any environment. This product by itself claims to be not so stable its popularity indicates how robust it is already with the DB related vulnerability exploitation. It has a command-line interface, works on Linux, Apple Mac OS X and not on Microsoft Windows. It is open source and can be found at this page.
Download link: Sqlninja download

18) Nmap

Nmap logo
“Network Mapper” though not necessarily a pen-testing tool, it is a must-have for the ethical hackers. This is a very popular tool that predominantly aids in understanding the characteristics of any target network. The characteristics can include: host, services, OS, packet filters/firewalls etc.  It works on most of the environments and is open sourced.
Download link: Nmap download

19) BeEF

BeEF  pen testing tool
BeEF is short for The Browser Exploitation Framework. It is a penetration testing tool that focuses on the web browser- what this means is that, it takes advantage of the fact that an open web-browser is the window(or crack) into a target system and designs its attacks to go on from this point on . It has a GUI interface, works on Linux, Apple Mac OS X and Microsoft Windows. It is open source and can be found at this page.
Download link: BeEF download

20) Dradis

Dradis pen testing tool
Dradis is an open source framework (a web application) that helps with maintaining the information that can be shared among the participants of a pen-test. The information collected helps understand what is done and what needs to be done. It achieves this purpose by the means of plugins to read and collect data from network scanning tools, like Nmap, w3af, Nessus, Burp Suite, Nikto and many more.  It has a GUI interface, works on Linux, Apple Mac OS X and Microsoft Windows. It is open source and can be found at this page.
Download link: Dradis download
**************
The above is a huge list of many tools but that is not all. There are many more Pen test tools that are gaining momentum in the recent times. They are:
21) Ettercap: A network and host analysis tool that provides sniffing and protocol dissection among other things. More info here.
22) Hydra: A password cracker – more details here.
23) Veracode: Works with the code development process to ensure security and minimize vulnerabilities at the source level. Check here.
24) SATAN: It stands for: Security Administrator Tool for Analyzing Networks. This tool is used on network hosts for collecting and reporting security/vulnerability related statistics. Download here.
25) SHODAN: It is a search engine that lets you search for computers/devices on the internet based on various parameters like city, country hostname, OS etc. Using the Shodan Exploits you can search for known vulnerabilities and exploits. Download here.
26) Aircrack-ng: Captures data packets and uses the same for recovery of 802.11 WEP and WPA-PSK keys. Download here.
27) Arachni: A Ruby framework that helps in analyzing web application security. It performs a meta analysis on the HTTP responses it receives during an audit process and presents various insights into how secure the application is. Download here.
28) PunkSPIDER(scanner powered by PunkSCAN): Security scanners and what is unique is that this tool performs a range of multiple scans at once on web applications thus surpassing the existing tools in the market. You can download the source code directly from Bitbucket at this page.
29) IBM AppScan:  As the name indicates this is a scanner that identifies problem areas and suggests remedial actions. Download here.
30) Nagios:  This is software when used will monitor the entire environment including servers, applications, network – the entire infrastructure and alert when a potential problem is detected.Download here.
31) Nikto:  A scanner that caters to web servers specially to detect outdated software configurations, invalid data and/or CGIs etc.Download here.
32) WebScarabNG: This tool use the http/https requests between the browser and the server to understand, capture and sometimes modify the parameters that are part of the communication between the two parties. Download here.
33) Maltego: This is a unique tool that focuses on showing/highlighting the relationships between people, sites, infrastructure etc. in order to identify inconsistent/incorrect connections. Download here.
34) IronWASP: A customizable scanner creator for web applications using python/ruby scripting. Download here.
35) HconSTF: Using this tool you can create your own web exploits, decoys that you can use to exploit vulnerabilities in the areas of passwords, databases, network etc. Download here.
36) OpenVAS: Stands for open vulnerabilities assessment system. Well, the name says it all. For more info, check here.
37) Secunia PSI: It is a personal software inspector that will keep your system secure when installed. Try it here.
We hope this piques your interest in the pen-testing field and provides you with the necessary information to get started. A word of caution: remember to wear your ‘White-hat’ because with great power comes great responsibility- and we don’t want to be the ones to misuse it. :-)

Over to you:

Have you performed pen-testing before? If yes, please share your experiences. Which penetration testing tool do you use? If we missed any good tool in this list please let us know in the comments below.

Introduction to Penetration Testing

What is a penetration test?

What is penetration testing? Penetration testing, often called “pentesting”,“pen testing”, or “security testing”, is the practice of attacking your own or your clients’ IT systems in the same way a hacker would to identify security holes. Of course, you do this without actually harming the network. The person carrying out a penetration test is called a penetration tester or pentester.
                                               (or)
What is Penetration Testing?
It’s the method of testing where the areas of weakness in software systems in terms of security are put to test to determine, if ‘weak-point’ is indeed one, that can be broken into or not.
Performed for: Websites/Servers/Networks
How is it performed?
Step #1. It starts with a list of Vulnerabilities/potential problem areas that would cause a security breach for the systems.
Step #2. If possible, this list of items has to be ranked in the order of priority/criticality
Step #3. Devise penetration tests that would work (attack your system) from both within the network and outside (externally) to determine if you can access data/network/server/website unauthorized.
Step #4. If the unauthorized access is possible, the system has to be corrected and the series of steps need to be re-run until the problem area is fixed.
Who performs Pen-testing?
Testers/ Network specialists/ Security Consultants
Note: it is important to note that pen-testing is not the same as vulnerability testing. The intention of vulnerability testing is just to identify potential problems, whereas pen-testing is to attach those problems.
Good news is, you do not have to start the process by yourself – you have a number of tools already in the market.  Why tools, you ask?
  • Even though you design the test on what to attack and how, you can leverage a lot of tools that are available in the market to hit the problem areas and collect data quickly that enables effective security analysis of the system.
Before we look into the details of the tools, what they do, where can you get them, etc. , I would like to point out that the tools you use for pen-testing can be classified into two kinds – In simple words they are: scanners and attackers. This is because; by definition pen-testing is exploiting the weak spots. So there are some software/tools that will show you the weak spots, some that show and attack. Literally speaking, the ‘show-ers’ are not pen-testing tools but they are inevitable for its success.

see the below video:
https://www.youtube.com/watch?v=b7jW9X9UqiY


BackTrack 4: Security with Penetration Testing Methodology:


http://www.packtpub.com/article/backtrack4-security-penetration-testing-methodology





Sunday, May 4, 2014

Database Testing


1. What is store procedure, what is the optimized way of calling a store procedure from .sql file or from the database itself?
Stored procedures allow a lot more flexibility offering capabilities such as conditional logic. Second, because stored procedures are stored within the DBMS, bandwidth and execution time are reduced. This is because a single stored procedure can execute a complex set of SQL statements.
Syntax:
create procedure SHOW_SUPPLIERS
as
select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
from SUPPLIERS, COFFEES
where SUPPLIERS.SUP_ID = COFFEES.SUP_ID
order by SUP_NAME
2. What is Normalization?
Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
The Normal Forms
The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you’ll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen and won’t be discussed in this article.
Before we begin our discussion of the normal forms, it’s important to point out that they are guidelines and guidelines only. Occasionally, it becomes necessary to stray from them to meet practical business requirements. However, when variations take place, it’s extremely important to evaluate any possible ramifications they could have on your system and account for possible inconsistencies. That said, let’s explore the normal forms.
First Normal Form (1NF)
First normal form (1NF) sets the very basic rules for an organized database:
* Eliminate duplicative columns from the same table.
* Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).
Second Normal Form (2NF)
Second normal form (2NF) further addresses the concept of removing duplicative data:
* Meet all the requirements of the first normal form.
* Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
* Create relationships between these new tables and their predecessors through the use of foreign keys.
Third Normal Form (3NF)
Third normal form (3NF) goes one large step further:
* Meet all the requirements of the second normal form.
* Remove columns that are not dependent upon the primary key.
Fourth Normal Form (4NF)
Finally, fourth normal form (4NF) has one additional requirement:
* Meet all the requirements of the third normal form.
* A relation is in 4NF if it has no multi-valued dependencies.
Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.
3. What is composite primary key?
Primary key is simply a primary key made up of more than one column. This is also known as a concatenated key.
4. Does a table contain two primary keys?
No
5. How to find the Minimum Salary?
Select Min (Salary) From Employee
6. How to find the Second Minimum Salary?
Select Salary from Employee where Salary > (select Min (Salary) from Employee);
7. How to find the Maximum Salary?
Select Max (Salary) From Employee
8. How to find the Second Maximum Salary?
Select Salary from Employee where Salary < (select Max (Salary) from Employee);
Or
Replace ‘n’ with the number of Max level you want ex: 2 (it displays the second highest).
Select a.Salary from emp a where &n= (Select count(Distinct b.salary)) from emp b where a.sal<=b.sal.
9. What does u test for in database testing other than data integrity (insert, delete, update?)Data Integrity Testing: Once a value undergoes any of the changes like (Update/Delete/Insert) the database should be verified for the changes performed on related entities i.e., Foreign Key/Primary Key and all dependent entities.
Store Procedure Testing: Every SP is to be tested separately for its functionality Based on Separate functions it performs. SP need to be broken up into Actions Items based on Functions and then each action item needs to be tested separately as the results of Complete SP. The following are to be considered.
a. The number of arguments being passed.
b. The data type of each of the arguments being passed.
c. The Order of the arguments being passed.
d. The return value.
e. The Data type of the return value.
Based on these you can write both positive and negative test cases.
Type Testing: Verifying the Data types. Often the data types chosen by developers are not the same as suggested by DBA. Ex: Phone (Num/Text), Description (Large Text).
Data Size Testing: Data size testing is often done only at the front end during the Unit Testing, but it is essential to perform it at back end separately.
Event Driven Item Testing: Event Driven Actions (Triggers or Scheduled Actions) needs to be tested based on two parameters.
a. Events that trigger these actions
b. Actions performed by the above stated events.
Input Item Verification: This is the process of verification of the input items, Often it is seen that the input items (Text Box/RTB/Combo Box/Active-X controls) are tested for validation only at front end (Screen testing) but these are again to be tested with junk character values to confirm that they do not push in such characters which the databases Often misrepresent or Replace with other characters.
10. What is a trigger? – What are different Types of Triggers?
Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database.
triggers that run implicitly when an INSERT, UPDATE, or DELETE statement is issued against the associated table or, in some cases, against a view, or when database system actions occur.
Syntax:
CREATE TRIGGER trig1
AFTER INSERT ON T4
REFERENCING NEW AS newRow
FOR EACH ROW
WHEN (newRow.a <= 10)
BEGIN
INSERT INTO T5 VALUES(:newRow.b, :newRow.a);
END trig1;
Using the options listed previously, you can create four types of row and statement triggers:
* BEFORE statement trigger
Before executing the triggering statement, the trigger action is run.
* BEFORE row trigger
Before modifying each row affected by the triggering statement and before checking appropriate integrity constraints, the trigger action is run, if the trigger restriction was not violated.
* AFTER row trigger
After modifying each row affected by the triggering statement and possibly applying appropriate integrity constraints, the trigger action is run for the current row provided the trigger restriction was not violated. Unlike BEFORE row triggers, AFTER row triggers lock rows.
* AFTER statement trigger
After executing the triggering statement and applying any deferred integrity constraints,
11. What is a view? – If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specific users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.
CREATE VIEW vpres AS select * from table
SELECT last_name, first_name, city, state FROM president;
12. What is an Index? – When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.
Syntax: If we want to create an index on both City and Country, we would type in,
CREATE INDEX IDX_CUSTOMER_LOCATION
on CUSTOMER (City, Country)

13. What are the types of indexes available with SQL Server? – There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered.
14. What is the basic difference between clustered and a non-clustered index? – The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.
15. What are cursors? – Well cursors help us to do an operation on a set of data that we retrieve by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retrieval one by one and remove rows which have duplicate values.
16. When do we use the UPDATE_STATISTICS command? – This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
17. Which TCP/IP port does SQL Server run on? – SQL Server runs on port 1433 but we can also change it for better security.
18. From where can you change the default port? - From the Network Utility TCP/IP properties –> Port number. Both on client and the server.
19. Can you tell me the difference between DELETE, TRUNCATE and Drop commands? Delete command removes the rows from a table based on the condition that we provide with a WHERE clause.
Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.
DROP TABLE removes a table. All table data and the table definition are removed.
20. Can we use Truncate command on a table which is referenced by FOREIGN KEY? No. We cannot use Truncate command on a table with Foreign Key because of referential integrity.
21. What is the use of DBCC commands? – DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
22. Can you give me some DBCC command options?(Database consistency check) – DBCC CHECKDB – Ensures that tables in the db and the indexes are correctly linked. and DBCC CHECKALLOC – To check that all pages in a db are correctly allocated. DBCC SQLPERF – It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP – Checks all tables file group for any damage.
23. What command do we use to rename a db? – sp_renamedb ‘oldname’ , ‘newname’
24. Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases? – In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.
25. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? - HAVING CLAUSE is used for evaluating a condition with an aggregate function i.e, Group By.
WHERE CLAUSE is used for general conditions.
26. What do you mean by COLLATION? – Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary – case insensitive and Binary.
27. What is a Join in SQL Server? – Join actually puts data from two or more tables into a single result set.
28. Can you explain the types of Joins that we can have with Sql Server? -JOIN is used to combine records from two tables or more in relational database. There are 3 types of Joins in SQL: CROSS JOIN, INNER JOIN, and OUTER JOIN. OUTER JOIN itself can be further divided into left OUTER JOIN, right OUTER JOIN and full OUTER JOIN.
Cross Join The CROSS JOIN list the tables to be joined without putting any filtering criteria.
Example of CROSS JOIN is as follows:
Select * from Employee CROSS JOIN Department.
Inner Join It takes all records from table1 and find matching records from table 2. If no matching is found, record in table1 will not be returned. One row of record will be returned for each matching found in table2. If 1 record in table1 match with 3 rows in table2, then 3 records will be returned. The following example will return records in resultset2.
Select * from Employee
Inner Join Department
ON Employee.DepartmentID= Department.DepartmentID
Outer Join
Left Outer Join 
it will return all records from table1 no matter it match any records in table2 or not. If no matching is found in table2, then each column in table2 will be returned as NULL values.
FOR Example: SELECT * FROM Employee
LEFT OUTER JOIN Department
ON Employee.DepartmentID = Department.DepartmentID
Right Outer Join all the records in table2 or Department table will be returned. For example: SELECT * FROM Employee
RIGHT OUTER JOIN Department
ON Employee.DepartmentID = Department.DepartmentID
Full Outer Join FULL OUTER JOIN is the combination of LEFT OUTER JOIN AND RIGHT OUTER JOIN. FULL JOIN shows results from both tables and missing match will be filled with NULL.SELECT * FROM Employee
FULL OUTER JOIN Department ON Employee.DepartmentID = Department.DepartmentID
29. Display the last 7 day records?
SELECT a.count,b.count as Rcount FROM $Table_links a, $Table_referer b WHERE
a.TO_DAYS(NOW()) – TO_DAYS(date) <= 7 && b.TO_DAYS(NOW()) – TO_DAYS(date) <= 7.
30. Display the records group by?The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at least one arithmetic operator appears in the SELECT statement. When that happens, we need to GROUP BY all the other selected columns, i.e., all columns except the one(s) operated on by the arithmetic operator.
Ex: SELECT store_name, SUM(Sales)
FROM Store_Information
GROUP BY store_name
Syntax for using Having clause.
Ex: SELECT store_name, SUM(sales)
FROM Store_Information
GROUP BY store_name
HAVING SUM(sales) > 1500
31. Display the records sort by?
Ex: SELECT Customer, Employee, Freight, ShipCountry ORDER BY ShipCountry
Ex: SELECT “column_name”
FROM “table_name”
[WHERE "condition"]
ORDER BY “column_name” [ASC, DESC]

32. What is a Foreign Key?A foreign key is a field (or fields) that points to the primary key of another table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the database are permitted.
SQL Server:
CREATE TABLE ORDERS
(Order_ID integer primary key,
Order_Date datetime,
Customer_SID integer references CUSTOMER(SID),
Amount double);