SQL interview Questions

Table Alias Vs Column Alias in sql server

Table Alias Vs Column Alias in sql server

Sql Server offers an option to give temporary alias name for the Table and it’s Column Names in the query. In that way we can give a meaning full alias to the Tables. And if two tables are joined both have the same column name, then we have to write two part column names i.e. [Table Name].[Column Name] otherwise Sql server gives an ambiguous column name error. If table name is too long it looks to awkward, so better give a alias name to the table and use this alias name in the Two part column name order to avoid ambiguity.
Table Alias Name. In this Query for Emp_Details Table the alias name specified is Emp in the FROM clause. Because of this we can access the table column names by prefixing Emp
SELECT Emp.Name, Emp.Phone FROM dbo.Emp_Details Emp

Column Name Alias. In this Query for Emp_Details Table the alias name specified is Emp in the FROM clause. Because of this we can access the table column names by prefixing Emp.  And for the Name column we are specifying the alias name as ‘Emp Name’ and for Phone column the alias name is ‘Phone Number
SELECT Emp.Name AS 'Emp Name', E.Phone AS [Phone Number]
FROM dbo.Employee AS Emp


Checkpoint in SQL Server


Checkpoint in SQL Server

Checkpoint is an internal process that writes modified pages from Buffer Cache to Physical disk, apart from this it also writes the log records from log buffer to physical file. Writing of such pages from buffer cache to data file is also known as Hardening of modified pages. It is a dedicated process and runs automatically by SQL Server at specific intervals. SQL Server runs checkpoint process for each Database individually.

Checkpoint helps to reduce the recovery time for SQL Server in the event of unexpected shutdown or system crash and system Failure.

In SQL Server there are four types of Checkpoints:

Automatic: The most common checkpoint which runs as a process in the background to make sure SQL Server Database can be recovered in the time limit defined by the Recovery Interval – Server Configuration Option.

Indirect: newly added to SQL Server 2012 runs in the background but to meet a user-specified target recovery time for the specific Database where the option has been configured. Once the Target_Recovery_Time for a given database has been selected this will override the Recovery Interval specified for the server and avoid Automatic Checkpoint on such DB.

Manual: runs like any other T-SQL statement, once you issue checkpoint command also run to its completion. Manual Checkpoint runs for your current Database Only. You can also specify the Checkpoint_Duration which is optional, this duration specifies the time in which you want your checkpoint to complete.

Internal: As a user you can’t control Internal Checkpoint. Issued on specific operations such as:

1. Shutdown initiates a Checkpoint operation on all databases except when Shutdown is not clean (Shutdown with nowait)
2. If the recovery model gets changed from Full\Bulk-logged to Simple.
3. While taking Backup of the Database.
4. If your DB is in Simple Recovery model, checkpoint process executes automatically either when the log becomes 70% full, or based on Server option-Recovery Interval.
5. Alter Database command to add or remove a data\log file also initiates a checkpoint.
6. Checkpoint also takes place when the recovery model of the DB is Bulk-Logged and a minimally logged operation is performed.
7. DB Snapshot creation.


SQL Injection

SQL Injection


SQL injection is a technique where hacker can inject SQL commands into an SQL statement, via web page.Injected SQL commands can compromise the security of a website.

SQL Injection Based on 0=0 is Always True


Let's say that the original purpose of the code was to create an SQL statement to select a user with a given Emp_id.

Emp_id: 112 or 0=0

SELECT * FROM Emp_Details WHERE Emp_id = 112 or 0=0

The SQL above is valid. It will return all rows from the table, as WHERE 0=0 is always true.

 

SQL Injection Based on ""="" is Always True

Here is a public construction, used to verify user login on a web page:

User Name:
Password:

The Final Statement will be

UserName = request.form("UserName");
Pass = request.form ("UserPass");

sql="
SELECT * FROM Emp_Details WHERE UserName ='" + UserName + "' AND PassWord ='" + Pass + "'"

