Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

SQL_Queries_2

Uploaded by

anilkoranga.pc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SQL_Queries_2

Uploaded by

anilkoranga.pc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

After covering all the clauses, let us now summarize the usage of SELECT:

SELECT column list


From <table name>
Where <predicate>
Group By <column name>
Having <search condition>
Order By <column name>
Scalar Expression with Selected Fields:
In SQL we can place scalar expression and constant among the selected fields.
If value in the expression is NULL then result of expression will be NULL only.
The operators used in arithmetic expressions are plus (+), minus (-), divide (/), multiply(*), and
modulo (%).
Example : SELECT ename, sal+ 20 FROM emp ;
Above statement add 20 to every row of column sal
Using Column Aliases:
Using column alias name we can give a different name to a columns for output purposes.
If alias name contains more than one word, than we have to enclose them in quotes.
Syntax: SELECT <columnname> [columnalias] [, <columnname> [columnalias] ] …….
FROM <tablename> ;
Example : SELECT ename “Emp_Name”,
job “Emp Post” FROM emp ;
Above statement give columns ename as Emp Name and Job alias name Emp Post.
Putting Text in the Query Output:
SQL enables us to putting some items as symbols and comment in the output.
We can insert text in our query also, to making it more
presentable.
Example :
SELECT ename, ‘gets the salary’, sal+ 20, ‘/-’
FROM emp ;
Creating Table from Existing Table:
By using SELECT statement with CREATE TABLE we can define table and put data into it
without going through the usual data definition process..
The new table stores the result produced by the SELECT statement.
The name of the new table must be unique..
Example: CREATE TABLE emp_info AS
( SELECT eno, ename
FROM emp
WHERE eno > 122 );
Above statement create a new table called emp_info that stores two columns: eno and ename for the
employees that have eno grater than 122 in relation emp.
Modifying Data with UPDATE Command:
UPDATE command is used for change some or all of the values in existing row.
The UPDATE command specifies the rows to be changed using the WHERE clause, and the new
data using
the SET keyword. Update table SET col=new_value where
Example: UPDATE emp
SET sal = 1500
WHERE sal = 1100;
Above statement change sal to 1500 only for that employees that have sal as 100.
A. Updating Multiple Columns:
To update multiple columns, multiple column assignment can be specified with SET clause,
separated by
commas.
Example: UPDATE emp
SET sal = 1500, comm = 200
WHERE eno < 122 ;
Above statement change sal to 1500 and comm to 200 for employees having eno less than 122.

B. Updating to NULL Values:


The NULL values can also be entered just as other values by using UPDATE command.
Example: UPDATE emp
SET comm = NULL
WHERE eno = 147 ;
Above statement insert a NULL values to column comm for employees that have eno as 147.
C. Using Expression in Update:
Scalar expression can be used in the SET clause of the UPDATE command.
Example: UPDATE emp
SET sal = sal * 2
WHERE ( eno = 115 OR eno = 126 ) ;
Above statement double the salary of employees having eno 115 or 126.
9. Deleting Data with DELETE Command:
The DELETE command removes rows from a table.
Removes the entire rows, not individual field values.
No field argument is needed or accepted.
Syntax: DELETE FROM <tablename>
[ WHERE <predicate> ] ;
Example : DELETE FROM emp;
Above statement removes all the contents of emp table.
Some specific rows can also be deleted by using condition as shown below:
Example : DELETE FROM emp
WHERE sal < 1500 ;
Above statement removes all the rows from emp table that have sal less than 1500.
Query Based on Two table (Join):
If we have 2 tables which are related to each other via a column having some or all identical values
(in tables below emp and emp_details have column Id which have some common values ie
1001,1003,1005,1009)
SELECT <Column-list>
FROM <table_name1>,<table_name2>
WHERE <Join_condition>[AND condition];
Table emp:
Id Designation name Salary

1002 Manager Alok 40000

1001 Clerk Kamal 30000

1003 Manager Lait 45000

1005 Peon Deepak 20000

1010 Clerk Pankaj 32000

1009 Clerk Harish 30000

