Вы находитесь на странице: 1из 31

SQL Server Data Types

Character strings: Data type char(n) varchar(n) Description Fixed-length character string. Maximum 8,000 characters Variable-length character string. Maximum 8,000 characters Storage n

varchar(max) Variable-length character string. Maximum 1,073,741,824 characters text Variable-length character string. Maximum 2GB of text data

Unicode strings: Data type nchar(n) nvarchar(n) Description Fixed-length Unicode data. Maximum 4,000 characters Variable-length Unicode data. Maximum 4,000 characters Storage

nvarchar(max) Variable-length Unicode data. Maximum 536,870,912 characters ntext Variable-length Unicode data. Maximum 2GB of text data

Binary types: Data type bit binary(n) varbinary(n) image Description Allows 0, 1, or NULL Fixed-length binary data. Maximum 8,000 bytes Variable-length binary data. Maximum 8,000 bytes Variable-length binary data. Maximum 2GB Storage

varbinary(max) Variable-length binary data. Maximum 2GB

Number types: Data type tinyint smallint int bigint Description Allows whole numbers from 0 to 255 Allows whole numbers between -32,768 and 32,767 Allows whole numbers between -2,147,483,648 and 2,147,483,647 Allows whole numbers between 9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 Fixed precision and scale numbers. Storage 1 byte 2 bytes 4 bytes 8 bytes

decimal(p,s)

5-17 bytes

Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 numeric(p,s) Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0 smallmoney money float(n) Monetary data from -214,748.3648 to 214,748.3647 Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 Floating precision number data from -1.79E + 308 to 1.79E + 308. The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53. real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes 4 bytes 8 bytes 4 or 8 bytes 5-17 bytes

Date types: Data type datetime datetime2 Description From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds Storage 8 bytes 6-8 bytes 4 bytes

smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute date time

Store a date only. From January 1, 0001 to December 3 bytes 31, 9999 Store a time only to an accuracy of 100 nanoseconds 3-5 bytes 8-10 bytes

datetimeoffset The same as datetime2 with the addition of a time zone offset

timestamp

Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable

Other data types: Data type sql_variant Description Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp Stores XML formatted data. Maximum 2GB Stores a reference to a cursor used for database operations Stores a result-set for later processing

uniqueidentifier Stores a globally unique identifier (GUID) xml cursor table

CREATE TABLE
CREATE TABLE [dbo]. [Employee]( [Empid] [Int] IDENTITY (1, 1) NOT NULL Primary key, [EmpNumber] [nvarchar](50) NOT NULL, [EmpFirstName] [nvarchar](150) NOT NULL, [EmpLastName] [nvarchar](150) NULL, [EmpEmail] [nvarchar](150) NULL, [Managerid] [int] NULL, [Departmentid] [INT] ) CREATE TABLE [dbo].[Department]( [Departmenttid] [int] IDENTITY (1, 1) NOT NULL primary key, [DepartmentName] [nvarchar](255) NOT NULL )

insert
insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A001','Samir','Singh','samir@abc.com',2,2) insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A002','Amit','Kumar','amit@abc.com',1,1) insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A003','Neha','Sharma','neha@abc.com',1,2) insert into Employee (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Departmentid) values('A004','Vivek','Kumar','vivek@abc.com',1,NULL) insert into Department(DepartmentName) values('Accounts') insert into Department(DepartmentName) values('Admin') insert into Department(DepartmentName) values('HR') insert into Department(DepartmentName) values('Technology')

Join
Inner Join
This type of join is also known as the Equi join. This join returns all the rows from both tables where there is a match. Now, if we want to get employee id, employee first name, employee's last name and their department name for those entries employee which belongs to at least one department, then we can use the inner join

Query for Inner Join


SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp INNER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid

Result
Empid 1 2 3 EmpFirstName Samir Amit Neha EmpLastName Singh Kumar Sharma DepartmentName Admin Accounts Admin

Self Join
Sometime we need to join a table to itself. This type of join is called Self join. It is one of the type of inner join where both the columns belong to the same table. In this Join, we need to open two copies of a same table in the memory. Since the table name is the same for both instances, we use the table aliases to make identical copies of the same table to be open in different memory locations. For example if we need to get the employee name and their manager name we need to use the self join, since the managerid for an employee is also stored in the same table as the employee.