Hackers might get access to user names and passwords in a database by simply inserting “or ""=" into the user name or password text box.

The code at the server will create a valid SQL statement like this:

SELECT * FROM Emp_Details WHERE UserName ="" or ""="" AND PassWord ="" or ""=""

The result SQL is valid. It will return all rows from the table Users,since  WHERE ""="" is always true.

SQL Injection Based on Batched SQL Statements 

Most databases support batched SQL statement, separated by semicolon.

e.g.
SELECT * FROM Emp_Details ; DROP TABLE EmpLoginDetails

The SQL above will return all rows in the Emp_Details table, and then delete EmpLoginDetails table.

If we had the following server code:

UserName = request.form("UserId");
txtSQL = "
SELECT * FROM Emp_Details WHERE UserName = " + UserName;

And the following input:
User Name: 105; DROP TABLE EmpLoginDetails

The code at the server would create a valid SQL statement like this:

SELECT * FROM Emp_Details WHERE UserName = 105; DROP TABLE EmpLoginDetails

Parameters for Protection

The only way to protect a web page from SQL injection, is to use SQL parameters. SQL parameters are values that are added to an SQL query at execution time, in a controlled manner. The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed.


UserName = request.form("UserId");
sql = "
SELECT * FROM Emp_Details WHERE  UserName = @a";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@a", UserName);
command.ExecuteReader();

Backup/Copy a table in SQL using query

Backup/Copy a table in SQL using query

Copy all columns into the new table:

SELECT * INTO NewTableName FROM OldtableName;
e.g.
SELECT * INTO Emp_DetailsBkup FROM Emp_Details;


Copy selected columns to new table

SELECT Col1, Col2, Col3 INTO Emp_DetailsBkup FROM Emp_Details;
e.g.

SELECT Emp_Name, Emp_Id, Address INTO Emp_DetailsBkup FROM Emp_Details;


Copy selected columns to new table with Where clause
SELECT * INTO NewTableName FROM OldtableName where clause;
e.g.

SELECT * INTO Emp_DetailsBkup FROM Emp_Details where id >10;

SQL Server data types


SQL data type is an attribute that specifies type of data of any object. Each column, variable and expression has related data type in SQL.

SQL Server categories of data types

Numeric Data Types

  • bigint: stores only date values with a range of -9,223,372,036,854,775,808 TO                                            9,223,372,036,854,775,807
  • int: stores only date values with a range of -2,147,483,648 TO 2,147,483,647
  • smallint: stores only date values with a range of  -32,768 TO 32,767
  • tinyint: stores only date values with a range of  0 TO 255
  • bit: stores only date values with a range of 0 TO 1
  • decimal: stores only date values with a range of -10^38 +1 TO 10^38 -1
  • numeric: stores only date values with a range of -10^38 +1 TO 10^38 -1
  • money: stores only date values with a range of -922,337,203,685,477.5808 TO                    +922,337,203,685,477.5807
  • smallmoney: stores only date values with a range of -214,748.3648 TO +214,748.3647
  • float: stores only date values with a range of -1.79E + 308 TO 1.79E + 308
  • real : stores only date values with a range of -3.40E + 38 TO 3.40E + 38

 

Date & Time Data Types

  • Datetime:          FROM Jan 1, 1753 TO Dec 31, 9999
  • Smalldatetime:  FROM Jan 1, 1900 TO Jun 6, 2079
  • Date:  Stores a date like June 30, 1991
  • Time:  Stores a time of day like 12:30 P.M.

 

Character Strings Data Types

  • char: Maximum length of 8,000 characters.( Fixed length non-Unicode characters)
  • varchar: Maximum of 8,000 characters.(Variable-length non-Unicode data).
  • varchar(max): Maximum length of 231characters, Variable-length non-Unicode data (SQL Server 2005 only).
  • text: Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

 