Select emp.Id, name, address from emp,emp_detail where emp.Id=emp_detail.Id


Table Emp_detail
Id Address Phone

1001 Nainital 9991110000

1008 Haldwani 9991110121

1003 Rudrapur 9991110322

1005 Haldwani 9991110678

1011 Rudrapur 9991110129

1009 Haldwani 9991110987

Now for the common Id we can join the data from 2 tables:
Select Emp.ID,name, salary ,address, phone from emp, emp_detail where emp.Id=
emp_detail.Id
Will give
Name Salary Address Phone

Kamal 30000 Nainital 9991110000

Lait 45000 Rudrapur 9991110322

Deepak 20000 Haldwani 9991110678

Harish 30000 Haldwani 9991110987

This will match Id in both the tables and give name, salary, address and phone for rows having same
Id in both tables. As Id 1001 is common it took name kamal and salary 30000 from emp table and
corresponding Id 1001 from emp_detail gave Address Nainital and Phone 9991110000, likewise for
Id 1003, 1005 and 1009 as these Id are common in both tables. No data will be given for Id which are
not common.
If we want to give Id also in output then as Id column is present in both the tables so for common
column we should write table_name.Column
Select E.Id, E.name, salary ,ED.address, phone from emp E, emp_detail ED where E.Id = ED.Id
Will give following output:
Id Name Salary Address Phone

1001 Kamal 30000 Nainital 9991110000

1003 Lait 45000 Rudrapur 9991110322

1005 Deepak 20000 Haldwani 9991110678

1009 Harish 30000 Haldwani 9991110987

CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or
more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the
data were coming from one single table.

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ... FROM table_name
WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
SQL statement, every time a user queries a view.
create a View named DetailsView from the table StudentDetails.
Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
Some More DDL Commands:
ALTER TABLE Command:
The ALTER TABLE command is used to change definition of existing tables.
ALTER TABLE is used:
To add a column
To add an integrity constraint
To redefine a column (datatype, size, default value).
A. Adding Columns:
The new column will be added with NULL values for all rows currently in the table.
Several new columns can be added, separated by commas, in a single command.
It may be possible to drop or alter columns.
Syntax: ALTER TABLE <table name> ADD <column name> <data type><size> [ <constraint
name>] ;
Example: ALTER TABLE emp
ADD ( Ph_no integer) ;
Above statement add a new column Ph_no of type integer in table emp.
B. Changing a Column Name:
For changing the name of the column CHANGE clause of ALTER TABLE command is used.
Syntax: ALTER TABLE
CHANGE [ COLUMN ] old_col_name new_col_name column_defination;
Example: ALTER TABLE emp
CHANGE Sal Salary DECIMAL ;
Above statement change the existing column namely Sal of table emp to Salary.
C. Modifying Column Definition:
By using the MODIFY clause we can change any of the following parts of a column definition:
Datatype:We can change any column’s datatype if all rows for the column contains nulls.
Default value: We can decrease any column’s size if all rows for the column contains nulls
whereas we can always increase the size or the precision of a column.
Integrity Constraint: By using the MODIFY clause we can add only NOT NULL constraint to an
existing column.
Order of column: With MODIFY clause we can reorder the columns within a table by using
FIRST or AFTER<colname> clause.
Syntax: ALTER TABLE <table name>
MODIFY (column name newdatatype (newsize) ) [ FIRST | AFTER column] ;
Example: ALTER TABLE emp
MODIFY ( Job char(30) ) ;
Above statement modify column Job of table emp to have new width of 30 characters.
ALTER TABLE dept
MODIFY Dname Char FIRST ;
Above statement reorder an existing column say Dname to be the first column in the table Dept.
D. Modifying Column Definition:
To remove a component of a table, DROP clause of ALTER TABLE is used.
Keywords mostly used with DROP clause of ALTER TABLE command are as following:
PRIMARY KEY – Drops the table’s primary key constraint.
COLUMN <columnname> – Remove mentioned column from the table.
Example: ALTER TABLE dept
DROP PRIMARY KEY , DROP FOREIGN KEY fk_1, DROP COLUMN dno;
Above statement removes the primary key, the foreign key constraint namely fk_1, and the column
namely dno from the Dept table.
The DROP TABLE Command:
The DROP TABLE command is used for drop a table from the database.
Syntax: DROP TABLE [IF EXISTS] <tablename> ;
Example: DROP TABLE dept;
Above statement drop the table namely Dept from the database.
The IF EXISTS clause first checks whether the given table exists in the database or not.
Example: DROP TABLE IF EXISTS emp;
The DROP VIEW Command:
Used for delete a view from database.
When view is dropped it does not cause any change in its base table.
Example: DROP VIEW taxpayee ;
Above statement drops the view taxpayee from the database.
Introduction to Constraint:
A Constraints is a condition or check applicable on a field or set of fields.
Constraints are also known as integrity constraints because they applied to maintain data integrity
Different Constraints:
Following are the different constraints in MySQL:
NOT NULL, UNIQUE, PRIMARY KEY, DEFAULT, CHECK, FOREIGN KEY
1. 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.
Example: CREATE TABLE emp
( Eno integer NOT NULL, Ename char(20) NOT NULL,
Job char(20) NOT NULL, Salary decimal );
The above table enforces the Eno column and the Ename column to not accept NULL values.
2. UNIQUE Constraint:
This constraint ensure that no two rows have the same value in the specified columns.
When applied to the columns ensure that there cannot exist more than one NULL value in the
column.
Example: CREATE TABLE emp
( Eno integer NOT NULL UNIQUE, Ename char(20) NOT NULL,
Job char(20) NOT NULL,
Salary decimal );
Two or more constrains can be applied in a column as Eno in above case.
3. Primary Key Constraint:
Only one column or one combination can be applied in this constraint.
The primary key cannot allow NULL values, thus this constraints must be applied to columns
declared as NOT NULL.
Example: CREATE TABLE emp
( Eno integer PRIMARY KEY , Ename char(20) NOT NULL,
Job char(20) NOT NULL,
Salary decimal );
4. Default Constraint:
A default value can be specified for a column using the DEFAULT clause.
When a user does not enter a value for the column, automatically the defined default value is
inserted in field.
A column can have only one default value.
Example: CREATE TABLE emp
( Eno integer NOT NULL PRIMARY KEY , Ename char(20) NOT NULL,
Job char(20) DEFAULT = ‘CLERK’, Salary decimal );
Here, if no value is provided for job, the default value of ’CLERK’, will be entered.
5. Check Constraint:
This constraint limits values that can inserted into a column of table.
Example: CREATE TABLE emp ( Eno integer NOT NULL PRIMARY KEY ,
Ename char(20) NOT NULL,
Job char(20) NOT NULL, Salary decimal CHECK > 2000 );
This statement ensure that the value inserted for salary must be greater than 2000.
When a check constraint involves more than one column from the same table, it is specified after
all the column have been defined.
Applying Table Constraints:
When a constraint is to be applied on a group of columns of a table, it is called table constraint.
The table constraint appear in the end of the definition.
Example: CREATE TABLE items ( icode char(5) NOT NULL , descp char(20) NOT NULL,
ROL integer, QOH integer,
CHECK (ROL < QOH),
PRIMARY KEY (icode, descp) );
The above statement define a primary key that have two columns namely icode and descp. It also
ensures that the ROL must be less than QOH in each row.
Referential integrity refers to the accuracy and consistency of data within a relationship. In
relationships, data is linked between two or more tables through primary key and foreign key. They
are linked such that ,if you change or delete a row in one table, you destroy the meaning of rows in
other table
For example, the following figure shows that the customer_num column of the customer table is
a primary key for that table and a foreign key in the orders and cust_call tables. Customer number
106, George Watson™, is referenced in both the orders and cust_calls tables. If customer 106 is
deleted from the customer table, the link between the three tables and this particular customer is
destroyed.

So referential integrity will prevent users from:

• Adding rows to a related table if there is no associated row in the primary


table.
• Changing values in a primary table that result in orphaned records in a
related table.
• Deleting rows from a primary table if there are matching related rows.

You might also like