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

SQL

Data: Set of information.

Database: Storage where data is stored in the form of tables.

Tables: Set of Fields and Records.


Fields
ID Name Salary City

001 ABC 10000 Bangalore 1 Record


002 XYZ 20900 Mysore

DBMS: Database Management System. (Managing the data).

Collections of programs that enable users to store, modify and


extract information from the database.

RDBMS:

 RDBMS is a DBMS that is based on the relation model as introduced


by EF.codd

 It is basis for all modern database system like My sql, Ms sql, Ms


access, Oracle, IBM DB2.

 Database relationship in the form of tables also known as relations.

 Object oriented relation DBMS:- The data to be stored in the form of


objects.
(Have attributes and methods) Ex: Postgre SQL

SQL

1. SQL is a standard language for storing, manipulating and retrieving


data in database.
2. SQL is just a query language, it is not a DB. To perform any queries
you need to install any DB Es. Oracle, MySQL.
3. It is designed for managing data in a relational database
management system (RDBMS).
4. It is pronced as See-Qwell.
Why SQL is required?

SQL is required to:

1. Create new Database, tables and views


2. Insert record in a Database
3. Update record in a Database
4. Delete record in a Database
5. Retrieve record in a Database

What SQL DOES?

1. With SQL we can query our database in a nos of ways.


2. With SQL user can access data from RDBMS.
3. It allow user to describe the data
4. It allow user to define the data in database and manipulate it when
needed.
5. It allow user to create and drop database and table
6. It allow user to create view, stored procedure, function in a
database.
7. It allow user to set permission on table, procedure and view.

Difference between DBMS and RDBMS

DBMS RDBMS
DBMS application store data RDBMS application store data in
as File a Tabular Form
Normalization is not present Normalization is present
It doesn’t support distributed It support distributed database
database
DBMS doesn’t apply any security RDBMS defines the integrity
with regards to data manipulation constraint for the purpose of
ACID (Atomicity, Consistency,
Isolation and Durability)
property
DBMS is meant to be for small RDBMS is designed to handle
organization and deal with small large amount of data.
data, it supports single users It supports Multiple data
Ex. File System, XML Ex. My sql, postgres, sql server,
oracle

What are the differences between SQL and PL/SQL?

SQL PL/SQL
SQL is a query execution or PL/SQL is a complete programming
commanding language language
SQL is data oriented language PL/SQL is a procedural language
SQL is very declarative in nature PL/SQL has a procedural nature
It is used for manipulating data It is used for creating applications
We can execute one statement at a We can execute block of statements in
time in SQL PL/SQL
SQL tells database, what to do? PL/SQL tells database how to do
We can embed SQL in PL/SQL We can not embed PL/SQL in SQL

SUB LANGUAGE OF SQL:

1. DDL (Data Definition Language)


2. DML (Data Manipulation Language)
3. DRL/DQL (Retrieval/query)
4. TCL (Transaction Control Language)
5. DCL (Data Control Language)

*DDL: This language is used to manage database objects. It is collection of five


commands.
CREATE, ALTER, DROP, TRUNCATE, RENAME

*DML: This language is used to manipulate the data you have stored. It is
collection of four commands.
INSERT, UPDATE, DELETE, MERGE

*DRL: This language is used to retrieve the data from the database. It is
collection of only one command.
SELECT

*TCL: It is used to maintain the transaction of Oracle database. It is collection of


three commands.
COMMIT, ROLLBACK, SAVEPOINT
*DCL: This language is used to control the axis of the data to the users it is
collection of two commands.
GRANT, REVOKE

Before to Create a Database:

1. open mysql in cmd: mysql -u root -p


2. show databases;
3. if you already created the database if you wanna to use the same
go with :-
4. use databasename (school)

Create a New Database:-

The CREATE DATABASE statement is used to create a new SQL database.

Syntax:- CREATE DATABASE database-name;


Ex:- create database school;

DROP DATABASE Statement:-