Query for the Self Join


SELECT Emp1.Empid, Emp1.EmpFirstName+' '+Emp1.EmpLastName as EmployeeName, Emp2.EmpFirstName+' '+Emp2.EmpLastName as ManagerName FROM Employee Emp1 INNER JOIN Employee Emp2 ON Emp1.Managerid=Emp2.Empid

Result
Empid 1 2 3 4 EmployeeName Samir Singh Amit Kumar Neha Sharma Vivek Kumar ManagerName Amit Kumar Samir Singh Samir Singh Samir Singh

Outer Join
This type of join is needed when we need to select all the rows from the table on the left (or right or both) regardless of whether the other table has common values or not and it usually enter null values for the data which is missing. The Outer join can be of three types

1. Left Outer Join 2. Right Outer Join 3. Full Outer Join

Left Outer Join


If we want to get employee id, employee first name, employes last name and their department name for all the employees regardless of whether they belong to any department or not,then we can use the left outer join. In this case we keep the Employee table on the left side of the join clause. It will insert NULL values for the data which is missing in the right table.

Query for Left Outer Join


SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp LEFT OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid

Result
Empid 1 2 3 4 EmpFirstName Samir Amit Neha Vivek EmpLastName Singh Kumar Sharma Kumar DepartmentName Admin Accounts Admin NULL

Right Outer Join


If we want to get all the departments name and employee id, employee first name, and employees last name of all the employees belonging to the department regardless of whether a department have employees or not, then we can use the right outer join. In this case we keep the Department table on the right side of the join clause. It will insert NULL values for the data which is missing in the left table (Employee).

Query for Right Outer Join


SELECT Dept.DepartmentName, Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName FROM Employee Emp RIGHT OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmentid

Result
DepartmentName Accounts Admin Admin HR Technology Empid 2 1 3 NULL NULL EmpFirstName Amit Samir Neha NULL NULL EmpLastName Kumar Singh Sharma NULL NULL

Full Outer Join


If we want to get all the departments name and the employee id, employee first name, employes last name of all the employees regardless of whether a department have employees or not, or whether a employee belong to a department or not, then we can use the full outer join. It will insert null values for the data which is missing in both the tables.

Query for Full Outer Join


SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp FULL OUTER JOIN Department dept ON Emp.Departmentid=Dept.Departmenttid

Result
Empid 1 2 3 4 NULL NULL EmpFirstName Samir Amit Neha Vivek NULL NULL EmpFirstName Singh Kumar Sharma Kumar NULL NULL DepartmentName Admin Accounts Admin NULL HR Technology

Cross Join
This join combines all the rows from the left table with every row from the right table. This type of join is needed when we need to select all the possible combinations of rows and columns from both the tables. This type of join is generally not preferred as it takes lot of time and gives a huge result that is not often useful.

Query for the Cross Join


SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DepartmentName FROM Employee Emp CROSS JOIN Department dept

Results
Empid 1 2 3 4 EmpFirstName Samir Amit Neha Vivek EmpLastName Singh Kumar Sharma Kumar DepartmentName Accounts Accounts Accounts Accounts

1 2 3 4 1 2 3 4 1 2 3 4

Samir Amit Neha Vivek Samir Amit Neha Vivek Samir Amit Neha Vivek

Singh Kumar Sharma Kumar Singh Kumar Sharma Kumar Singh Kumar Sharma Kumar

Admin Admin Admin Admin HR HR HR HR Technology Technology Technology Technology

constraint
Primary key, Foreign Key and Default constraint are the 3 main constraints that need to be considered while creating tables or even after that. It seems very easy to apply these constraints but still we have some confusions and problems while implementing it. So I tried to write about these constraints that can be created or added at different levels and in different ways or methods.

Primary Key Constraint: Primary


1) a.

Keys constraints prevents duplicate values for columns and provides

unique identifier to each column, as well it creates clustered index on the columns. Create Table Statement to create Primary Key Column Level

USE AdventureWorks2008 GO CREATE TABLE Products ( ProductID INT CONSTRAINT pk_products_pid PRIMARY KEY, ProductName VARCHAR(25) ); GO b. Table Level

