Anda di halaman 1dari 42

SQL STATEMENTS

SQL statements are divided into the following categories:Data Definition Language (DDL) statements g g ( ) Data Manipulation Language (DML) statements Data Control Language (DCL) statements g g Transaction Control (TCL) statements

Data Definition Language (DDL) g g ( )


It is used to create and modify the structure of y database objects in database It defines the database structure or schema.
CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed COMMENT - add comments to the data dictionary RENAME - rename an object

CREATE
Create database
The CREATE DATABASE statement is used to create a database. CREATE DATABASE database_name

Then use the database.


USE database_name

CREATE
Create table
The CREATE TABLE statement is used to create a table in a database. CREATE TABLE table_name ( column_name1 d l 1 data_type, column_name2 data_type, column_name3 data_type, column name3 data type, .... )

Ques: Create a table called "Persons" that contains five columns: P_Id, LastName, FirstName, Address, and City. CREATE TABLE Persons ( P_Id P Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), Add h (255) City varchar(255) )

ALTER
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. To add a column in a table use the following syntax: table, syntax ALTER TABLE table_name ADD column_name datatype To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting don t a column): ALTER TABLE table_name DROP COLUMN column_name l

DROP
The DROP TABLE Statement The DROP TABLE statement is used to delete a table. DROP TABLE table name table_name

The DROP DATABASE Statement The DROP DATABASE statement is used to delete a database. DROP DATABASE database name database_name

TRUNCATE
What if we only want to delete the data inside the table, and not the table itself? Then, use the TRUNCATE TABLE statement: TRUNCATE TABLE table_name table name

Data Manipulation Language (DML) p g g ( )


It used for managing data within schema objects. It is used to retrieve, store, modify, delete, insert and update data in database database.
SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain MERGE - UPSERT operation (insert or update) CALL - call a PL/SQL or Java subprogram EXPLAIN PLAN - explain access path to data LOCK TABLE - control concurrency

SQL SELECT Statement


The SELECT statement is used to select data from a database. The result is stored in a result table, called the result-set. SELECT column_list FROM table-name [WHERE Clause] [GROUP BY clause] [HAVING clause] [ORDER BY clause]; l ]

SQL INSERT INTO Statement


The INSERT INTO statement is used to insert a new row in e S Osae e s o se ew ow a table. It is possible to write the INSERT INTO statement in two forms. The first form doesn't specify the column names where the data will be inserted, only their values: INSERT INTO table_name bl VALUES (value1, value2, value3,...)

The second form specifies both the column names and the e seco d o spec es bo e co u a es a d e values to be inserted: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)

SQL UPDATE Statement


The UPDATE statement is used to update records in a table. The UPDATE statement is used to update existing records in a table. UPDATE table_name SET column1 value, column2 value2,... column1=value, column2=value2,... WHERE some_column=some_value

SQL DELETE Statement


The DELETE statement is used to delete records in a table. The DELETE statement is used to delete rows in a table. DELETE FROM table_name WHERE some column=some value some_column some_value

Data Control Language (DCL) g g ( )


It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it. y g
GRANT Gives users access privileges to database REVOKE Withdraws users access privileges to database given with the GRANT command

Transactional Control Language g g


It is used to manage different transactions occurring within a database.
COMMIT Saves work done in transactions ROLLBACK Restores database to original state since the last COMMIT command in transactions

SQL ORDER BY
The SQL ORDER BY clause defines in what order to return a data set retrieved with a SQL SELECT statement. This could be in ascending order, in descending order, or could be based on either numerical value or text value value. SELECT "column name" column_name FROM "table_name" [WHERE "condition"] ORDER BY " l "column_name" [ASC, DESC] " [ASC

SQL Aggregate Functions gg g


SQL aggregate functions are used to sum, count, get the average, average get the minimum and get the maximum values from a column or from a sub-set of column values.
1.

COUNT : This allows us to COUNT up the number of row in a certain table. The syntax is,
SELECT COUNT("column name") COUNT( column_name ) FROM "table_name

2. 2

AVERAGE: SQL uses the AVG() function to calculate the average of a column. The syntax for using this function is,
SELECT AVG("column_name") FROM "table name table_name

O_Id 1 2 3 4 5 6

OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04

OrderPrice 1000 1600 700 300 2000 100

Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

SELECTAVG(OrderPrice)ASOrderAverage FROMOrders OrderAverage 950 SELECTCustomerFROMOrders WHEREOrderPrice>(SELECTAVG(OrderPrice)FROMOrders) WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders) Customer Hansen Nilsen Jensen

SELECTCOUNT(Customer)ASCustomerNilsen FROMOrders WHERECustomer='Nilsen CustomerNilsen 2 SELECTCOUNT(*)ASNumberOfOrders FROMOrders NumberOfOrders 6 SELECTCOUNT(DISTINCTCustomer)ASNumberOfCustomers FROMOrders NumberOfCustomers 3

3.

MINIMUM : SQL uses the MIN function to find the maximum value in a column. The syntax for using the MIN function is,
SELECT MIN("column_name") FROM "table_name

4.

