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

CREATE TABLE COMMAND

Create Table
The mechanics of creating a table are relatively straight forward. Being able to design a well thought out database that will scale to meet the needs of a large scale enterprise is a very challenging undertaking. In these examples we will be working through development of a fairly simple three table database. In doing so we will get to cover a good deal of the development basics for creating tables and indexes.

Creating the person table


CREATE TABLE person ( num INT NOT NULL , firstname VARCHAR(20) NULL , lastname VARCHAR(30) NULL , gender_code VARCHAR(1) NULL , birth_dttm DATETIME NULL , inactive_date DATETIME NULL , CONSTRAINT PK_Person PRIMARY KEY CLUSTERED (num ASC) ON [PRIMARY] )

Creating the phone table


CREATE TABLE phone ( person_num INT NOT NULL , type_code CHAR(3) NOT NULL , area_code CHAR(3) NULL , exchange CHAR(3) NULL , extension CHAR(4) NULL , CONSTRAINT PK_phone PRIMARY KEY CLUSTERED (person_num ASC, type_code ASC) ON [PRIMARY] )

Creating the address table


CREATE TABLE address ( person_num INT NOT NULL , type_code CHAR(4) NOT NULL , street1 CHAR(30) NULL , street2 CHAR(30) NULL , city CHAR(30) NULL , state CHAR(2) NULL , postal_code CHAR(10) NULL , CONSTRAINT PK_address PRIMARY KEY CLUSTERED (person_num ASC, type_code ASC) ON [PRIMARY] )

This SQL CREATE TABLE statement defines a new table to store the products data: CREATE TABLE PRODUCTS (MFR_ID CHAR(3), PRODUCT_ID CHAR(5), DESCRIPTION VARCHAR(20), PRICE MONEY, QTY_ON_HAND INTEGER)

SQL Server - SQL Table Basics - Data Types


SQL Server BIT TINYINT SMALLINT INT BIGINT REAL FLOAT MONEY SMALLMONEY DECIMAL NUMERIC DATETIME CHARn NCHARn VARCHARn NVARCHARn TEXT NTEXT BINARY VARBINARY IMAGE Data Precision Integer: 0 or 1 Positive Integer 0 -> 255 Signed Integer -32,768 -> 32,767 Signed Integer -2^31 -> 2^31-1 Signed Integer -2^63 -> 2^63-1 Floating precision -1.79E + 308 -> 1.79E + 308 Floating precision -3.40E + 38 -> 3.40E + 38 4 decimal places, -2^63/10000 -> 2^63-1/10000 4 decimal places, -214,748.3648 -> 214,748.3647 Fixed precision -10^38 + 1 -> 10^38 - 1 Fixed precision -10^38 + 1 -> 10^38 - 1 Date+Time 1753-01-01 -> 9999-12-31, accuracy of 3.33 ms Fixed-length non-Unicode string to 8,000 characters Fixed-length Unicode string to 4,000 characters Variable-length non-Unicode string to 8,000 characters Variable-length Unicode string to 4,000 characters Variable-length non-Unicode string to 2,147,483,647 characters Variable-length Unicode string to 1,073,741,823 characters Fixed-length binary data up to 8,000 characters Variable-length binary data up to 8,000 characters Variable-length binary data up to 2,147,483,647 characters

SMALLDATETIME Date+Time 1900-01-01 -> 2079-06-06, accuracy of one minute

INSERT COMMAND TO INSERT DATA INTO TABLE


Once the table has been created, you can fill it with data by using INSERT command INSERT INTO PRODUCTS VALUES ('ACI', '41007', 'Size 7 Widget', 225.00, 250);

DELETE TABLE
DROP TABLE PRODUCTS;

UPDATE TABLE
UPDATE PRODUCTS SET DESCRIPTION=ASDFGFG WHERE PRODUCT_ID=41007;

DELETE RECORD OF TABLE


DELETE FROM PRODUCTS WHERE PRODUCT_ID=41007;

ALTER COLUMN OF A TABLE


ALTER TABLE student ALTER COLUMN roll int NOT NULL;

ALTER Command FOR ADDING CONSTRAINT


ALTER TABLE STUDENT ADD CONSTRAINT pk_roll primary key(roll);