The DROP DATABASE statement is used to drop an existing SQL database.
Syntax:-
DROP DATABASE databasename;
Ex:- drop database school;

SQL RENAME DATABASE:-


To Rename Database from old name to new name
Syntax:- RENAME DATABASE old_db_name To new_db_name;

*DDL (DATA DEFINITION LANGUAGE):


DDL is short name of Data Definition Language,which deals with database
schemas and descriptions, of how the data should reside in the database.
1. CREATE - to create a database and its objects like (table, index,
views, store procedure, function, and triggers)
2. ALTER - alters the structure of the existing database
3. DROP - delete objects from the database
4. TRUNCATE - remove all records from a table, including all spaces
allocated for the records are removed
5. RENAME - rename an object

TABLE: Table is an object which is used to store some data. In general it is


collection of Rows and Columns.

CREATE TABLE :
The CREATE TABLE statement is used to create a new table in a database.
Syntax:- CREATE TABLE table_name(
column1 datatype,
column2 datatype,
);
1. The column parameters specify the names of the columns of the
table.
2. The data type parameter specifies the type of data the column can
hold (e.g. varchar, integer, date, etc.).

Ex:- create table student( s_id int(10), s_name varchar(20), s_age int (2));
Note: NOTNULL :- the field cant be empty.

2) ALTER: By using ALTER command we can perform the following task.


1.1. ADDING A NEW COLUMN
1.2. DROPING AN EXISTING COLUMN
1.3. MODIFYING A COLUMN
1.4. RENAMING A COLUMN

ADDING A NEW COLUMN:


i.
Syntax: ALTER TABLE <TABLE_NAME> ADD (COL1_NAME DATA
TYPE(SIZE),
(COL2_NAME DATA
TYPE(SIZE));
Ex: ALTER table student ADD(city varchar2(10));
ALTER table student ADD(state varchar2(10), pincode number(6));
Note: New column can be added only at last.
The new column will have null values.
Update student set city = ‘Hyderabad’ where sno = 101;
Update student set state = ‘Andra pradesh’ where sno = 101;
Update student set pincode = 500082 where sno = 101;

ii. DROPING AN EXISTING COLUMN:


Syntax: ALTER TABLE <TABLE_NAME> DROP(COL1_NAME,COL2_NAME);
Ex: ALTER table student drop(state);
ALTER table student drop(city,pincode);

iii. MODIFYING A COLUMN: (increasing/decreasing the size of columns)


Syntax: ALTER TABLE <TABLE_NAME> MODIFY(COL1_NAME DATA
TYPE(SIZE));
Ex:
ALTER table student modify(Sname varchar2(10));
ALTER table student modify(Sname varchar2(8));
Note: .we can increase and decrease as well as the size of the column.
.We can decrease the column size only when existing column values
can
fit into new size.
.By using modify keyword we can change the data type of a column.
.Column should be empty to change it’s data type.

iv. RENAMING A COLUMN:


Syntax: ALTER TABLE <TABLE_NAME> RENAME
COLUMN<OLD_COL_NAME>
TO <NEW_COL_NAME>;
Ex:
ALTER table emp rename column SAL TO WAGES;

3) DROP: This command is used to rename the table from the database.
Syntax: DROP TABLE <TABLE_NAME>;
Ex:
DROP table student;
DROP table emp;

4) TRUNCATE: This command is used to remove all the rows (only data in the
table will be removed) from the table.
Syntax: TRUNCATE TABLE <TABLE_NAME>;
Ex: TRUNCATE table student;
Select * from TAB; // ALL TABLE NAME’S ARE DISPLAYED

*Difference between TRUNCATE and DELETE?

DELETE TRUNCATE
We can Roll Back the data. We cannot Roll Back the data.
Rows are deleting temporally. Rows are deleting
permanently.
Where clause can be used. Where clause cannot be used.
Delete is sub language DML. Delete is sub language DDL.
Syntax: Delete from table_name ; Syntax:- Truncate table table-name;
or
Delete from table_name
[where condition];