MAXIMUM: SQL uses the MAX function to find the maximum value in a column. The syntax for using the MAX f ti i l i l Th t f i th function is,
SELECT MAX("column_name") FROM "table_name

5.

SUM: The SUM function is used to calculate the total for a column. column The syntax is is,
SELECT SUM("column_name") FROM "table_name

SELECTMAX(OrderPrice)ASLargestOrderPrice FROMOrders LargestOrderPrice 2000 SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders SmallestOrderPrice 100 SELECT SUM(OrderPrice) AS OrderTotal FROM Orders OrderTotal 5700

SQL GROUP BY
The SQL GROUP BY clause is used along with the SQL g aggregate functions and specifies the groups where selected rows are placed. WHEN one or more aggregate functions are presented in the SQL SELECT column list the SQL GROUP BY list, clause calculates a summary value for each group. The corresponding SQL syntax is, SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1

SQL HAVING
The SQL HAVING keyword provides a search condition for a group or aggregate. Th SQL HAVING clause works together The l k h with the SQL SELECT clause. The SQL HAVING clause is somewhat similar to the SQL WHERE clause, because it specifies a search condition. There is one important difference between SQL HAVING and SQL WHERE clauses. The SQL WHERE clause condition is tested against each and every row of data, while the SQL HAVING g y , Q clause condition is tested against the groups and/or aggregates specified in the SQL GROUP BY clause and/or the SQL SELECT column list list.

SELECTCustomer,SUM(OrderPrice)FROMOrders GROUPBYCustomer GROUP BY Customer Customer Hansen Nilsen Jensen SUM(OrderPrice) 2000 1700 2000

SELECTCustomer,SUM(OrderPrice)FROMOrders GROUPBYCustomer HAVINGSUM(OrderPrice)<2000 Customer Nilsen SUM(OrderPrice) 1700

SQL AND & OR


Compound conditions are made up of multiple simple conditions connected by AND or OR. There is no limit to the number of simple conditions that can be present in a single SQL statement. The syntax for a compound condition is as follows:

SELECT "column name" column_name FROM "table_name" WHERE "simple condition" {[ {[AND|OR] "simple condition"}+ ] p }

The {}+ means that the expression inside the bracket will occur one or more times. Note that AND and OR can be used interchangeably.

SQL JOIN
SQL Joins are used to relate information in different tables .The SQL JOIN clause selects data from two or more tables tied together by matching table columns. l A Join condition is a part of the sql query that retrieves rows f from two or more tables. bl The Syntax for joining two tables is:

SELECT col1, col2, col3... FROM table_name1, table_name2 WHERE table name1 col2 = table_name2.col1; table_name1.col2 table name2 col1;

SQL Constraints
Constraints are used to limit the type of data that can yp go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).
NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY CHECK DEFAULT

SQL NOT NULL Constraint


By default, a table column can hold NULL values. 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 value. new record, or update a record without adding a value to this field.

The following SQL enforces the "P_Id" column and the g _ "LastName" column to not accept NULL values: CREATE TABLE Persons ( P_Id P Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), Add h (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.

The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons" table is created: CREATE TABLE Persons ( P_Id int NOT NULL UNIQUE, LastName varchar(255) NOT NULL, FirstName varchar(255) varchar(255), Address varchar(255), y ( ) City varchar(255) )

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies q y 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.

The following SQL creates a PRIMARY KEY on the g "P_Id" column when the "Persons" table is created: CREATE TABLE Persons ( P_Id P Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), Add h (255) City varchar(255) )

SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in another table. The following SQL creates a FOREIGN KEY on the "P Id" P_Id column when the "Orders" table is created: CREATE TABLE O d Orders ( O_Id int NOT NULL, OrderNo int NOT NULL NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P Id) REFERENCES Persons(P Id) (P_Id) Persons(P_Id) )

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.

The following SQL creates a CHECK constraint on the "P Id" P_Id column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater th 0 i t t than 0. 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) )

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.

The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created: CREATE TABLE Persons ( P_Id int P Id i NOT NULL NULL, LastName varchar(255) NOT NULL, FirstName varchar(255) varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' )

Query in SQL( Set-I) y ( )


1.

2. 3. 4. 5.

Create the table Student with following field. g Roll no integer, primary key Name Varchar City varchar, city should be only either Gurgaon or Delhi or Noida. Noida Fees integer should not be less than 200 integer, and not greater than 5000. Insert the records into the table. Retrieve the fees for each student from the table. Query the student names who live in Delhi. Retrieve the roll no of students whose fees is between 500 and 1000.

Query contd. ( y (set-2) )


1. 2. 3. 4. 4 5. 6.

Create a table employee with fields Ename(unique),empid(primary key), Salary, dept no., Post no Post. Insert records into the table. Select the employee with the post Engineer Select employee whose post is not manager. manager . Select employee whose post is clerk and empid is either 20 or 40 or 60. Select employee whose salary is >4000 and <9000 Modify the table employee. (a) Add a column for department number. (b) Drop the column post. Drop primary key constraint. Drop the table employee. Delete the records of al the employees that belong to department no.111.

7. 8. 9. 10. 11. 12.