CREATE TABLE Products ( ProductID INT, ProductName VARCHAR(25) CONSTRAINT pk_products_pid PRIMARY KEY(ProductID) ); GO 2) Alter Table Statement to create Primary Key

ALTER TABLE Products ADD CONSTRAINT pk_products_pid PRIMARY KEY(ProductID) GO 3) Alter Statement to Drop Primary key

ALTER TABLE Products DROP CONSTRAINT pk_products_pid; GO

Foreign Key Constraint:


When a FOREIGN KEY constraint is added to an existing column or columns in the table SQL Server, by default checks the existing data in the columns to ensure that all values, except NULL, exist in the column(s) of the referenced PRIMARY KEY or UNIQUE constraint. 1) Create Table Statement to create Foreign Key

a.

Column Level

USE AdventureWorks2008 GO CREATE TABLE ProductSales ( SalesID INT CONSTRAINT pk_productSales_sid PRIMARY KEY, ProductID INT CONSTRAINT fk_productSales_pidFOREIGN KEY REFERENCES Products(ProductID) , SalesPerson VARCHAR(25) ); GO b. Table Level

CREATE TABLE ProductSales ( SalesID INT, ProductID INT, SalesPerson VARCHAR(25) CONSTRAINT pk_productSales_sid PRIMARY KEY(SalesID), CONSTRAINT fk_productSales_pidFOREIGN KEY(ProductID)REFERENCES Products(ProductID) ); GO 1) Alter Table Statement to create Foreign Key

ALTER TABLE ProductSales ADD CONSTRAINT fk_productSales_pidFOREIGN KEY(ProductID)REFERENCES Products(ProductID) GO 2) Alter Table Statement to Drop Foreign Key

ALTER TABLE ProductSales DROP CONSTRAINT fk_productSales_pid; GO

Default Constraint:
Default constraint when created on some column will have the default data which is given in the constraint when no records or data is inserted in that column. 1) a. Create Table Statement to create Default Constraint Column Level

USE AdventureWorks2008 GO CREATE TABLE Customer ( CustomerID INT CONSTRAINT pk_customer_cid PRIMARY KEY, CustomerName VARCHAR(30), CustomerAddress VARCHAR(50) CONSTRAINT df_customer_AddDEFAULT 'UNKNOWN' ); GO

b. 2)

Table Level : Not applicable for Default Constraint Alter Table Statement to Add Default Constraint

ALTER TABLE Customer ADD CONSTRAINT df_customer_Add DEFAULT 'UNKNOWN' FORCustomerAddress AGO 3) Alter Table to Drop Default Constraint

ALTER TABLE Customer DROP CONSTRAINT df_customer_Add GO

SQL NOT NULL Constraint


The NOT NULL constraint enforces a column to NOT accept NULL values. The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. The following SQL enforces the "P_Id" column and the "LastName" column to not accept NULL values: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

SQL UNIQUE Constraint


The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created:
MySQL:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255),

Address varchar(255), City varchar(255), UNIQUE (P_Id) )


SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) )

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons ADD UNIQUE (P_Id)


To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

To DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL: MySQL:

ALTER TABLE Persons DROP INDEX uc_PersonID

SQL Server / Oracle / MS Access:

ALTER TABLE Persons DROP CONSTRAINT uc_PersonID

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created: MySQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (P_Id) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) )

Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the value of the pk_PersonID is made up of two columns (P_Id and LastName).

SQL PRIMARY KEY Constraint on ALTER TABLE


To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD PRIMARY KEY (P_Id) To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).

To DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:
MySQL:

ALTER TABLE Persons DROP PRIMARY KEY SQL Server / Oracle / MS Access: ALTER TABLE Persons DROP CONSTRAINT pk_PersonID

SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in another table. Let's illustrate the foreign key with an example. Look at the following two tables : The "Persons" table:
P_Id 1 LastName Hansen FirstName Ola Address Timoteivn 10 City Sandnes

2 3

Svendson Pettersen

Tove Kari

Borgvn 23 Storgt 20

Sandnes Stavanger

The "Orders" table:


O_Id 1 2 3 4 OrderNo 77895 44678 22456 24562 P_Id 3 3 2 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY Constraint on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table is created:
MySQL:

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )
SQL Server / Oracle / MS Access:

CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) ) To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders ( O_Id int NOT NULL,

OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )

SQL FOREIGN KEY Constraint on ALTER TABLE


To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders ADD FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)

To DROP a FOREIGN KEY Constraint


To drop a FOREIGN KEY constraint, use the following SQL:
MySQL:

ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders


SQL Server / Oracle / MS Access:

ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

SQL CHECK Constraint on CREATE TABLE


The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0. MySQL: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) ) SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) ) To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') )

SQL CHECK Constraint on ALTER TABLE


To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons ADD CHECK (P_Id>0) To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access: ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')

To DROP a CHECK Constraint


To drop a CHECK constraint, use the following SQL: SQL Server / Oracle / MS Access:

ALTER TABLE Persons DROP CONSTRAINT chk_Person


MySQL:

ALTER TABLE Persons DROP CHECK chk_Person

SQL DEFAULT Constraint


The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified.

SQL DEFAULT Constraint on CREATE TABLE


The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created: My SQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' ) The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE(): CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, OrderDate date DEFAULT GETDATE() )

SQL DEFAULT Constraint on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:

MySQL:

ALTER TABLE Persons ALTER City SET DEFAULT 'SANDNES'


SQL Server / MS Access:

ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES'


Oracle:

ALTER TABLE Persons MODIFY City DEFAULT 'SANDNES'

To DROP a DEFAULT Constraint


To drop a DEFAULT constraint, use the following SQL: MySQL:

ALTER TABLE Persons ALTER City DROP DEFAULT


SQL Server / Oracle / MS Access:

ALTER TABLE Persons ALTER COLUMN City DROP DEFAULT

CLAUSES in SQL Server


SQL Server provides with the following clauses that can be used in the SELECT statements:

WHERE GROUP BY HAVING ORDER BY

The complete syntax of the SELECT statement looks as following: SELECT <select_list> FROM <tname> [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ]

WHERE Clause:
The WHERE clause is a filter that defines the conditions each row in the source tables must meet to qualify for the SELECT. Only rows that meet the conditions contribute data to the result set. Data from rows that do not meet the conditions is not used.

SELECT * FROM EMP WHERE JOB='MANAGER' SELECT * FROM EMP WHERE DEPTNO=20

GROUP BY Clause:
The GROUP BY clause partitions the result set into groups based on the values in the columns of the group_by_list. For example, theEmp table has 3 values in Deptno column. A GROUP BY Deptno clause partitions the result set into 3 groups, one for each value ofDeptno.

Ex-1:How to find the highest salaries for each department. Sol: SELECT DEPTNO, MAX(SAL) FROM EMP GROUP BY DEPTNO Ex-2:How to find the highest salaries for each job. Sol: SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB Ex-3:How to find the highest salaries for each department in it for each job.

Sol: SELECT DEPTNO, JOB, MAX(SAL) FROM EMP GROUP BY DEPTNO, JOB Note: While using the GROUP By clause the select_list of the query should contain only the following:

Group Functions or Aggregate Functions Columns used in the Group By Clause Constants.

Ex-4:How to find the number of employees working for each department. Sol: SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO Ex-5:How to find the number of employees working for each department only if the number is greater than 3. Sol: SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>3

HAVING Clause:
The HAVING clause is an additional filter that is applied to the result set. Logically, the HAVING clause filters rows from the intermediate result set built from applying any FROM, WHERE, or GROUP BY clauses in the SELECT statement. HAVING clauses are typically used with a GROUP BY clause.

Ex-6:How to find the number of Clerks working for each department. Sol: SELECT DEPTNO, COUNT(*) FROM EMP WHERE JOB='CLERK' GROUP BY DEPTNO Ex-7:How to find the number of Clerk's working for each department only if the count is greater than 1. Sol: SELECT DEPTNO, COUNT(*) FROM EMP WHERE JOB='CLERK' GROUP BY DEPTNO HAVING COUNT(*)>1

ORDER BY clause:
The ORDER BY clause defines the order in which the rows in the result set are sorted. order_list specifies the result set columns that make up the sort list. The ASC and DESC keywords are used to specify if the rows are sorted in an ascending or descending sequence.

ORDER BY order_list[ ASC | DESC ] SELECT * FROM EMP ORDER BY SAL SELECT * FROM EMP ORDER BY SAL DESC SELECT * FROM EMP ORDER BY SAL, COMM

