SQL(Structured Query Language ) is a standard language for accessing and manipulating
databases.
SQL commands are used to create ,retreivw and manipulate database from RDBMS
(Relational Database Management System)
Features of SQL
1. It can retrieve data from a database through query processing.
2. It can insert records in a database.
3. It can update records in a database.
4. It can create new records in a database and modify the existing ones.
5. It can create new tables in a database.
6. It can create views in a database.
7. It can allow modifying security settings for the system.
Advantages of SQL
1. Ease of Use
2. No coding required
3. Portable
4. SQL is not case sensitive
5. Large volume of database can be handled quite easily
6. Powerful language
7. Reliable
Classification of SQLStatements are divided into four parts
DDL(Data Definition Language) To create database and table structure-commands like
CREATE(DB) , CREATE(TABLE,),USE,(open )ALTER , DROP etc.
DML (Data Manipulation Language) Record/rows related operations.commands like SELECT....,
INSERT..., DELETE..., UPDATE.... etc.
DCL (Data Control Language) Used to control the transactions.commands like COMMIT,
ROLLBACK, SAVEPOINT etc.
Transactional control Language. used to manipulate permissions or access rights to the
tables.commands like GRANT , REVOKE etc
SQL Datatypes
It is classified into 3 types
1. Numeric
2. Non-Numeric
3. Date-time
Numeric types are
a. Interger (int)
b. Decimal(x,y) where x is the size of the number and y is the precision of the digit
Ex Salary DECIMAL(5,2) salary 500.45
Non-Numeric Types
c. Character (char)
Ex: Name CHAR( 10)
d. Variable character( Varchar(x) )
Ex Name varchar(10)
e. Date Date
Ex: yyyy/mm/dd format we have to follow
2005/09/30
f. Time Time
Ex: hh:mm:ss
12:30:25
What is constraints?
A constraint is a condition or check applicable on a field or a set of fields
Creating Table with Constraints
The following constraints are commonly used in SQL:
NOT NULL -It Ensures that a column cannot have a NULL value
UNIQUE - It Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in
a table
FOREIGN KEY - It Uniquely identifies a row/record in another table
CHECK - It Ensures that all values in a column satisfies a specific condition
DEFAULT - It Sets a default value for a column when no value is specified
SQL Statements
A statement or command is a combination of two or more clauses.
Sql statements are not case sensitive
Sql statements ends with a semicolon
DDL statements
1. Show Database: checking whether database exists or not
Syntax
mysql> show databases;
2. Create Database: creating a database
Syntax
mysql> create database <database name>;
Ex: create school;
3. Open Database:opening a database
Syntax
mysql>USE <databasename>;
Ex: USE school;
4. Removing Database :
Syntax
mysql>Drop database <databasename>;
Ex: Drop database school;
5. CREATE TABLE
Syntax
mysql>CREATE TABLE<tablename> (Colname<data type>(size),
column<datatype>(size)...);
6. Show Table
mysql> show tables;
7. Show Table structure
mysql>Describe <table name> ;
mysql>desc tablename;
CREATE TABLE IF NOT EXISTS TABLENAME(COL, DATATYPE(SIZE),.......)
1. Drop Table: delete table from database
Syntax: DROP TABLENAME;
Syntax DROP TABLE IF EXIST TABLENAME;
Eg: drop student;
2. Alter Table: This command is used to add,delete,modify column,datatype and
constraints
A) Add column:
Syntax: Alter table tablename ADD COLUMN-NAME datatype;
Eg: ALTER TABLE STUDENT ADD SECTION CHAR(1);
B) Drop column:
Syntax: Alter table tablename DROP column COLUMN-NAME;
EG: ALTER TABLE STUDENT DROP COLUMN SECTION ;
C) Modify column datatype:
Syntax: Alter table tablename MODIFY COLUMN-NAME datatype;
Eg: ALTER TABLE STUDENT MODIFY MARK (89.5);
D) Delete a constraint:
Syntax: Alter table table_name DROP COLUMN-NAME <CONSTRAINT>
ALTER TABLE STUDENT DROP ROLL NO PRIMARY KEY;
E) ALTER TABLE table_name(parent) ADD CONSTRAINT
column_name FOREIGN KEY(column_name) REFERENCES
child_tablename (child_column_name );
Ex:
RENAME COLUMN NAME
ALTER TABLE TABLENAME CHANGE OLD COLUMNNAME NEW COLUMNNAME DATATYPE
(SIZE);
ALTER TABLE STIUDENT CHANGE COLUMN GENDER AGE INT;
7. Rename Table: used to rename a table
Syntax: RENAME OLD TABLE-NAME TO NEW TABLE-NAME;
Eg: Rename student to stud;
8. VIEWING TABLE
SYNTAX: DESCRIBE TABLENAME; or
DESC TABLENAME;
Eg: desc student; or
Describe student;
9. Shows the table structure
SYNTAX: SHOW tables;
10*. CREATE TABLE FROM EXISTING TABLE
CREATE TABLE TABLENAME AS
(SELECT COLUMN name ,
COLUMN name FROM TABLE-NAME WHERE COLUMN-NAME[CONSTRAINT]) ;
DML(Data manipulation Language): Data to be changed in the table
1. Inserting Data into Table
Syntax: INSERT INTO TABLENAME[COLUMN-LIST] VALUES(VALUE1,VALUE2….);
Eg: INSERT INTO Employee (ecode,ename,sex,grade,sal)
VALUES (101,’Ravi’,’M’ ,”E4’, 4670.00)
OR
INSERT INTO tablename values(val1,val2……);
2. Selected columns
Syntax: INSERT INTO tablename [COLUMN-LIST]
VALUES(val1,val2…..)
3. INSERTING NULL VALUES
4. INSERTING dates ‘yyyy/mm/dd’
5. UPDATE data in table
Syntax : UPDATE table-name SET columnname=value,column-name=value
WHERE <column-name=existing value or expression>;
Eg: UPDATE items SET ROL=400, QOH=700
WHERE ROL=300
Eg: UPDATE employee SET gross= gross*2
Where (grade =’E3’ Or grade=’E4’);
APPY COMMIT after making changes to your table
6. Delete the Rows
Syntax : DELETE FROM table-name WHERE Column-name=EXPRESSION OR VALUE;
Eg: DELETE FROM EMPLOYEE WHERE GROSS <220;
Delete the whole contents DELETE FROM EMPLOYEE;
7. SELECT: items can be viewed/selected from the table
Syntax: SELECT column-name1 ,columnname2….. FROM table-name;
7.1 Selecting all columns
Select * from table-name;
7.2 Select the column name in any order and the display will be also like that
7.3 Remove the duplicate data using DISTINCT keyword with SELECT statement.
SELECT DISTINCT (NAME ) FROM EMPLOYEE;
7.4 Selecting specific rows using WHERE clause
Syntax: SELECT column-name1 ,columnname2….. FROM table-name
WHERE condition;
7.5 Selecting specific rows using WHERE clause
Syntax: SELECT column-name1 ,columnname2….. FROM table-name
WHERE condition;
7.6 Using relational Operator AND Logical operator
SELECT * FROM EMPLOYEE WHERE DEPT=’IT’ AND EMPNO<> 005;
7.7 CONDITION based on range BETWEEN……... AND
Select rollNo from student where mark between 50 and 60;
7.8 Condition Based on pattern ---WILD CHARACTERS(% character matches any
substring)
(_) (UNDERSCORE) MATCHES ANY ONE CHARACTER
Select rollNo from student where NAME LIKE ‘%S’;
7.9 Condition based on a List _____IN & NOT-IN
IN finds rows that match in the list for the columns from the table
& NOT IN that does not match
Select * from students where STREAM IN (‘SCIENCE’, ‘COMMERCE’,’HUMANITIES’)
Select * from students where STREAM NOT IN (‘SCIENCE’,
‘COMMERCE’,’HUMANITIES’)
Searching for NULL
Select empno,ename from employee where deptno is null;
SQL provides a large collection of in-built function also called as library function that can be
used directly with SQL statements for performing calculations on data known as
Relational operator
=,>,<,>=,<= <>
Logical operator
OR -|| ,AND (&&) ,NOT(!)
AGGREGATE FUNCTIONS
Aggregate functions
Aggregate functions returns a single value calculated from
a group of values for the query.
AVG(colname):
1. SELECT AVG(colname) FROM tablename where condition;
Ex: SELECT AVG(MARK) FROM STUD WHERE STREAM=’SCIENCE’;
SELECT ,AVG(MARK) as Average FROM STUD ;
2. MIN(colname): SELECT MIN(colname/Distinct colname) FROM
tablename where condition(optional);
3. MAX(colname): SELECT MAX(colname/Distinct colname) FROM
tablename where condition(optional);
4. COUNT(colname): SELECT COUNT(colname/Distinct colname) FROM
tablename where condition(optional);
I. count(*)- All
ii. count(distinct colname)- duplicate values read as one
Difference between Count(*) and Count(Column_name)
Count(*): It counts all the rows, including those where all the
column values are null. It essentially counts the number of
records in the table.
Ex: SELECT COUNT(*) FROM table_name;
Count(col_name): This counts the number of non-null values
in the specified column. It does not count rows where the
value of the specified column is null.
Ex: SELECT COUNT(column_name) FROM table_name;
5. SUM(colname): SELECT SUM(colname/Distinct colname )
FROM tablename where condition(optional);
8. ORDER BY column_name[Ascending or descending order]
where condition(optional);
Select colname /colnames from tablename where
<condition> ORDER BY colname /colnames;
Ex: Select * From Employee Order By Grade Desc, Ename
Asc;
Select * From Employee where sal >5000
Order By Ecode ;
Performing Simple Calculation
Select 10*2;
Select empname,Sal*10;
CONSTRAINTS
Syntax
1. FOREIGN KEY CONSTRAINTS
CREATE TABLE TABLENAME(column datatype PRIMARY KEY,column
datatype,column datatype,FOREIGN KEY(colname) REFERENCES
CHILD_TABLENAME (COLNAME),column datatype );
OPTIONAL [ON DELETE CASCADE ON UPDATE CASCADE ]
2. CHECK CONSTRAINT
CREATE TABLE<tablename> (Column name<data type>(size), column name
<datatype>(size)...CHECK(COLUMNNAME<condition>);
3. DEFAULT CONSTRAINT
CREATE TABLE<tablename> (Column name<data type>(size), column name
<datatype>(size)..DEFAULT ‘DEFAULT NAME’);
MY SQL FUNCTIONS
1.STRING FUNCTIONS
Functions Descriptions ex:
CHAR() Returns the character for
each integer passed
CONCAT() Returns concatenated string
LOWER() Returns the argument in
lower case
UPPER() Returns to uppercase
TRIM() Removes the leading and
Trailing spaces
LENGTH() Returns the length of the
string
2. NUMERIC FUNCTIONS
MOD() Returns the remainder
POW() Returns the power to a value
ROUND() Returns the numeric expression
Rounded to an integer
SQRT() Returns the square -root of
numeric expression
TRUNCATE() Returns the truncated value
3. DATE & TIME FUNCTION
DATE()
NOW()
YEAR()