ALTER Command FOR DELETING CONSTRAINT

alter table student drop constraint pk_roll;

FOREIGN KEY
A column in one table whose value matches the primary key in some other table is called a foreign key. create table marks(roll int,tmarks int,FOREIGN key(roll) references student(roll)); Here student is the parent table and roll is primary key of parent table that is referenced by child table marks.

ALTER FOR ADDING FOREIGN KEY CONSTRAINT

ALTER TABLE marks2 ADD CONSTRAINT fk_r FOREIGN KEY (roll)

REFERENCES student1(roll);

COMPOSITE PRIMARY KEY


CREATE TABLE CategoriesComp ( CategoryID int NOT NULL, CategoryCode char(5) NOT NULL, CategoryName varchar(50) NOT NULL, CONSTRAINT PK_Categories PRIMARY KEY (CategoryID, CategoryCode));

INSERT INSERT INSERT INSERT

INTO INTO INTO INTO

CategoriesComp CategoriesComp CategoriesComp CategoriesComp

VALUES VALUES VALUES VALUES

(1, (2, (2, (1,

'AAA', 'AAA', 'AAA', 'BBB',

'Cat 'Cat 'Cat 'Cat

1'); 4'); 3');//fail 2');

DEFAULT CONSTRAINT
create table student2(roll int,name char(15),tmarks int default(0)); insert into student2(roll,name) values(1,'Ram'); select * from student2;

CHECK CONSTRAINT
create table student3(roll int,name char(15),tmarks int check(tmarks<500)); insert into student3 values(1,'Ram',367); insert into student3 values(1,'Ram',602);//fail

SELECT STATEMENT The SQL statement that retrieves data from the database is called SELECT. This SQL statement retrieves the data you want: FOR SELECTING ALL COLUMNS OF TABLE OFFICE
SELECT * FROM OFFICES;

FOR SELECTING SPECIFIED COLUMNS OF TABLE OFFICE

SELECT CITY, OFFICE, SALES FROM OFFICES;

SELECT STATEMENT WITH CONDITION


SELECT NAME, SALES, QUOTA FROM OFFICES WHERE SALES < QUOTA SELECT CITY, TARGET, SALES FROM OFFICES WHERE REGION = 'East' AND SALES > TARGET SELECT NAME, SALES FROM SALESREPS WHERE MANAGER = 104 SELECT CITY, MGR FROM OFFICES WHERE MGR <> 108

DISTINCT KEYWORD
You can eliminate duplicate rows of query results by inserting the keyword DISTINCT in the SELECT statement just before the select list. SELECT DISTINCT MGR FROM OFFICES;

ORDER BY CLAUSE FOR SORTING ACCORDING TO GIVEN COLUMN


You can ask SQL to sort the results of a query by including the ORDER BY clause in the SELECT statement. // ASCENDING ORDER SELECT CITY, REGION, SALES FROM OFFICES ORDER BY REGION, CITY CITY REGION SALES ---------------------------Atlanta Eastern $367,911.00 Chicago Eastern $735,042.00 New York Eastern $692,637.00 Denver Western $186,042.00 Los Angeles Western $835,915.00

//DESCENDING ORDER SELECT CITY, REGION, SALES FROM OFFICES ORDER BY SALES DESC CITY REGION SALES ---------------------------Los Angeles Western $835,915.00 Chicago Eastern $735,042.00 New York Eastern $692,637.00 Atlanta Eastern $367,911.00 Denver Western $186,042.00

BETWEEN CLAUSE
SQL provides a different form of search condition with the range test by using BETWEEN SELECT CITY, NAME, QUOTA FROM OFFICES WHERE SALES BETWEEN 4095 AND 12000 SELECT ORDER_NUM, AMOUNT FROM ORDERS WHERE AMOUNT BETWEEN 20000.00 AND 29999.99 The negated version of the range test (NOT BETWEEN) checks for values that fall outside the range, as in this example: SELECT ORDER_NUM, AMOUNT FROM ORDERS WHERE AMOUNT NOT BETWEEN 20000.00 AND 29999.99

IN CLAUSE
Another common search condition is the set membership test by using IN

SELECT * FROM OFFICES WHERE CITY IN (DELHI,MUMBAI,CHENNAI);


SELECT NAME, QUOTA, SALES FROM SALESREPS WHERE REP_OFFICE IN (11, 13, 22)

LIKE KEYWORD
A simple comparison test can be used to retrieve rows where the contents of a text column match some particular text. The percent sign (%) wildcard character matches any sequence of zero or more

characters. SELECT COMPANY, CREDIT_LIMIT FROM CUSTOMERS WHERE COMPANY LIKE 'Smith%; The underscore (_) wildcard character matches any single character. SELECT COMPANY, CREDIT_LIMIT FROM CUSTOMERS WHERE COMPANY LIKE 'S_ith;

AVG FUNCTION TO GET AVERAGE OF GIVEN COLUMN


SELECT AVG(SALES) FROM OFFICES WHERE REGION = 'East'

SUM FUNCTION TO GET SUM OF GIVEN COLUMN


SELECT SUM(SALES) FROM OFFICES;

FINDING EXTREME VALUES ( MIN AND MAX )


SELECT MIN(SALES), MAX(SALES) FROM OFFICES;

The COUNT ( ) column function counts the number of data values in a column.
SELECT COUNT (CUST_NUM) FROM CUSTOMERS;

SQL supports a special COUNT(*) column function, which counts rows rather than data values.
SELECT COUNT(*) FROM ORDERS;

Joins (Equi-Joins)
The process of forming pairs of rows by matching the contents of related columns is called joining the tables. The resulting table (containing data from both of the original tables) is called a join between the two tables. (A join based on an exact match between two columns is more precisely called an equi-join. SELECT ORDER_NUM, AMOUNT, COMPANY, CREDIT_LIMIT

FROM ORDERS, CUSTOMERS WHERE CUST = CUST_NUM

Joins with Row Selection Criteria


SELECT CITY, NAME, TITLE FROM OFFICES, SALESREPS WHERE MGR = EMPL_NUM AND TARGET > 6000

Non-Equi Joins
The term join applies to any query that combines data from two tables by comparing the values in a pair of columns from the tables. Although joins based on equality between matching columns (equi-joins) are by far the most common joins, SQL also allows you to join tables based on other comparison operators. Here's an example where a greater than (>) comparison test is used as the basis for a join: SELECT NAME, QUOTA, CITY, TARGET FROM SALESREPS, OFFICES WHERE QUOTA > TARGET

GROUP BY Clause
The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according to one or more columns. For Example: If you want to know the total amount of salary spent on each department, the query would be:
SELECT dept, SUM (salary) FROM employee GROUP BY dept;

The output would be like: dept Electrical Electronics Aeronautics InfoTech salary 25000 55000 35000 30000

Multiple Grouping Columns SELECT location, dept, SUM (salary) FROM employee GROUP BY location, dept;

The output would be like: location Bangalore Bangalore Mysore Mangalore dept salary Electrical 25000 Electronics 55000 Aeronautics 35000 InfoTech 30000

Group Search Conditions (HAVING Clause)


Just as the WHERE clause can be used to select and reject the individual rows that participate in a query, the HAVING clause can be used to select and reject row groups. SELECT REP, AVG(AMOUNT) FROM ORDERS GROUP BY REP HAVING SUM(AMOUNT) > 30000

Sub queries
A sub query is a query-within-a-query. Sub query or Inner query or Nested query is a query in a query. A sub query is usually added in the WHERE Clause of the sql statement. SELECT CITY FROM OFFICES WHERE TARGET > (SELECT SUM(QUOTA) FROM SALESREPS WHERE REP_OFFICE = OFFICE SELECT NAME FROM SALESREPS WHERE QUOTA >= (SELECT TARGET FROM OFFICES WHERE CITY = 'Atlanta')

STORED PROCEDURES
A stored procedure is one or more SQL commands stored in a database as an executable object. Stored procedures can be called interactively, from within client application code, from within other stored procedures, and from within triggers. Parameters can be passed to and returned from stored procedures to increase their usefulness and flexibility. A stored procedure can also return a number of result sets and a status code.

A Stored Procedure That Returns Book Titles and the Names of the Authors Who Wrote Them
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END;

Вам также может понравиться