Logical Operators in sql server Logical Operators


Logical operators test for the truth of some condition. Logical operators, like comparison operators, return a Boolean data type with a value of TRUE, FALSE, or UNKNOWN.

Operator
ALL AND ANY BETWEEN EXISTS IN LIKE NOT OR SOME

Meaning
TRUE if all of a set of comparisons are TRUE. TRUE if both Boolean expressions are TRUE. TRUE if any one of a set of comparisons are TRUE. TRUE if the operand is within a range. TRUE if a subquery contains any rows. TRUE if the operand is equal to one of a list of expressions. TRUE if the operand matches a pattern. Reverses the value of any other Boolean operator. TRUE if either Boolean expression is TRUE. TRUE if some of a set of comparisons are TRUE.

Table

How Logical Operator works

ALL Compares a scalar value with a single-column set of values. The following query returns all if all the StateCodes greater than 200. If atleast one statecode is less then 200 then it doesn,t return any records. Here States MP and UP have statecodes greater than 200, so condition fails and result is nothing.

SELECT * FROM WHERE 200 > ALL (

tbl_Population

SELECT StateCode FROM tbl_Population )

OUTPUT Noyhing

AND Performs a logical AND operation. The expression evaluates to TRUE if all conditions are TRUE.

SELECT * FROM tbl_Population WHERE (StateCode > 100 AND StateCode < 200)

OUTPUT

ANY and SOME Compares a scalar value with a single-column set of values. Both SOME or ANY returns TRUE when the comparison specified is TRUE for ANY pair, otherwise, returns FALSE. In the given table there is some states which statecodes are less than 200, so it will returns all the records.

ANY SELECT * FROM WHERE 200 > ANY ( SELECT StateCode FROM tbl_Population ) tbl_Population

SOME SELECT * FROM tbl_Population

WHERE 200 > SOME ( SELECT StateCode FROM tbl_Population )

OUTPUT

BETWEEN Specifies a range to test.

SELECT * FROM tbl_Population WHERE StateCode BETWEEN 100 AND 200

OUTPUT

EXISTS Specifies a subquery to test for the existence of rows.

SELECT * FROM tbl_Population WHERE EXISTS ( SELECT * FROM tbl_Population WHERE StateCode=409 ) It returns data when a specified record exist in the table which is given in sub query of where condition

OUTPUT

IN Determines whether a given value matches any value in a subquery or a list. SELECT * FROM tbl_Population WHERE StateCode IN (1,101,102,300)

OUTPUT

LIKE Determines whether a specific character string matches a specified pattern. A pattern can include regular characters and wildcard characters. During pattern matching, regular characters must exactly match the characters specified in the character string. However, wildcard characters can be matched with arbitrary fragments of the character string. Using wildcard characters makes the LIKE operator more flexible than using the = and != string comparison operators. If any one of the arguments are not of character string data type,

the SQL Server 2005 Database Engine converts them to character string data type, if it is possible.

SELECT * FROM tbl_Population WHERE StateName LIKE 'K%'

Returns all the records which has K as first letter in StateName

OUTPUT

NOT To find rows that do not match a value, use the NOT operator. SELECT * FROM tbl_Population WHERE StateCode NOT IN (1,100,200,300)

OUTPUT

OR Performs a logical OR operation. The expression evaluates to TRUE if atleast one condition

is TRUE.

SELECT * FROM tbl_Population WHERE StateName LIKE 'K%' OR StateCode < 105

OUTPUT

The BETWEEN Operator


The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.

SQL BETWEEN Syntax


SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2

BETWEEN Operator Example


The "Persons" table: P_Id 1 2 3 LastName Hansen Svendson Pettersen FirstName Ola Tove Kari Address Timoteivn 10 Borgvn 23 Storgt 20 City Sandnes Sandnes Stavanger

Now we want to select the persons with a last name alphabetically between "Hansen" and "Pettersen" from the table above. We use the following SELECT statement:

SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'


The result-set will look like this: P_Id 1 LastName Hansen FirstName Ola Address Timoteivn 10 City Sandnes

