Watch & Subscribe my SQL videos on YouTube | Join me on Facebook

MS SQL Server 2005 – New Feature | Create Synonyms

April 5, 2009 2 comments

A SYNONYM is a database object that serves the following purposes:

– It provides an alternative name for another database object, referred to as the base object, that can exist on a local or remote server.
– It provides a layer of abstraction that protects a client application from changes made to the name or location of the base object.

For example: consider the Employee table of Adventure Works, located on a server named Server1. To reference this table from another server, Server2, a client application would have to use the four-part name, Server1.AdventureWorks.Person.Employee. Also, if the location of the table were to change, for example, to another server, the client application would have to be modified to reflect that change.

To address both these issues, you can create a synonym, EmpTable, on Server2 for the Employee table on Server1. Now, the client application only has to use the single-part name, EmpTable, to reference the Employee table. Also, if the location of the Employee table changes, you will have to modify the synonym, EmpTable, to point to the new location of the Employee table. Because there is no ALTER SYNONYM statement, you first have to drop the synonym, EmpTable, and then re-create it with the same name, but point it to the new location of Employee.

CREATE SYNONYM:
Syntax-
CREATE SYNONYM [ schema_name_1. ] synonym_name FOR :: = {
[ server_name.[ database_name ] . [ schema_name_2 ]. database_name .
[ schema_name_2 ]. schema_name_2. ] object_name
}

Arguments:
schema_name_1 : Specifies the schema in which the synonym is created. If schema is not specified, SQL Server 2005 uses the default schema of the current user.
synonym_name : Is the name of the new synonym.
server_name : Is the name of the server on which base object is located.
database_name : Is the name of the database in which the base object is located. If database_name is not specified, the name of the current database is used.
schema_name_2 : Is the name of the schema of the base object. If schema_name is not specified the default schema of the current user is used.
object_name : Is the name of the base object that the synonym references.

Example:

-- Create a synonym for the Product table in AdventureWorks.
CREATE SYNONYM MyProduct
FOR AdventureWorks.Production.Product

-- Query the Product table by using the synonym.
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID = 5
Categories: SQL Server 2005 Tags:

DB Basics – Database Normalization | 1NF, 2NF, 3NF

March 25, 2009 5 comments

In the field of Relational Database design, normalization is a systematic way of ensuring that a database structure is suitable for general-purpose querying and free of certain undesirable characteristics—insertion, update, and deletion anomalies—that could lead to a loss of data integrity.
 

According to E. F. Codd the objectives of normalization were stated as follows:

1. To free the collection of relations from undesirable insertion, update and deletion dependencies.

2. To reduce the need for restructuring the collection of relations as new types of data are introduced, and thus increase the life span of application programs.

3. To make the relational model more informative to users.

4. To make the collection of relations neutral to the query statistics, where these statistics are liable to change as time goes by.
 

E. F. Code the inventor of Relational Model, introduced the concept of normalization (1NF at 1970, 2-3NF at 1971, then with R. F. Boyce defined the BCFN in 1974).

C. Date, H. Darwin, R. Fagin, N. Lorentzos defined other higher forms upto 6NF by 2002.

As of now there are total 8 normal forms, as follows:
1. First normal form (1NF)
2. Second normal form (2NF)
3. Third normal form (3NF)
4. Boyce-Codd normal form (BCNF)
5. Fourth normal form (4NF)
6. Fifth normal form (5NF)
7. Domain/key normal form (DKNF)
8. Sixth normal form (6NF)

But to keep our data consistent & non-redundant the first 3 Normal Forms are sufficient.
 

1. The 1st Normal Form:

– There are no duplicate rows and each row should have a unique identifier (or Primary key). A table should be free from repeating groups.

– The values in each column of a table are atomic. Meaning a field value cannot be decomposed into smaller pieces or should not be divided into parts with more than one kind of data in it.
Like: A Person’s Name column could be further divided into First, Middle, Last Name columns.
 

2. The 2nd Normal Form:

– A table should be in 1st Normal Form.

– Any Candidate key (K) and any Attribute (A) that is not a constituent of a candidate key, A depends upon whole of K rather than just part of it.

Means all its non-prime attributes are functionally dependent on the whole of a candidate key.