Unicode Character Strings Data Types

  • nchar: Maximum length of 4,000 characters.( Fixed length Unicode)
  • nvarchar: Maximum length of 4,000 characters.(Variable length Unicode)
  • nvarchar(max): Maximum length of 231characters (SQL Server 2005 only).( Variable length Unicode)
  • ntext: Maximum length of 1,073,741,823 characters. (Variable length Unicode)

 

Binary Data Types

  • binary: Maximum length of 8,000 bytes(Fixed-length binary data )
  • varbinary: Maximum length of 8,000 bytes.(Variable length binary data)
  • varbinary(max): Maximum length of 231 bytes (SQL Server 2005 only). ( Variable length Binary data)
  • image: Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data)

 

Misc Data Types

  • sql_variant: Stores values of various SQL Server-supported data types, except text, ntext, and timestamp.
  • timestamp: Stores a database-wide unique number that gets updated every time a row gets updated
  • uniqueidentifier: Stores a globally unique identifier (GUID)
  • xml: Stores XML data. You can store xml instances in a column or a variable (SQL Server 2005 only).
  • cursor: Reference to a cursor object
  • table: Stores a result set for later processing

Types of SQL Server Functions


Types of Function

1.            System Defined Function

These functions are defined by Sql Server for different purpose. We have two types of system defined function in Sql Server

Scalar Function

Scalar functions operates on a single value and returns a single value. Below is the list of some useful Sql Server Scalar functions.

      System Scalar Function
  • abs(-9.37) : returns absolute number of the given number means 9.37.
  • rand(15): will generate random number of 15 characters.
  • round(1.567): will round off the given number to 2 places of decimal means 1.57
  • upper('sqlserver'): will returns upper case of given string means ‘SQLSERVER’
  • lower(SQLSERVER’): will returns lower case of given string means 'sqlserver'
  • ltrim(' sqlserver'): will remove the spaces from left hand side of 'sqlserver' string.
  • convert(int, 72.66): will convert the given float value to integer means 72.


Aggregate Function

Aggregate functions operates on a collection of values and returns a single value. Below is the list of some useful Sql Server Aggregate functions.
     System Aggregate Function
  • max(): returns maximum value from a collection of values.
  • min(): returns minimum value from a collection of values.
  • avg(): returns average of all values in a collection.
  • count(): returns no of counts from a collection of values.


User Defined Function

Please check the article posted on dated “Monday, 14 December 2015”


Difference between Stored Procedures and User Defined Functions


Stored Procedures:

1   Stored Procedure may or not return values.
2.    Can have select statements as well as DML statements such as insert, update, delete and so on
3.    It can have both input and output parameters.
4.    For exception handling we can use try catch blocks
5.    Can use transactions within Stored Procedures
6.    Can use both table variables as well as temporary table in it
7.    Stored Procedures can call functions
8.    Procedures can't be called from Select/Where/Having and so on statements. Execute/Exec statement can be used to call/execute Stored Procedure
9.    Procedures can't be used in Join clause



User Defined Functions

1.    Function must return a value.
2.    Will allow only Select statements, it will not allow us to use DML statements.
3.    It will allow only input parameters, doesn't support output parameters.
4.    It will not allow us to use try-catch blocks
5.    Transactions are not allowed within functions
6.    We can use only table variables, it will not allow using temporary tables
7.    Stored Procedures can't be called from a function
8.    Functions can be called from a select statement
9.    A UDF can be used in join clause as a result set.


User Defined Functions IN SQL

User Defined Functions allows modular programming you can create the function once, store it in the database, and call it any number of times in your program. User Defined Functions can be modified independently of the program source code. Similar to Stored Procedures, Transact-SQL User Defined Functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and re-optimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic. Transact-SQL functions are better suited for data-access intensive logic. An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Stored Procedures IN SQL