Note: The BETWEEN operator is treated differently in different databases! In some databases, persons with the LastName of "Hansen" or "Pettersen" will not be listed, because the BETWEEN operator only selects fields that are between and excluding the test values. In other databases, persons with the LastName of "Hansen" or "Pettersen" will be listed, because the BETWEEN operator selects fields that are between and including the test values. And in other databases, persons with the LastName of "Hansen" will be listed, but "Pettersen" will not be listed (like the example above), because the BETWEEN operator selects fields between the test values, including the first test value and excluding the last test value. Therefore: Check how your database treats the BETWEEN operator.

Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:

SELECT * FROM Persons WHERE LastName NOT BETWEEN 'Hansen' AND 'Pettersen'
The result-set will look like this: P_Id 2 3 LastName Svendson Pettersen FirstName Tove Kari Address Borgvn 23 Storgt 20 City Sandnes Stavanger

SQL Alias
You can give a table or a column another name by using an alias. This can be a good thing to do if you have very long or complex table names or column names. An alias name could be anything, but usually it is short. SQL Alias Syntax for Tables
SELECT column_name(s) FROM table_name AS alias_name

SQL Alias Syntax for Columns


SELECT column_name AS alias_name FROM table_name

Alias Example
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the table aliases of "p" and "po" respectively. Now we want to list all the orders that "Ola Hansen" is responsible for. We use the following SELECT statement:

SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po WHERE p.LastName='Hansen' AND p.FirstName='Ola'
The same SELECT statement without aliases:

SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons, Product_Orders WHERE Persons.LastName='Hansen' AND Persons.FirstName='Ola'

Microsoft SQL Server supports the following constraints:

PRIMARY KEY UNIQUE FOREIGN KEY CHECK NOT NULL

A PRIMARY KEY constraint IT is a unique identifier for a row within a database table. Every TABLE should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

A UNIQUE constraint IT enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints. Each TABLE can have only one primary key. If there are multiple UNIQUE identifiers for a multiple columns, such column pairs are often referred to as alternate keys or candidate keys (these terms are not used by SQL Server). In practice, one of two columns is logically promoted to primary key using the PRIMARY KEY constraint, and the other is usually declared by a UNIQUE constraint. Internally, PRIMARY KEY and UNIQUE constraints are handled almost identically. A FOREIGN KEY constraint prevents any actions that would destroy link between tables with the corresponding data values. A foreign key in one TABLE points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity. A FOREIGN KEY is a column whose values are derived from the PRIMARY KEY or UNIQUE KEY of some other table. By using ON DELETE CASCADE option and if a user deletes a record in the master table, all corresponding recording in the detail TABLE along with the record in the master TABLE will be deleted. CREATE TABLE orders(order_id INT NOT NULL PRIMARY KEY, cust_id int NOT NULL REFERENCES customer(cust_id) ON DELETE CASCADE) A TABLE can have a maximum of 253 FOREIGN KEY references. This limit is derived from the internal limit of 256 tables in a single query. If youre dropping tables, you must drop all the referencing tables or drop the referencing FOREIGN KEY constraint before dropping the referenced table. DROP TABLE orders DROP TABLE customer CHECK constraint It is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity. Check constraints allow us to define an expression for a TABLE that must not evaluate to FALSE for a data modification statement to succeed. Check constraints deal only with some logical expression for the specific row already being operated on, so no additional I/O required. CREATE TABLE employee(emp_id INT NOT NULL PRIMARY KEYCHECK(emp_id between 0 and 1000), emp_name VARCHAR(30) NOT NULL constraint no_numsCHECK(emp_name not like %[0-9]%), entered_date datetime NULL CHECK(entered_date>=CURRENT_TIMESTAMP), dept_no INT CHECK(dept_no < 0 and dept_no > 100)) NOT NULL constraint Enforces that the column will not accept NULL values. The NOT NULL constraints are used to enforce domain integrity, as the check constraints.

What about DEFAULT Constraints? A default allows you to specify a constant value, NULL or the run-time value of a system function if no known value exists or if the column is missing in an INSERT statement. CREATE TABLE employee(emp_id INT NOT NULL PRIMARY KEY DEFAULT 1000 CHECK(emp_id between 0 and 1000), emp_name VARCHAR(20) DEFAULT 'Radha Krishna') Insert into employee values(DEFAULT, DEFAULT)