In Simple terms, any non-key columns must be dependent on the entire primary key. In the case of a composite primary key, this means that a non-key column cannot depend on only part of the composite key.
 

3. The 3rd Normal Form:

– A table should be in 2nd Normal Form.

– Every non-prime attribute of R is non-transitively dependent (i.e. directly dependent) on every candidate/primary key of R.

– All columns should depend directly on the primary key. Tables violate the Third Normal Form when one column depends on another column, which in turn depends on the primary key (a transitive dependency).
 

>> Check & Subscribe my [YouTube videos] on SQL Server.
 


Categories: DB Concepts Tags: , , , ,

DB Basics – SQL Server JOINS and Types

March 12, 2009 5 comments

JOIN clause in SQL Server is used to combine records and create a new record set from two tables based upon the relationship between them. The relationship is established by JOINing common columns with the ON clause from both the tables and returning only required columns from both the tables.
 

JOIN clause is specified with the FROM clause. Clauses like AND, WHERE and/or HAVING can also be used to filter the rows selected by the JOIN clause.
 

–> A JOIN table operator operates on two input tables. The three fundamental types of joins are CROSS JOIN, INNER JOIN, and OUTER JOINS. These three types of joins differ in how they apply their logical query processing phases; each type applies a different set of phases:

– A CROSS JOIN applies only one phase — Cartesian Product.

– An INNER JOIN applies two phases — Cartesian Product and Filter.

– An OUTER JOIN applies three phases — Cartesian Product, Filter, and Add Outer Rows.
 

–> Here is a pictorial representation of various types JOINs you can create in T-SQL:

SQL_JOINS
 

–> Joins can be categorized as:
 

1. CROSS JOINs: Cross Joins return all rows from the Left table. Each row from the Left table is combined with all rows from the Right table. Cross Joins are also called Cartesian products.
 

2. INNER JOIN: (the typical Join operation, which uses some comparison operator like = or ). These include equi-joins and natural joins.
Inner Joins use a comparison operator to match rows from two tables based on the values in common columns from each table.
 

3. OUTER JOIN: Outer joins can be a Left, a Right, or Full Outer Join.
Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

3.a. LEFT JOIN or LEFT OUTER JOIN: The result set of a Left Outer Join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

3.b. RIGHT JOIN or RIGHT OUTER JOIN: A Right Outer Join is the reverse of a Left Outer Join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

3.c. FULL JOIN or FULL OUTER JOIN: A Full Outer Join returns all rows in both the Left and Right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.
 

>> Check & Subscribe my [YouTube videos] on SQL Server.
 


SQL Basics – Difference between TRUNCATE, DELETE and DROP?

February 22, 2009 23 comments

DELETE and TRUNCATE are two SQL commands used to remove records from a particular table. But they differ in how they execute and operate.
 

–> DELETE: (MSDN)

1. Removes Some or All rows from a table.

2. A WHERE clause can be used to remove some rows. If no WHERE condition is specified, all rows will be removed.

3. Causes all DELETE triggers on the table to fire.

4. It removes rows row-by-row one at a time and records an entry in the Transaction logs, thus is slower than TRUNCATE.

5. Every deleted row in locked, thus it requires more number of locks and database resources.

6. According to MS BOL, if a table is a Heap or no Clustered index is defined than the row-pages emptied are not de-allocated instantly and remain allocated in the heap. Thus, no other object can reuse this associated space. Thus to de-allocate the space a Clustered index is required or TABLOCK hint should be applied in the DELETE statement.

7. This is a DML command as it is just used to manipulate/modify the table data. It does not change any property of a table.


 

–> TRUNCATE: (MSDN)

1. Removes All rows from a table.

2. Does not require a WHERE clause, so you can not filter rows while Truncating.

3. With SQL Server 2016 you can Truncate a Table Partition, for more details check [here].

4. IDENTITY columns are re-seeded on this operation, if no seed was defined then the default value 1 is used.

5. No Triggers are fired on this operation because it does not operate on individual rows.

6. It de-allocates Data Pages instead of Rows and records Data Pages instead of Rows in Transaction logs, thus is faster than DELETE.

7. While de-allocating Pages it locks Pages and not Rows, thus it requires less number of locks and few resources.

8. TRUNCATE is not possible when a table:
a. is reference by a Foreign Key or tables used in replication or with Indexed views.
b. participates in an Indexed/Materialized View.
c. published by using Transactional/Merge replication.