5) Rename: This command is used to change the table name.


Syntax: RENAME <OLD_TABLE_NAME> TO <NEW_TABLE_NAME>;
Ex: Rename student To student1;
Rename SALGRADE To GRADE;

NOTE: When we use a Truncate command the table gets dropped and re-
created. As the structure is effected is called as a DDL command.
All DDL command are permanent.
All DML command are Temporary.
DML is short name of Data Manipulation Language which deals with
data manipulation and includes most common SQL statements such
SELECT, INSERT, UPDATE, DELETE, etc., and it is used to store, modify,
retrieve, delete and update data in a database.
SELECT - retrieve data from a database

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - Delete all records from a database table

MERGE - UPSERT operation (insert or update)

CALL - call a PL/SQL or Java subprogram

EXPLAIN PLAN - interpretation of the data access path

LOCK TABLE - concurrency Control

INSERT :
The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO statement in two ways.
The first way specifies both the column names and the values to be
inserted:
1. INSERT INTO table_name (column1,column2,column3, ...)
VALUES(value1,value2,value3, ...);
2. INSERT INTO table_name
VALUES (value1,value2,value3, ...);
INSERT MULTIPLE ROWS
INSERT INTO student (ID, NAME)
VALUES (1, 'ARMAAN');
INSERT INTO student (ID, NAME)
VALUES (2, 'BILLY');
INSERT INTO student (ID, NAME)
VALUES (3, 'CHARLIE');

Inserting data through SELECT Statement

SQL INSERT INTO SELECT Syntax

INSERT INTO table_name


1.[(column1, column2,....column)]
2.SELECT column1,column2,....Column N
3.FROM table_name [WHERE condition];

SQL UPDATE

The SQL commands (UPDATE and DELETE) are used to modify the data
that is already in the database. The SQL DELETE command uses a WHERE
clause.

SQL UPDATE statement is used to change the data of the records held by
tables. Which rows is to be update, it is decided by a condition. To specify
condition, we use WHERE clause.

Syntax:
UPDATE table_name
SET column_name = expression
WHERE conditions
Example:
UPDATE students
SET User_Name = 'beinghuman'
WHERE Student_Id ='3'

Updating Multiple Fields:


UPDATE students
SET User_Name = 'beserious', First_Name='Johnny'
WHERE Student_Id='3'

SQL SELECT STATEMENT


The SQL SELECT statement is used to fetch the data from a database
table which returns this data in the form of a result table.

Syntax:-

1. SELECT column1, column2, columnN FROM table_name;


2. SELECT * FROM table_name;
Ex:-
1. SELECT ID, NAME, SALARY FROM CUSTOMERS;
2. SELECT * FROM CUSTOMERS;

Optional clauses in SELECT statement


There are some optional clauses in SELECT statement:
[WHERE Clause] : It specifies which rows to retrieve.
[GROUP BY Clause] : Groups rows that share a property so that the
aggregate function can be applied to each group.
[HAVING Clause] : It selects among the groups defined by the GROUP BY
clause.
[ORDER BY Clause] : It specifies an order in which to return the rows.

SQL SELECT UNIQUE


Actually, there is no difference between DISTINCT and UNIQUE.
SELECT UNIQUE is an old syntax which was used in oracle description
but later ANSI standard defines DISTINCT as the official keyword.
After that oracle also added DISTINCT but did not withdraw the service of
UNIQUE keyword for the sake of backward compatibility.

In simple words, we can say that SELECT UNIQUE statement is used to


retrieve a unique or distinct element from the table.

SQL SELECT DISTINCT


The SQL DISTINCT command is used with SELECT key word to retrieve
only distinct or unique data.
In a table, there may be a chance to exist a duplicate value and
sometimes we want to retrieve only unique values. In such scenarios, SQL
SELECT DISTINCT statement is used.

mysql> SELECT DISTINCT s_age FROM student;

SQL SELECT COUNT


