Archive
SQL Basics – Create Database and Tables in SQL Server
A Database, it is a collection of data/information organized in a particular fashion so that it can be easily managed and accessed back in same fashion. The data stored and retrieved should in same format and should be consistent.
A Relational Database stores data in Tables, and there can be multiple tables in a database, which may be related to each other by referential integrity.
A Table is a collection of related data stored in a structured format within a database, in form or rows (tuple) and columns (fields).
–> Database:
Check video on how to create a new Database by using both, SSMS GUI and T-SQL Script:
–> T-SQL script to Create a new Database:
USE master GO CREATE DATABASE [Demo] ON PRIMARY ( NAME = N'Demo', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER2016\MSSQL\DATA\Demo.mdf' , SIZE = 4096KB , FILEGROWTH = 1024KB ) LOG ON ( NAME = N'Demo_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER2016\MSSQL\DATA\Demo_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10% ) GO
–> Table:
Check video on how to create a new Table by using both, SSMS GUI and T-SQL Script:
–> T-SQL script to Create a new Table:
USE [Demo] GO CREATE TABLE [dbo].[Employee]( [EmployeeID] [int] NOT NULL, [EmployeeName] [nvarchar](100) NOT NULL, [Gender] [nchar](1) NULL, [DOB] [datetime] NULL, [DOJ] [datetime] NULL, [DeptID] [int] NULL ) SELECT * FROM [dbo].[Employee] INSERT INTO [dbo].[Employee] VALUES (1, 'MANOJ PANDEY', 'M', '1990-01-01', '2010-01-01', 101) sp_help 'Employee' -- ALT + F1 INSERT INTO [dbo].[Employee] VALUES (2, 'JHON K', 'M', NULL, '2010-01-01', NULL) INSERT INTO [dbo].[Employee] ([EmployeeID], [EmployeeName]) VALUES (3, 'Brock H') sp_rename 'Employees', 'Employee' DELETE FROM [dbo].[Employee] WHERE EmployeeID = 2 TRUNCATE TABLE [dbo].[Employee] DROP TABLE [dbo].[Employee]
Check my [next post] on how to ADD/DROP columns in a table.
DB Basics – Database Normalization | 1NF, 2NF, 3NF
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.
DB Basics – SQL Server JOINS and Types

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:
–> 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.
DB Basics – What are DDL, DML, DCL and TCL commands & difference b/w them?
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:
An introduction to SQL and its Components
–>Introduction:
SQL or Structured Query Language is a language that provides an interface to relational database systems. The proper pronunciation of SQL is “ess cue ell,” and not “sequel” as is commonly heard. SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO and ANSI standard. In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables and other database structures. The development of SQL is governed by standards. A major revision to the SQL standard was completed in 1992, called SQL2. SQL3 support object extensions and are (partially?) implemented in Oracle8 and 9i.
SQL (Structured Query Language) is a database computer language designed for managing data in relational database management systems (RDBMS). Its scope includes data query and update, schema creation and modification, and data access control. SQL was one of the first languages for Edgar F. Codd’s relational model in his influential 1970 paper, “A Relational Model of Data for Large Shared Data Banks” and became the most widely used language for relational databases.
–>Language elements:
The SQL language is sub-divided into several language elements, including:
1. Clauses which are in some cases optional, constituent components of statements and queries.
2. Expressions which can produce either scalar values or tables consisting of columns and rows of data.
3. Predicates which specify conditions that can be evaluated to SQL three-valued logic (3VL) Boolean truth values and which are used to limit the effects of statements and queries, or to change program flow.
4. Queries which retrieve data based on specific criteria.
5. Statements which may have a persistent effect on schemas and data, or which may control transactions, program flow, connections, sessions, or diagnostics.
6. SQL statements also include the semicolon (“;”) statement terminator. Though not required on every platform, it is defined as a standard part of the SQL grammar.
7. Insignificant whitespace is generally ignored in SQL statements and queries, making it easier to format SQL code for readability.
–> Queries:
The most common operation in SQL is the query, which is performed with the declarative SELECT statement. SELECT retrieves data from one or more tables, or expressions. Standard SQL statements have no persistent effects on the database. Some non-standard implementations of SELECT can have persistent effects, such as the SELECT INTO syntax that exists in some databases.
Queries allow the user to describe desired data, leaving the database management system (DBMS) responsible for planning, optimizing, and performing the physical operations necessary to produce that result as it chooses.
A Query includes a list of columns to be included in the final result immediately following the SELECT keyword. An asterisk (“*”) can also be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that includes:
1. The FROM clause which indicates the table(s) from which data is to be retrieved. The FROM clause can include optional JOIN subclauses to specify the rules for joining tables.
2. The WHERE clause includes a comparison predicate, which restricts the rows returned by the query. The WHERE clause eliminates all rows from the result set for which the comparison predicate does not evaluate to True.
3. The GROUP BY clause is used to project rows having common values into a smaller set of rows. GROUP BY is often used in conjunction with SQL aggregation functions or to eliminate duplicate rows from a result set. The WHERE clause is applied before the GROUP BY clause.
4. The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions can be used in the HAVING clause predicate.
5. The ORDER BY clause identifies which columns are used to sort the resulting data, and in which direction they should be sorted (options are ascending or descending). Without an ORDER BY clause, the order of rows returned by an SQL query is undefined.
–> A simple SELECT example:
SELECT * FROM dbo.Book WHERE price > 100.00 ORDER BY title;
–> With SQL you can:
– Create new Databases.
– Create new Tables in a database.
– Execute Queries against a database.
– Insert records in a database.
– Update records in a database.
– Delete records from a database.
– Retrieve data from a database.
– Create stored procedures in a database.
– Create views in a database.
– Set permissions on tables, procedures, and views.
For the complete history check my following [blog post].