9. This is a DDL command as it resets IDENTITY columns, de-allocates Data Pages and empty them for use of other objects in the database.

Note: It is a misconception among some people that TRUNCATE cannot be roll-backed. But in reality both DELETE and TRUNCATE operations can be COMMITTED AND ROLL-BACKED if provided inside a Transaction. The only method to Rollback a committed transaction after DELETE/TRUNCATE is to restore the last backup and run transactions logs till the time when DELETE/TRUNCATE is about to happen.


 

–> DROP: (MSDN)

1. The DROP TABLE command removes one or more table(s) from the database.

2. All related Data, Indexes, Triggers, Constraints, and Permission specifications for the Table are dropped by this operation.

3. Some objects like Views, Stored Procedures that references the dropped table are not dropped and must be explicitly dropped.

4. Cannot drop a table that is referenced by any Foreign Key constraint.

5. According to MS BOL, Large tables and indexes that use more than 128 extents are dropped in two separate phases: Logical and Physical. In the Logical phase, the existing allocation units used by the table are marked for de-allocation and locked until the transaction commits. In the physical phase, the IAM pages marked for de-allocation are physically dropped in batches.
 


 


DB Basics – What are DDL, DML, DCL and TCL commands & difference b/w them?

February 10, 2009 4 comments

DDL – Data Definition Language:

Statements used to Create, Alter, Drop Database Objects.

Some examples:

– CREATE: used to define new objects

– ALTER: used to modify the definition of existing objects

– DROP: used to remove existing entities.

– TRUNCATE TABLE: used to remove all rows from a table without logging the individual row deletions.

– UPDATE STATISTICS: used to update query optimization statistics on a table or indexed view.
 

DML – Data Manipulation Language:

Statements used to Retrieve, Insert, Update, Remove and Manage data within DB objects.

Some examples:

– SELECT: retrieves one or more rows from a Table or View.

– INSERT: insert one or more rows from a Table or View.

– UPDATE: changes existing data in a Table or View.

– DELETE: removes one or more rows from a Table or View.

– BULK INSERT: imports a data file into a database Table or View in a user-specified format.

– MERGE: performs Insert, Update and/or Delete operations on a Target table based on the results of a JOIN with a source table in one Transaction.

– READTEXT: reads text, ntext, or image values from a text, ntext, or image column

– UPDATETEXT: updates an existing text, ntext, or image field.

– WRITETEXT: permits minimally logged, interactive updating of an existing text, ntext, or image column.
 

DCL – Data Control Language:

Statements used to control the access of data stored in database and provide data security.

Some examples:

– GRANT: grants permissions on a securable to a principal.

– REVOKE: removes a previously granted or denied permission.

– SETUSER: allows a member of the sysadmin fixed server role or db_owner fixed database role to impersonate another user.

– EXECUTE AS, statement: sets the execution context of a session.

– EXECUTE AS, clause: define the execution context of the following user-defined modules: functions (except inline table-valued functions), procedures, queues, and triggers.

– REVERT: switches the execution context back to the caller of the last EXECUTE AS statement.

– OPEN MASTER KEY: opens the Database Master Key of the current database.

– CLOSE MASTER KEY: closes the master key of the current database.

– OPEN SYMMETRIC KEY: Decrypts a symmetric key and makes it available for use.

– CLOSE SYMMETRIC KEY: closes a symmetric key, or closes all symmetric keys open in the current session.
permission through its group or role memberships.
 

TCL – Transaction Control Language:

statements used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

Some Examples:

– BEGIN DISTRIBUTED TRANSACTION: specifies the start of a Transact-SQL distributed transaction managed by Microsoft Distributed Transaction Coordinator (MS DTC).

– BEGIN TRANSACTION: marks the starting point of an explicit, local transaction. BEGIN TRANSACTION increments @@TRANCOUNT by 1.

– COMMIT TRANSACTION: marks the end of a successful implicit or explicit transaction.

– COMMIT WORK: marks the end of a transaction.

– ROLLBACK TRANSACTION: rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside the transaction.

– ROLLBACK WORK: rolls back a user-specified transaction to the beginning of the transaction.

– SAVE TRANSACTION: sets a savepoint within a transaction.
 

Check the video:

DDL DML DCL TCL