The SQL COUNT() function is used to return the number of rows in a
query.
For example: If you have a record of the voters in selected area and
want to count the number of voters then it is very difficult to do it
manually but you can do it easily by using the SQL SELECT COUNT query.

SELECT COUNT (expression)  

1.FROM tables  
2.WHERE conditions;  

SQL SELECT COUNT(column_name)

1. SELECT COUNT(name) FROM employee_table;  

It will return the total number of names of employee_table. But null fields
will not be counted.
SQL SELECT COUNT(*)

1. SELECT COUNT(*) FROM employee_table;  
The "select count(*) from table" is used to return the number of records in
table.

SQL SELECT COUNT(DISTINCT column_name)


1. SELECT COUNT(DISTINCT name) FROM employee_table;  

It will return the total distinct names of employee_table.

The SQL SELECT TOP Clause


The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of
records. Returning a large number of records can impact on performance.
Note: Not all database systems support the SELECT TOP clause. MySQL
supports the LIMIT clause to select a limited number of records, while
Oracle uses ROWNUM.
mysql> SELECT * FROM student LIMIT 3;
+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 10 | devraj | 29 |
| 20 | abc | 19 |
| 11 | tt7f | 78 |
+------+--------+-------+
3 rows in set (0.00 sec)

mysql> SELECT * FROM student LIMIT 10;


+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 10 | devraj | 29 |
| 20 | abc | 19 |
| 11 | tt7f | 78 |
| 11 | tt7f | 78 |
| 101 | xyz | 56 |
| 103 | Anil | 56 |
| 106 | Anand | 16 |
| 200 | abhi | 77 |
| 210 | Bindhu | 747 |
| 110 | abhi | 37 |
+------+--------+-------+
10 rows in set (0.00 sec)

The SQL WHERE Clause


The WHERE clause is used to filter records.
The WHERE clause is used to extract only those records that fulfill a
specified condition.

Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Note: The WHERE clause is not only used in SELECT statement, it is also


used in UPDATE, DELETE statement, etc.!
Example:
mysql> select * from student where s_age=77;
+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 200 | abhi | 77 |
+------+--------+-------+
Operators in The WHERE Clause

Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. 
Note: In some versions of SQL this
operator may be written as !=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values
for a column

The SQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than
one condition:
1. The AND operator displays a record if all the conditions separated
by AND are TRUE.
2. The OR operator displays a record if any of the conditions separated
by OR is TRUE.
3. The NOT operator displays a record if the condition(s) is NOT TRUE.

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
mysql> SELECT * FROM student WHERE s_id='101' AND s_age=56;
+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 101 | xyz | 56 |
+------+--------+-------+
1 row in set (0.00 sec)

mysql> SELECT * FROM student WHERE s_id='101' OR s_age=56;


+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 101 | xyz | 56 |
| 103 | Anil | 56 |
+------+--------+-------+
2 rows in set (0.01 sec)
mysql> SELECT * FROM student WHERE NOT s_age=56;
+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 10 | devraj | 29 |
| 20 | abc | 19 |
| 11 | tt7f | 78 |
| 11 | tt7f | 78 |
| 106 | Anand | 16 |
| 200 | abhi | 77 |
| 210 | Bindhu | 747 |
| 110 | abhi | 37 |
+------+--------+-------+
8 rows in set (0.00 sec)

Combining AND OR &NOT


SELECT * FROM student WHERE s_id=10 AND (s_name='devraj' OR
s_age=20);
+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 10 | devraj | 29 |
+------+--------+-------+
1 row in set (0.01 sec)

mysql> SELECT * FROM student WHERE NOT s_age=56 and not s_id=200;
+------+--------+-------+
| s_id | s_name | s_age |
+------+--------+-------+
| 10 | devraj | 29 |
| 20 | abc | 19 |
| 11 | tt7f | 78 |
| 11 | tt7f | 78 |
| 106 | Anand | 16 |
| 210 | Bindhu | 747 |
| 110 | abhi | 37 |
+------+--------+-------+
7 rows in set (0.00 sec)

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