Stored Procedures are Precompiled means SQL Server compiles each Stored Procedure once and then re utilizes the execution plan. This results in great performance improvements when Stored Procedures are called frequently. It Reduced load on the network bandwidth. Stored Procedures can be used by multiple users and client programs. If you utilize them in a planned manner then you'll find the development cycle requires less time. You can grant users permission to execute a Stored Procedure independently of underlying table permissions.

Triggers in SQL Server


Triggers are database object. Basically these are special type of stored procedure that are automatically fired/executed when a DDL or DML command statement related with the trigger is executed. Triggers are used to assess/evaluate data before or after data modification using DDL and DML statements. These are also used to preserve data integrity, to control server operations, to audit a server and to implement business logic or business rule.

We have two types of triggers

·   DDL Triggers: Triggers Created on DDL Statements i.e. CREATE, ALTER, DROP  and system defined stored procedures that perform DDL-like operations .user can use only FOR and AFTER clause in DDL triggers not INSTEAD OF clause that means user can make only After Trigger on DDL statements. DDL trigger can be used to observe and control actions performed on the server, and to audit these operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating database operations


·    DML Triggers: DML triggers are invoked when any DML commands like INSERT, DELETE, and UPDATE happen on the data of a table and or view. DML triggers are powerful objects for maintaining database integrity and consistency. These type of triggers evaluate data before it has been committed to the database.

During this evaluation following actions are performed.
o    Compare before and after versions of data
o    Roll back invalid modification
o    Read from other tables, those in other database
o    Modify other tables, including those in other database.
o    Execute local and remote stored procedures.

We cannot use following commands in DML trigger
o    ALTER DATABASE
o    CREATE DATABASE
o    DISK DATABASE
o    LOAD DATABASE
o    RESTORE DATABASE

We have two type of DML triggers

o    After Triggers: Triggers used for using FOR and AFTER CLAUSE An AFTER trigger is the original mechanism that SQL Server created to provide an automated response to data modifications. AFTER triggers fire after the data modification statement completes but before the statement's work is committed to the databases. The trigger has the capability to roll back its actions as well as the actions of the modification statement that invoked it.


o    Instead of Trigger: Triggers used in INSTEAD OF CLAUSE called instead of Triggers. Provides an alternative to the AFTER trigger that was heavily utilized in prior versions of SQL Server. It performs its actions instead of the action that fired it. This is much different from the AFTER trigger, which performs its actions after the statement that caused it to fire has completed. This means you can have an INSTEAD OF update trigger on a table that successfully completes but does not include the actual update to the table.
We can define an INSTEAD OF trigger on a view (something that will not work with AFTER triggers) and this is the basis of the Distributed Partitioned Views that are used so split data across a cluster of SQL Servers. We can use INSTEAD OF triggers to simplify the process of updating multiple tables for application developers.

Trigger Syntax 

  •          trigger_name: This is the name of the trigger. It should conform to the rules for identifiers in Sql Server.

  •          Table or view: This is the table or the view on which the trigger is to be created.

  •          ENCRYPTION: This option is optional. If this option is specified, original text of the CREATE TRIGGER statement will be encrypted.

  •          EXECUTE AS: This option is optional. This option specifies, the security context under which the trigger is executed.

  •          FOR or AFTER: FOR or AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR is the only keyword specified. AFTER triggers cannot be defined on views.

  •          INSTEAD OF: INSTEAD OF specifies that the trigger is Instead Of Trigger.

  •          CREATE or ALTER or DROP or INSERT or UPDATE or DELETE:  These keywords specify on which action the trigger should be fired. One of these keywords or any combination of these keywords in any order can be used.

  •          NOT FOR REPLICATION: Indicates that the trigger should not be executed when a replication process modifies the table involved in the trigger.

  •          AS: After this we specifies the actions and condition that the trigger perform.

  •          sql_statement: These are the trigger conditions and actions. The trigger actions specified in the T-SQL statements.



Why we can't execute a stored procedure from a User Defined function(UDF)

Functions cannot "touch" any database but read them only. Stored procedures can do anything and everything with databases. You ...